Sub topic 3
Why statelessness helps scaling and deploys
This chapter assumes you know HTTP requests, responses, headers and cookies. It also assumes you have built a web service or API in some language, and that you know a load balancer sends incoming requests to one of several servers. The previous chapters defined a stateless service and what counts as session state. Here we look at what that property buys you in operations: scaling, deploys and failover.
The core claim
A stateless service keeps nothing between requests that a later request needs. Each request carries, or can look up from shared storage, everything required to handle it. Because of this, any instance can handle any request. That one property explains most of the operational benefits below.
If instances are interchangeable, the load balancer can send a request anywhere. You can add an instance without moving data to it. You can remove an instance without losing anything a user cares about.
Horizontal and vertical scaling
There are two ways to add capacity.
- Vertical scaling means moving to a bigger machine, with more CPU or memory. It is simple, but it has a ceiling, and the machine is still a single point of failure.
- Horizontal scaling means running more copies of the service behind a load balancer. It has no fixed ceiling and tolerates the loss of one copy.
Horizontal scaling only works well when the copies are interchangeable. If instance A holds a user's session in its memory, a request that lands on instance B fails to find it. The user appears logged out, or loses a shopping cart. State held inside an instance turns "add more copies" into a correctness problem.
What you gain
Elastic capacity
With interchangeable instances, an autoscaler can add instances when load rises and remove them when it falls. New instances start empty and are useful as soon as they pass a health check. You do not need to copy sessions to them or warm any per-user data.
Scale-in works the same way. When the autoscaler picks an instance to terminate, no user data is lost, because the instance held none that mattered. If the instance is stateful, you must first drain its state somewhere, and that makes scale-in slow and risky.
Simple load balancing
Stateless instances let the load balancer use any algorithm that spreads load well, such as round robin or least connections. It does not need to remember which user belongs to which instance. Load spreads evenly, and one busy user cannot overload a single instance just because the balancer pinned them there.
Compare this with sticky sessions (covered in the next chapter), where the balancer must route a user to the same instance each time. Stickiness reduces the balancer's freedom and creates uneven load.
Rolling deploys
A rolling deploy replaces instances a few at a time, so the service stays available throughout. It works smoothly only when stopping an instance is harmless.
With stateless instances, the steps are: start a new one, wait for it to be healthy, stop sending requests to an old one, let in-flight requests finish, then terminate it. No user loses a session. If the instances held sessions in memory, every restart would log out the users pinned to them. Teams then avoid deploying during busy hours, and deploys become rare and large, which makes them riskier.
Stateless services also make other deploy strategies easier:
- Blue/green: run the new version beside the old one and switch traffic at once. Both versions can use the same shared state.
- Canary: send a small share of traffic to the new version, watch error rates, then widen it.
- Rollback: stop sending traffic to the new version. Nothing on the instances needs restoring.
Failover
Hardware fails, processes crash and nodes get reclaimed by the cloud provider. When an instance dies, the balancer's health check detects it and stops routing to it. Other instances take its requests. A stateless service loses only the requests that were in flight at that moment. A client that retries gets a normal response from another instance.
A stateful service loses everything held on the failed instance. You then need replication of that state, which is the same problem as building a shared store, but done inside your application.
A worked example of the failure
This small Flask app keeps a counter in process memory. It works with one instance and breaks with two.
from flask import Flask, session
app = Flask(__name__)
app.secret_key = "dev-only-change-me"
# Instance-local state: lives in this process only.
carts = {}
@app.post("/cart/<user_id>/<item>")
def add_item(user_id, item):
carts.setdefault(user_id, []).append(item)
return {"items": carts[user_id]}
@app.get("/cart/<user_id>")
def get_cart(user_id):
return {"items": carts.get(user_id, [])}
if __name__ == "__main__":
app.run(port=5000)Run two copies on ports 5000 and 5001 behind a round-robin balancer. A user adds an item, and the request goes to the first copy. The user then reads the cart, and the request goes to the second copy, which returns an empty list. Nothing crashed. The data simply lives in the wrong place.
The fix is to move the cart into a store that every instance reaches:
import json
import redis
from flask import Flask
app = Flask(__name__)
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
@app.post("/cart/<user_id>/<item>")
def add_item(user_id, item):
key = f"cart:{user_id}"
r.rpush(key, item)
return {"items": r.lrange(key, 0, -1)}
@app.get("/cart/<user_id>")
def get_cart(user_id):
return {"items": r.lrange(f"cart:{user_id}", 0, -1)}
if __name__ == "__main__":
app.run(port=5000)Using rpush also avoids a read-modify-write race. Two instances adding items at the same moment both succeed, because Redis applies each push atomically. Doing the same with a read, a change in application code and a write back could lose one update.
Costs and limits
Statelessness does not make state disappear. It moves state, and the move has costs.
| Cost | What it means |
|---|---|
| Extra network hop | Each request may call the shared store. This adds latency, usually under a millisecond to a few milliseconds in the same network. |
| New dependency | If the store is down or slow, every instance is affected. A later chapter covers store failure modes. |
| Serialization | Data must be encoded and decoded on every access. |
| Consistency | Concurrent requests for the same user can race. Atomic operations or versioning may be needed. |
| Shared bottleneck | The store itself must scale, using replicas or partitioning. |
The service tier becomes easy to scale, and the difficulty concentrates in the data tier. This is usually a good trade. Stores such as Redis or a database are built to be scaled, replicated and backed up, and application code is not.
Common mistakes
- Treating a local cache as harmless when it holds writes. A cache of read-only data is safe to lose. A cache that holds changes not yet saved elsewhere is state.
- Relying on local disk. Uploaded files written to an instance's disk vanish when it is replaced and are invisible to other instances. Use object storage or a shared file system.
- Running scheduled jobs inside every instance. With ten instances, a nightly job runs ten times. Use a single scheduler, or a lock in shared storage.
- In-memory rate limits. Each instance counts separately, so a limit of 100 requests per minute becomes 100 times the instance count. Keep counters in a shared store.
- Assuming one deploy version at a time. During a rolling deploy, old and new instances run together and share the same store. Data formats written by the new version must be readable by the old one for the duration of the deploy.
- Skipping graceful shutdown. If a process exits on
SIGTERMwithout finishing in-flight requests, users still see errors, even though no state is lost.
The fifth mistake matters for sessions in particular. If a new version changes the session's JSON fields, old instances may fail to parse sessions written by new ones. Add fields in a backward-compatible way first, then remove old ones in a later release.
Statelessness and the HTTP model
HTTP itself is stateless: the server treats every request independently. Applications add state on top, usually by having the client send an identifier in a cookie. Making your service stateless means choosing where that state lives, and the options are the subject of the rest of this tutorial:
- In the instance (sticky sessions).
- In a shared server-side store.
- In the client, in a signed token.
Each option is a different answer to the question this chapter raises: if requests can reach any instance, where does the instance find what it needs?
Practical checklist
Before you scale out, check each of these:
- Can you kill any instance at random without a user noticing?
- Does the service start with no local data and become useful straight away?
- Does the service handle
SIGTERMby stopping new work and finishing in-flight requests? - Is every value that must survive between requests held in the client or in shared storage?
- Do scheduled jobs and counters behave correctly with N instances?
- Can two adjacent versions of your code read each other's stored data?
If you answer "no" to any item, that item is where your scaling and deploy problems will appear.
Exercise
A service runs three instances behind a round-robin load balancer. It stores a user's login in a Python dictionary in each process. Users report being logged out at random, and more often after a deploy. Explain both symptoms and name one change that fixes them.
Show answer
Each instance has its own dictionary, so the login exists only on the instance that handled the login request. Round robin sends the next request to another instance, which has no record and treats the user as logged out. A deploy replaces every process, which empties every dictionary, so all users are logged out at once. Moving sessions into a shared store such as Redis, keyed by a session ID the client sends in a cookie, lets any instance find the login and survives restarts. (A signed client-side token also fixes it.)
Exercise
You run ten stateless instances. A cron-style job inside the application sends a daily summary email, and customers now receive ten copies. Give two ways to fix this without making instances stateful.
Show answer
Run the job from a single scheduler outside the request-serving instances, such as a separate one-instance worker or the platform's scheduled-job feature. Alternatively, have each instance try to take a lock in shared storage (for example Redis SET key value NX EX 3600) and run the job only if it gets the lock. Both keep the coordinating state outside the instances.
Exercise
During a rolling deploy, version 2 writes sessions with a new required field, and version 1 instances start throwing errors when they read those sessions. What rule would have avoided this?
Show answer
Make stored data changes backward compatible across adjacent versions. Version 1 must be able to read what version 2 writes for as long as both run. Release the code that tolerates the new field first, then release the code that writes it, and remove old fields only in a later release.