Sub topic 1
What a Stateless Service Is
Prerequisites
This chapter assumes you know the following:
- Basic HTTP: requests, responses, headers and cookies.
- How to build a web service or API in any language.
- What a load balancer does: it spreads incoming requests across several copies of a service.
The working definition
A stateless service keeps no data between requests that it needs to answer the next request correctly. Each request carries, or points to, everything the service needs. Any running copy of the service (an instance) can handle any request and produce the same result.
"Stateless" does not mean the system has no state. Users still have accounts, carts and orders. That data lives somewhere. The rule is about where it lives: not in the memory or local disk of one instance, but in a shared place such as a database, a cache, or the request itself.
A useful test: if you killed an instance between two requests from the same user and a different instance served the second one, would the user notice? If not, the service is stateless in the way that matters.
A stateful example
This Flask handler keeps a counter in a Python dictionary. It works with one process and breaks with two.
from flask import Flask, request
app = Flask(__name__)
cart_counts = {} # lives in this process's memory only
@app.post("/cart/add")
def add_to_cart():
user_id = request.headers["X-User-Id"]
cart_counts[user_id] = cart_counts.get(user_id, 0) + 1
return {"items": cart_counts[user_id]}Suppose a load balancer runs two instances, A and B. A user adds an item and the request reaches A, which stores {"42": 1}. The user adds another item and the request reaches B. B has an empty dictionary, so it answers 1. The cart appears to have lost an item.
The stateless version
The fix is to move the data out of the instance. Here the count lives in Redis, which every instance can reach.
import redis
from flask import Flask, request
app = Flask(__name__)
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
@app.post("/cart/add")
def add_to_cart():
user_id = request.headers["X-User-Id"]
count = r.incr(f"cart:{user_id}") # atomic, shared by all instances
return {"items": count}Now instance A and instance B read and write the same counter. INCR is atomic, so two simultaneous requests cannot both read the same old value and overwrite each other. The handler itself holds nothing between calls, so you can add, remove or restart instances freely.
What an instance may still hold
Statelessness does not forbid all local data. An instance can safely keep data that is:
- Read-only and identical on every instance, such as configuration loaded at startup.
- Disposable, such as a cache that can be rebuilt on a miss, where a stale or missing entry costs speed but not correctness.
- Scoped to a single request, such as variables inside a handler.
The data you must not rely on is anything that, if lost when the instance dies, would change a user's outcome. That includes carts, login state, half-finished uploads and in-progress workflows.
Common errors
- Treating a local cache as the source of truth. If a write goes only to the local cache, other instances never see it and a restart loses it. Write to the shared store first.
- Assuming the same instance serves a user twice. Code that works in development with one process often fails the first time you run two.
- Writing files to local disk and reading them back later. An uploaded file saved to one instance's disk is missing on the others. Use shared object storage instead.
- Hiding state in global variables. Module-level dictionaries, counters and singletons that change at runtime are state, even when they look like code.
Why this matters for what comes next
Because any instance can serve any request, you can scale out by adding instances, replace instances during a deploy, and survive an instance crash without losing user data. The next chapters look at the data that most often breaks this property, which is session state, and at the places you can keep it.
Exercise
A service stores each user's login status in a Python dictionary at module level. It runs as three instances behind a load balancer. Users report being randomly logged out. Explain why, and name one change that fixes it.
Show answer
Each instance has its own dictionary, so a login recorded on one instance is unknown to the other two. When the load balancer sends a later request to a different instance, that instance sees no login and treats the user as logged out. Moving the login data to a store all instances share, such as Redis, fixes it. Every instance then reads the same record.
Exercise
Which of these can an instance keep in local memory without breaking statelessness? (a) a user's shopping cart, (b) configuration read at startup, (c) a cache of product descriptions that can be reloaded from the database on a miss.
Show answer
(b) and (c). Configuration is identical on every instance and read-only. The product cache is disposable because a miss only costs a database read. The shopping cart (a) is user data that would be lost or inconsistent across instances, so it must live in a shared store.