Keep servers stateless
Sessions or files stored on a server mean requests must return to the same machine.
Say it like this
Any instance must be able to serve any request, so I keep the API tier stateless: sessions in Redis or a signed token, files in object storage, and nothing on local disk that a second request would need.
Basic solution
Move state out: sessions to Redis or signed cookies, files to object storage, so any server can serve any request.
State lives beside the instances, not in them
Any instance can serve the request: identity comes in the signed token, counters and sessions sit in Redis, files sit in object storage. Instances can be replaced at will.
How it works
- A request arrives at whichever instance the load balancer picks. That instance has no memory of any earlier request from the same client, and it does not need one.
- Identity travels with the request. Either the client sends a signed token (a JWT) that the instance verifies locally with a public key, or it sends a session id that the instance looks up in a shared store such as Redis. Either way, nothing about who the user is lives on the instance.
- Anything the request needs that was produced earlier, such as a draft, an uploaded file or a shopping cart, is read from a shared store by its key, never from this instance's memory or local disk, because the earlier request may have been served by a different instance.
- The instance does its work and writes the results back to shared stores. Its local memory is used only as a scratchpad for the current request, or as a read-through cache whose loss costs speed but never correctness.
- Because nothing lives only on the instance, it can be killed, replaced or multiplied at any moment and no user loses anything.
What counts as state
- Sessions, uploaded files, in-progress jobs, WebSocket connections, rate-limit counters, and feature-flag evaluations cached for a user. Each needs a home that is not the instance, or an explicit rule that routes the client back to the same instance.
Worked example
URL shortener API tier
- 40 writes/s and 40K redirects/s at peak across 12 instances. A user creates a link on instance 3 and lists their links a second later on instance 9.
- Sessions: a JWT of about 300 bytes carries user_id and scopes, signed with a key the instances hold; verification is one signature check, about 20 microseconds, no network call. Lifetime 15 minutes with a refresh token stored server-side so a revoked user is out within 15 minutes.
- Rate limits: the per-user counter lives in Redis (one EVALSHA, about 0.3 ms), so instance 3 and instance 9 see the same count. A local counter would give each user 12× the limit.
- Uploads (custom link previews): the client gets a pre-signed URL and writes to object storage; the API only stores the key. No instance ever holds a file.
- Deploy: 12 instances replaced one at a time with no sticky sessions to drain and no lost carts, because the balancer can send the next request anywhere.
- Autoscaling becomes possible: the fleet went from 12 to 30 instances during a viral spike and back, with no coordination beyond registering with the balancer.
Variants and when each wins
Signed tokens (JWT, PASETO)
- The token itself carries the user's id and permissions, signed so an instance can verify it without a lookup. It wins when you want zero store traffic per request; the cost is that a token cannot be revoked before it expires, so keep it short and pair it with a refresh token.
Server-side sessions in a shared store
- A random session id travels in a cookie and the session's state lives in Redis. It wins when you need instant revocation; the cost is one Redis lookup per request, putting Redis on the hot path.
Sticky sessions at the balancer
- State stays on the instance and the balancer routes each client back to the same instance every time. It wins as a quick bridge for an older service you have not yet made stateless; the cost is that a lost instance loses its sessions and the balancer cannot rebalance load.
Externalise only what must be shared
Recommendation: short-lived signed tokens plus a server-side refresh token for auth, Redis for anything else that must be shared, and sticky sessions only as a temporary bridge while removing state from an older service.
Failure modes
Revoked user keeps working
- A banned or logged-out user keeps calling the API successfully for minutes. Their JWT is long-lived and nothing on the server checks it against a revocation list, so it stays valid until it expires. Issue access tokens that last 5 to 15 minutes, store refresh tokens server-side where they can be revoked, and keep a small denylist in Redis for emergency revocation.
Lost work on deploy
- Users lose a half-finished upload or multi-step form whenever instances are replaced. The in-progress state was held in the memory of the instance that died. Persist each step to a store keyed by user as it happens, and make every step resumable from that record.
Shared store becomes the bottleneck
- Redis saturates at peak and every request slows down with it. Each request makes several session reads, so the store's load grows with request rate. Carry the commonly needed claims in the token so most requests need no lookup, cache session reads in-process for a few seconds, and batch whatever remains.
Local disk filling up
- Instances crash with no space left on the device. Temporary files or logs were written to local disk and never cleaned up. Stream uploads to object storage, ship logs off the box, and treat local disk as ephemeral scratch space.
Affinity creeping back in
- Errors appear only when the balancer switches a client to a different instance mid-flow. An in-memory cache was populated by one request and a later request assumed it would still be there. Give every cached read a fallback to the shared store, and test by routing consecutive requests to different instances in CI.
Interviewer follow-ups
Answer out loud before you open each one.
If JWTs cannot be revoked, how do you log someone out everywhere?
Keep access tokens short, 5 to 15 minutes, and store refresh tokens server-side so revoking the refresh token ends the session at the next refresh. For immediate effect keep a small denylist of revoked token ids in Redis that the gateway checks; it only has to hold entries until their tokens expire.
Are WebSockets compatible with stateless services?
The connection itself is state on one instance, which is unavoidable. The fix is to make it the only state: keep a registry of which instance holds which user in a shared store, and keep messages and presence in shared stores so a reconnect to a different instance loses nothing.
What is allowed in instance memory?
Anything whose loss costs only performance: a read-through cache of hot keys, compiled templates, connection pools, parsed configuration. The rule is that a request routed to a fresh instance must still return the right answer, just slower.
How does statelessness change the deploy process?
Instances become interchangeable, so you can replace them one batch at a time, drain in seconds instead of waiting for sessions to end, and roll back by swapping images. It is also what makes autoscaling safe, because adding or removing an instance never loses anything.
Connections
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Application Load Balancer | Load balancer | Cloud Load Balancing | Application Gateway, Azure Load Balancer | NGINX, HAProxy, Envoy |
| Amazon EC2 Auto Scaling | Instance 3, Instance 9 | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon ElastiCache | Redis | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon S3 | Object storage | Cloud Storage | Blob Storage | Cloudflare R2, MinIO, Ceph |