Sub topic 1
What a Stateless Service Is
This chapter defines what "stateless" means for a web service, separates it from nearby ideas, and shows what breaks when a service is not stateless. Later chapters cover where session state can live instead.
Prerequisites
This chapter assumes you know:
- The basics of 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.
You do not need any knowledge of Redis, tokens or cryptography yet. Those appear in later chapters.
The working definition
A service is stateless when it can handle any request using only two things: the data in the request itself, and data it fetches from shared systems such as a database. It keeps nothing between requests that the next request depends on.
The key phrase is "that the next request depends on." A stateless service can still hold memory. A cache of product names, for example, is fine as long as losing it only makes things slower, never wrong. What matters is whether the instance's memory is the only copy of something the system needs.
A useful test: kill any instance at any moment and restart it empty. Does the user notice anything except a slower response? If no, the service is stateless in the sense that matters. If the user is suddenly logged out, loses a half-filled cart or sees an upload fail, the instance was holding state.
State versus statelessness at the system level
"Stateless" describes a service, not an application. Every useful application has state: user accounts, orders, sessions. Making a service stateless does not remove that state. It moves it to a place that all instances can reach and that is designed to keep data safely, such as a database, a cache cluster or the client.
- Stateful service: the instance owns data. Requests must reach the right instance.
- Stateless service: the instance owns nothing durable. Any instance can serve any request.
Stateless is not the same as HTTP being stateless
HTTP itself is stateless: each request is independent, and the protocol has no memory of earlier requests. Cookies, sessions and tokens exist to add continuity on top of it. A web application is therefore only as stateless as the way it stores that continuity. A service that keeps a Python dictionary of logged-in users in process memory uses a stateless protocol but is itself stateful.
A stateful example
The following Flask-style handler stores login data in a module-level dictionary. It runs, and it works with exactly one instance.
import secrets
from flask import Flask, jsonify, make_response, request
app = Flask(__name__)
# State held in this process's memory only.
SESSIONS: dict[str, dict] = {}
@app.post("/login")
def login():
user_id = request.json["user_id"]
session_id = secrets.token_urlsafe(32)
SESSIONS[session_id] = {"user_id": user_id}
resp = make_response(jsonify(ok=True))
resp.set_cookie("sid", session_id, httponly=True)
return resp
@app.get("/me")
def me():
session = SESSIONS.get(request.cookies.get("sid", ""))
if session is None:
return jsonify(error="not logged in"), 401
return jsonify(user_id=session["user_id"])With one process, a user logs in and then calls /me successfully. Now run two copies behind a load balancer that alternates between them (round robin).
The user did nothing wrong, yet they appear logged out. The bug is intermittent: it depends on which instance each request lands on, so it often passes testing on a laptop and fails in production.
Failure modes of instance-local state
Local state causes several distinct problems. They share a root cause: the instance's memory is the only copy.
| Situation | What happens with local state |
|---|---|
| Load balancer rotates requests | The request lands on an instance that has no record of the user |
| Instance crashes | All sessions held by that instance are lost |
| Rolling deploy replaces instances | Users on replaced instances are logged out, one batch at a time |
| Autoscaler removes an instance during a quiet period | Active users on it lose their sessions |
| New instance added during a spike | It starts empty and receives traffic from users it knows nothing about |
The deploy case deserves attention. With a rolling deploy, instances are replaced one by one. If each holds sessions, every release logs out some fraction of your users. Teams respond by deploying rarely or at night, which is a sign that state is constraining how the system operates.
What a stateless version looks like
The fix does not need to be elaborate. Move the data out of the process and into something shared. The sketch below keeps the same routes but reads and writes sessions through Redis.
import json
import secrets
import redis
from flask import Flask, jsonify, make_response, request
app = Flask(__name__)
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
SESSION_TTL_SECONDS = 1800
@app.post("/login")
def login():
user_id = request.json["user_id"]
session_id = secrets.token_urlsafe(32)
r.set(f"session:{session_id}", json.dumps({"user_id": user_id}), ex=SESSION_TTL_SECONDS)
resp = make_response(jsonify(ok=True))
resp.set_cookie("sid", session_id, httponly=True, max_age=SESSION_TTL_SECONDS)
return resp
@app.get("/me")
def me():
data = r.get(f"session:{request.cookies.get('sid', '')}")
if data is None:
return jsonify(error="not logged in"), 401
return jsonify(user_id=json.loads(data)["user_id"])Any instance can now serve /me, because every instance reads the same Redis. You can kill and replace instances freely. The application still has session state; the service no longer holds it. Chapter by chapter, the tutorial returns to this idea and compares other places the state can go.
Common misunderstandings
"Stateless means no database"
It does not. Stateless services usually talk to databases constantly. The database is the shared place where state lives. The property is about the service instances, not about the system as a whole.
"Stateless means no cache"
A local cache is allowed if it is disposable and safe to be out of date. Two risks to check:
- Staleness across instances. Instance A caches a user's role, an administrator changes it, and instance B reads the new value. For a short time, different instances give different answers. Decide whether that is acceptable and set a short expiry if it is.
- Cold start. A new instance with an empty cache sends a burst of traffic to the database. This is a performance concern, not a correctness one, but it can still cause an outage if the database cannot absorb it.
"Stateless means no sessions"
Sessions are a feature of the application. You can keep them and still run a stateless service by storing them outside the instance or in the client. That choice is the subject of the rest of this tutorial.
"Stateless means every request carries everything"
That is one design, used by signed tokens. Another design sends only an identifier and looks the rest up in shared storage. Both are stateless from the instance's point of view. They differ in cost, revocation and failure behavior, which later chapters compare.
Edge cases to watch for
Sessions are the most visible example of instance-local state, but they are not the only one. Check these when you review a service:
- Files written to local disk. Uploads saved to the instance's disk are invisible to other instances and disappear when the instance is replaced.
- In-memory counters. A rate limit of 100 requests per minute enforced per instance becomes 100 times the number of instances.
- Scheduled jobs inside the app. A timer in every instance runs once per instance, so a "send daily email" job sends several emails.
- In-process locks. A lock held in memory protects against threads in one process, not against other instances.
- WebSocket or streaming connections. A long-lived connection is tied to one instance by nature. Messages for that user must be routed to it, usually through a shared message bus.
A later chapter in this tutorial treats these in more detail. For now, the pattern to remember is the one in the kill-and-restart test: if the data matters after the instance is gone, it does not belong only in that instance.
Costs and trade-offs
Statelessness is a design choice with costs, not a free upgrade.
- Extra network hops. A lookup in shared storage takes a round trip, typically a fraction of a millisecond to a few milliseconds within one data center. Local memory is faster.
- New dependencies. The shared store must be available, secured, backed up where needed and sized for the load.
- Serialization. State must be converted to bytes and back, which limits what you can keep. Open file handles, sockets and live objects cannot be stored this way.
- Consistency. Two instances may now write to the same record at the same time. You need to think about concurrent updates, which in-process code could ignore.
In return you get instances that are interchangeable, and that is what makes scaling out, rolling deploys and failover simple.
Summary of the model
Key points:
- A stateless service handles each request using the request plus shared systems, with nothing in the instance that the next request needs.
- State still exists. It lives in a database, a cache cluster, object storage or the client.
- The kill-and-restart test tells you whether an instance holds state that matters.
- Instance-local sessions, files, counters, jobs and locks are the usual sources of hidden state.
- Statelessness trades some latency and operational work for interchangeable instances.
Exercise
A service runs three instances behind a round-robin load balancer. Users report being randomly logged out about two requests out of three, and the problem never appears in local testing with one instance. Name the cause, and name one change that fixes it without changing the load balancer.
Show answer
Each instance keeps sessions in its own process memory, so a request routed to an instance other than the one that handled the login finds no session. With three instances and round robin, roughly two in three requests reach an instance that does not know the user. Moving the sessions into a store shared by all instances, such as Redis, fixes it, as does putting the session data in a signed token held by the client.
Exercise
Your service keeps a dictionary in memory that maps product IDs to product names, loaded from the database on first use. Is this a violation of statelessness? Explain using the kill-and-restart test.
Show answer
No. If an instance is killed and restarted empty, it reloads the names from the database on first use. The user sees at most a slower first response, and no data is lost, because the database holds the real copy. The cache is disposable. You should still consider staleness if names can change, and cold-start load on the database.
Exercise
A team enforces "100 requests per minute per user" using a counter in each instance's memory. They run 5 instances behind a round-robin load balancer. What limit does a user effectively get, and why?
Show answer
Up to about 500 requests per minute. Each instance counts only the requests it sees, and round robin spreads one user's requests across all five instances, so each counter reaches 100 separately. A shared counter, for example in Redis, enforces the intended limit.