Sub topic 7
Keeping application servers stateless
This chapter assumes you know how a web application talks to a database, what an HTTP request and a cookie are, and why a load balancer sits in front of several servers. It covers what "stateless" means, why horizontal scaling depends on it, and how to remove state from application servers.
Why state breaks horizontal scaling
State is data that a server remembers between requests. Examples are a logged-in session, a shopping cart held in memory, or an uploaded file saved on local disk.
With one server, this works. Every request reaches the same machine, so the data is always there. With several servers behind a load balancer, consecutive requests from one user can reach different servers. If the cart lives in the memory of app-1 and the next request lands on app-2, the cart appears empty.
A stateless server keeps nothing between requests that a later request needs. Each request carries, or can look up, everything required to handle it. Any server in the pool can then serve any request.
Common kinds of hidden state
Look for these when you review an application.
| Kind of state | Where it hides | Stateless alternative |
|---|---|---|
| User sessions | In-process memory or local files | Shared store such as Redis, or a signed token |
| Uploaded files | Local disk | Object storage such as Amazon S3 |
| Caches | In-process dictionaries | Shared cache, or accept per-server caches that can be rebuilt |
| Scheduled jobs | A cron entry on one server | One dedicated worker, or a job queue |
| Counters and locks | Variables in memory | Database or shared store with atomic operations |
Three ways to handle sessions
- Sticky sessions. The load balancer sends a user to the same server every time, usually using a cookie. This is quick to set up, but it only hides the problem. Load spreads unevenly, and if that server fails or is removed, its sessions are lost.
- Shared session store. The server keeps only a session ID in a cookie. The session data lives in a fast external store that every server can reach. Any server can handle any request, and a server can be removed without losing sessions.
- Client-side tokens. The server signs the session data, for example as a JSON Web Token (JWT), and gives it to the client. The client sends it with each request, and any server can verify the signature. This needs no store lookup, but tokens are hard to revoke before they expire, and they grow large if you put much data in them.
The shared store is the usual choice because it is simple and lets you end a session at any time. The store then becomes a dependency you must keep available and fast.
A small example
This Flask app keeps its session in Redis instead of process memory. Every instance that points at the same Redis sees the same session.
import os
import redis
from flask import Flask, session
from flask_session import Session
app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]
app.config["SESSION_TYPE"] = "redis"
app.config["SESSION_REDIS"] = redis.from_url(
os.environ.get("REDIS_URL", "redis://localhost:6379")
)
Session(app)
@app.route("/add")
def add_item():
cart = session.get("cart", [])
cart.append("book")
session["cart"] = cart
return {"items": len(cart)}Run two copies on different ports with the same SECRET_KEY and REDIS_URL, and call /add on each with the same cookie. The count keeps rising, because the cart is in Redis and not in either process.
Other practices
- Put configuration in the environment. Read settings from environment variables, not from files edited by hand on one server. Every instance then behaves the same.
- Treat local disk as temporary. Logs, scratch files, and caches are fine locally if losing them does no harm. Anything that must survive goes to shared storage.
- Make requests safe to retry. A load balancer or client may resend a request to another server after a timeout. Use idempotency keys for operations such as payments, so a retry does not repeat the effect.
- Keep shutdown graceful. A stateless server can be stopped at any time, but in-flight requests should finish first.
What statelessness does not remove
State does not disappear. It moves to the session store, the database, and object storage. Those components now carry the load and must scale on their own terms, which the next chapters on the data tier address. Statelessness makes the application tier easy to scale out, add to, and replace. It also lets an autoscaler start and stop servers freely.
Exercise
Your app stores shopping carts in a Python dictionary inside each server process. You add a second server behind a load balancer, and users report that their carts sometimes empty. Explain why, and give two ways to fix it.
Show answer
The load balancer sends a user's requests to different servers, and each server has its own dictionary, so a request that reaches a server without the user's cart sees an empty cart. One fix is to move carts into a shared store such as Redis, keyed by session ID. Another is to keep the cart in the database, or in a signed client-side token. Sticky sessions would reduce the symptom but would lose carts when a server fails or is removed, so they are a weaker fix.
Exercise
A team stores user avatar uploads in /var/uploads on each application server. What goes wrong when they scale from one server to three, and what should they change?
Show answer
An avatar uploaded through one server exists only on that server's disk, so requests served by the other two cannot find it, and the file is lost if that server is replaced. They should write uploads to shared object storage such as Amazon S3 and store the object key in the database.