Sub topic 3
Why statelessness helps scaling and deploys
This chapter assumes you know HTTP requests, headers and cookies, you have built a web service or API, and you know that a load balancer spreads requests across servers. It explains why a stateless service is easier to scale, deploy and recover. Later chapters cover where the session state goes.
The working model
A stateless service keeps nothing between requests that a later request depends on. Each request carries, or can look up, everything the service needs to answer it. Any instance can then handle any request, and the answer does not depend on which instance receives it.
This property gives you three things:
- Interchangeable instances. One instance is as good as another.
- Disposable instances. You can stop one at any time without losing user data.
- Simple routing. The load balancer needs no knowledge of users or sessions.
Horizontal scaling
Horizontal scaling means adding more instances behind a load balancer, instead of making one machine bigger. It only works well when instances are interchangeable.
With this layout, the load balancer can use a simple policy such as round robin or least connections. If traffic doubles, you start more instances and register them. Nothing needs to be copied to the new instances, and they can serve requests as soon as they pass a health check.
If instances hold state, scaling gets harder in three ways:
- A new instance does not have the data that existing users built up on other instances.
- The load balancer must send each user back to the same instance, which limits how evenly it can spread load.
- Removing an instance during scale-in discards the state it held.
Deploys and failover
Deploys and failures are the same problem seen from two sides: an instance goes away, and you want users not to notice.
Rolling deploys
A rolling deploy replaces instances a few at a time with the new version. The steps are:
- Remove one instance from the load balancer and let its in-flight requests finish (connection draining).
- Stop it and start the new version.
- Wait for the health check to pass, then add it back.
- Repeat for the next instance.
If instances are stateless, step 2 loses nothing. Users keep their sessions across the whole rollout. If instances hold session data in memory, every replaced instance logs out the users who were on it.
Failover
Failover is the same event, without the warning. An instance crashes, the health check fails, and the load balancer stops sending it traffic. Stateless instances mean the next request from any user simply lands on a healthy instance. You can also run instances in several availability zones, because no instance is special.
Mixed versions during a rollout
During a rolling deploy, old and new versions run at the same time. If both read the same shared state, the format of that state must work for both. A common rule is to make changes in two releases: first deploy code that can read both the old and new format, then deploy code that writes the new one.
Statelessness moves state, it does not remove it
A common misunderstanding is that a stateless service has no state. The state still exists. It lives somewhere else: a database, a cache, a session store, or the client. The service itself holds no state that it cannot rebuild or look up.
A quick check is the restart test. Kill an instance at a random moment. If no user loses data or has to sign in again, the instance was stateless in practice.
The shared store becomes a dependency that you must scale and keep available. This is the main trade-off, and a later chapter covers store failures.
Common errors
The following are frequent ways a "stateless" service quietly keeps state:
| Hidden state | What goes wrong | Typical fix |
|---|---|---|
| In-memory session dictionary | Users are logged out on deploy or when routed elsewhere | Move to a shared store or signed token |
| Uploaded files on local disk | Another instance cannot find the file | Use object storage |
| In-process cache of mutable data | Instances return different answers | Use a shared cache, or cache only data that can be stale |
| Local scheduled jobs | The job runs once per instance, or not at all | Use a single scheduler or a lock |
Caching read-only data in memory is fine, because losing it only costs a reload. The problem is state that must be correct and that only one instance holds.
Checking it in code
This small Python example shows the bug. The handler keeps a counter in process memory, so the result depends on which instance answers.
from flask import Flask, jsonify
app = Flask(__name__)
visits = {} # lives in this process only
@app.get("/visit/<user_id>")
def visit(user_id: str):
visits[user_id] = visits.get(user_id, 0) + 1
return jsonify(user=user_id, visits=visits[user_id])
if __name__ == "__main__":
app.run(port=5000)Run two copies on ports 5000 and 5001 and call each in turn. Each reports its own count, and a restart resets it to zero. Replacing the visits dictionary with a call to a shared store makes both instances agree.
Exercise
Your service keeps a shopping cart in a Python dictionary inside each instance. Name two operational events that would cause users to lose their carts, and say what change would prevent both.
Show answer
A rolling deploy that replaces the instance, and an autoscaling scale-in or a crash that removes it, both discard the dictionary. A load balancer that routes the user to a different instance also shows an empty cart. Moving the cart to a shared store such as a database or Redis, keyed by user or session ID, prevents all of these.