Sub topic 7
Keeping application servers stateless
This chapter assumes you know how a web request flows from client to server to database. It also assumes you have read the earlier chapters on horizontal scaling and load balancing. Horizontal scaling only works well when any server in the pool can handle any request. That property comes from keeping application servers stateless.
What "stateless" means
A server is stateless when it keeps nothing between requests that a later request depends on. Each request carries, or can look up, everything needed to process it. The server may still use memory while it handles a request. It may also hold caches that can be rebuilt. What it must not do is hold the only copy of data that matters.
State is any data that outlives a single request and affects later behavior. Common examples:
- A login session (who the user is).
- A shopping cart that has not been saved to a database.
- An uploaded file sitting on the server's local disk.
- A counter or rate-limit tally in a process variable.
- A scheduled job that only one process knows about.
The word "stateless" is a goal for the application tier, not for the whole system. The state does not vanish. It moves to a place designed to hold it: a database, a shared cache, object storage, or the client.
Why state breaks horizontal scaling
Suppose a load balancer spreads requests over three servers in round-robin order, as in this small model.
from itertools import cycle
servers = ["app-1", "app-2", "app-3"]
pool = cycle(servers)
for request_id in range(5):
print(request_id, "->", next(pool))Now suppose each server keeps login sessions in its own memory. A user logs in and the request lands on app-1, which stores the session. The next request lands on app-2, which has never seen this user and treats them as logged out. The user sees random logouts that depend on which server answered.
Local state causes four problems when you scale out:
- Inconsistent behavior. Different servers give different answers to the same user.
- Lost data on failure. If
app-1crashes or is replaced, its sessions and files are gone. - Unsafe scale-in. Removing a server during a quiet period destroys whatever it held.
- Uneven load. If requests must return to the server that holds their state, the balancer cannot spread work freely.
Option 1: sticky sessions
The quickest fix is sticky sessions (also called session affinity). The load balancer remembers which server handled a client, usually through a cookie or a hash of the client IP, and sends that client to the same server every time.
Sticky sessions need no application changes, so they are a reasonable stopgap. They also have costs:
- Uneven load. A few heavy users pinned to one server can overload it while others sit idle.
- Failure still loses state. If the pinned server dies, its sessions die with it.
- Awkward scale-in and deploys. You must drain a server (wait for pinned users to finish) before removing it.
- Weaker autoscaling. New servers receive only new clients, so they take a while to share the load.
Treat stickiness as a mitigation. It does not make the application stateless.
Option 2: externalize the state
The standard solution is to move state out of the application process into a shared service that every server can reach. Which service fits depends on the kind of state.
| Kind of state | Typical home | Notes |
|---|---|---|
| User sessions | Shared cache such as Redis, or a database | Fast lookups, expiry built in |
| Business data (orders, profiles) | Database | Durable, transactional |
| Uploaded files, images | Object storage such as Amazon S3 | Serve through a URL, not local disk |
| Cached query results | Shared cache | Safe to lose, can be rebuilt |
| Background work | Message queue | Any worker can take the next job |
| Configuration | Environment variables or a config service | Same values on every instance |
With a shared session store, the earlier failure disappears. Whichever server receives the request looks up the session by its ID.
Here is a minimal sketch of the pattern in Python. It uses a dictionary to stand in for the shared store so the code runs anywhere. In production, SessionStore would wrap a network service such as Redis, and the two Server objects would be separate machines.
import uuid
class SessionStore:
"""Stand-in for a shared service such as Redis."""
def __init__(self):
self._data = {}
def create(self, user):
session_id = str(uuid.uuid4())
self._data[session_id] = {"user": user}
return session_id
def get(self, session_id):
return self._data.get(session_id)
class Server:
"""Holds no session data of its own."""
def __init__(self, name, store):
self.name = name
self.store = store
def login(self, user):
return self.store.create(user)
def whoami(self, session_id):
session = self.store.get(session_id)
if session is None:
return f"{self.name}: 401 Unauthorized"
return f"{self.name}: hello {session['user']}"
store = SessionStore()
app1 = Server("app-1", store)
app2 = Server("app-2", store)
token = app1.login("dana")
print(app2.whoami(token)) # app-2: hello dana
print(app2.whoami("bogus")) # app-2: 401 UnauthorizedThe login happens on app-1 and the follow-up request is answered by app-2. The servers differ, yet the user sees consistent behavior, because neither server owns the session.
Option 3: put state in the client
Another approach is to give the client the state and have the server verify it. A common form is a signed token such as a JSON Web Token (JWT), which contains the user ID and an expiry time, plus a signature made with a secret key that all servers share. Any server can check the signature without a lookup.
This removes the session store from the request path. It also brings trade-offs:
- Revocation is hard. A valid token stays valid until it expires, unless you add a deny list, which is state again.
- Size. The token travels with every request, so keep it small.
- Confidentiality. A signed token is not encrypted by default. Anyone holding it can read its contents, so do not put secrets in it.
- Key management. Every server needs the verification key, and rotating it needs care.
Many systems combine the two: short-lived signed tokens for speed, plus a small server-side store for revocation and long-lived refresh.
Other places state hides
Sessions are the obvious case. The following are easier to miss.
Local files
Writing uploads or generated reports to local disk means only one server has the file. Write them to object storage instead, and store the object's key in the database. Temporary files used inside a single request are fine, as long as nothing else needs them later.
In-process caches
A cache in process memory is allowed, because losing it only costs speed. The risk is staleness. If app-1 caches a product price and app-2 receives the update, the two servers disagree until the cache entries expire. Use short time-to-live values for such caches, or use a shared cache when consistency matters.
Counters and rate limits
A per-process request counter undercounts by the number of servers. With 10 servers and a limit of 100 requests per minute enforced locally, a client can make up to 1000 requests per minute. Keep rate-limit counters in a shared store with atomic increments.
Scheduled jobs
If every server runs the same nightly cron job, the job runs once per server. Either run scheduled work in a dedicated single process, or use a lock in a shared store so only one instance proceeds.
WebSockets and long-lived connections
An open connection is tied to one server by nature. The connection itself is a form of state. Keep application data out of the process and let clients reconnect to any server. When servers need to push messages to a user connected elsewhere, use a shared publish-subscribe channel.
Process identity
Code that assumes it is the only instance, such as an in-memory queue or a leader-only task, fails when a second copy starts. Check for this before you add replicas.
What stateless buys you
Once state is externalized, several benefits follow together:
- Any server can handle any request, so the load balancer can use simple policies.
- Servers are disposable. A crashed instance is replaced with no data loss.
- You can deploy by replacing servers one at a time.
- Autoscaling can add and remove instances freely, which the later autoscaling chapter relies on.
What it costs
Statelessness is not free.
- Extra network hops. A session lookup is a network call instead of a memory read. Typically this adds around a millisecond within one data center, but it adds up if you make many lookups per request.
- A new dependency. The shared store is now critical. If it is down, every server is affected. It needs its own replication and monitoring.
- The bottleneck moves. The state does not disappear. It concentrates in the shared store and the database, which then need to scale. The next chapter covers that data tier.
A checklist for auditing an application
Before scaling out, check each item:
- Where are sessions stored? Is the store shared by all instances?
- Does any code write to local disk and read it back in a later request?
- Are there module-level variables that change as requests arrive?
- Do scheduled tasks assume a single instance?
- Do any caches need to be consistent across servers?
- What happens if one instance is killed in the middle of a request?
The last question is a practical test. Start two instances behind a balancer, send traffic, and terminate one at random. If users notice, some state is still local.
Common mistakes
- Fixing sessions and forgetting files. The login works, but profile photos vanish for half the users.
- Using sticky sessions as a permanent answer. It hides the problem until a server fails or an autoscaler removes it.
- Putting large objects in the session. Big sessions slow every request and fill the store.
- Treating the shared cache as durable. Caches evict data. Keep the source of truth in a database.
- Testing with one instance only. State bugs show up only with two or more.
Exercise
An online shop runs three identical servers behind a round-robin load balancer. Customers report that items randomly disappear from their carts, and uploaded product images sometimes return "not found". Each server keeps carts in memory and saves uploads to its own disk. Explain why this happens and describe a fix for each problem.
Show answer
Round-robin sends a customer's successive requests to different servers. A cart held in one server's memory is invisible to the others, so the cart seems to lose items. An image saved to one server's disk exists only there, so requests that reach another server get "not found". Fix the cart by storing it in a shared store (a database, or a shared cache such as Redis with a session ID in a cookie). Fix the images by uploading them to object storage such as S3 and saving the object key in the database, so every server serves the same file. Sticky sessions would reduce the symptoms for carts but would not fix lost data on server failure, and would not help with images shared between customers.
Exercise
A team enforces a limit of 60 requests per minute per user using a counter in each server's memory. They run 6 servers behind a round-robin balancer. What is the worst-case number of requests per minute a single user can make, and how should the limit be implemented instead?
Show answer
Each server counts separately, so the user can make 60 requests on each of the 6 servers, a total of 360 per minute. The counter should live in a shared store with atomic increments, for example a Redis key per user per time window, so all servers share one count.