Lesson 01

Stateless Services, Many Copies

Building block

The cheapest tier to scale is the one that remembers nothing between requests. When any copy of a service can answer any request, capacity is a count of copies, a lost copy loses nothing a user was told was saved, and the load balancer may send traffic anywhere.

The state does not disappear. It moves into stores, and the rest of this chapter is about those stores. The request tier is in every first design and is almost never the hard part. What the interviewer tests is whether you know what made it easy.

Where the State Goes

Every piece of state a request leaves behind needs a home outside the process that served it. A login session moves to a session store, or into a signed token that the client carries. An upload in progress goes to object storage, not to one copy's disk. A cart or a counter goes to the database. A job that must run exactly once leaves the request tier altogether.

The test fits in one sentence: any request can go to any copy, and any copy can be killed at any moment without losing anything. A small cache inside each copy passes it, because losing that cache costs only misses, as the next lesson shows. A value that lives only in one process fails it, however briefly it lives there.

Session Store vs Signed Token

A session store keeps the session on the server and gives the client only an ID. A logout or a ban takes effect on the next request, at the cost of a lookup on every request, a round trip of 1 to 2 milliseconds when the store sits in another zone, and a replicated tier to run. Use it when revoking access must take effect at once.

A signed token carries the claims to every copy, which checks it with no lookup at all. It cannot be withdrawn before it expires without a deny list, and a deny list brings the lookup back. Use it when access may outlive a revocation by the token's short lifetime. How either one is built is the subject of Backend Deep Dive's lesson on sessions and tokens.

Copies Behind a Load Balancer

On the board, the load balancer is a black box with stated guarantees. It spreads requests over the copies that are healthy, and a health check takes a dead copy out of rotation. The one box you draw stands for a redundant pair or a managed service: say so once, and do not design it. What it does not know is what a request costs. Layer 4 against layer 7, the algorithms and the health checks themselves belong to Networking Deep Dive's chapter on load balancing.

A stateless tier: every piece of state lives in a store, so a dead copy loses nothing
Clientany request Load balancerhealthy copies App serverholds nothing App serverholds nothing App serverdead, nothing lost Session storereplicated Object storeuploads Databasecarts, counters request check fails: out session upload cart readwritefailure

The number of copies is arithmetic, and the interviewer expects to hear it. Assume 10,000 requests a second on average, a peak of twice that, and 1,000 requests a second per copy. The peak is 20,000 a second, so it needs 20 copies.

Now spread those copies over three zones and lose one zone. Two thirds of 20 copies carry about 13,000 requests a second, well short of the peak. So the tier is 30 copies, 10 in each zone, and any two zones carry the full 20,000. Zones and what they protect against come back in Chapter 6.

Sizing for the peak with a zone lost
20 copiespeak 20,000 a second, 1,000 per copy
Enough with every zone up. A zone lost leaves two thirds: about 13,000 a second of the 20,000.
30 copies10 in each of three zones
A zone lost leaves 20 copies, and the two zones left carry the full 20,000 a second.

Sticky Sessions, the Trap

Session affinity, often called sticky sessions, sends each user back to the copy that holds their session. It hides the state instead of moving it, and three things follow. The load follows users, not requests, so it goes uneven when a few users are busy. A lost copy logs out everyone pinned to it. And copies added during a spike receive only new users, while everyone already pinned stays on the copies that were overloaded.

One copy is lost
With affinitysessions held in the copy
Every user pinned to it is logged out. The load on the other copies stays uneven, pinned by user.
Without affinitysessions in a store
Any copy answers the next request. The store still holds every session, and nobody notices.

Routing by key is sound in two cases. One is an optimisation where a wrong route costs only a cache miss, such as sending a user to the copy whose local cache already holds their data. The other is a tier that is stateful by design, such as the connection gateways of a chat system in Chapter 18. The one-service version of this story, affinity left switched on after the sessions had moved out, is told in Backend Deep Dive's lesson on scaling out.

What Scaling Out Moves

Every copy you add multiplies the load on what the copies share: connections to the database, readers of the cache, lookups in the session store. Triple the copies and the database holds three times the connections, whether or not it was built for them. The tier scales because its state lives elsewhere, and from here on, the elsewhere is the limit.

That makes the stores the new single points. A session store without a replica is exactly the single point of failure the stateless tier was meant to remove: when it goes, every copy is healthy and every request fails. How one service sizes its pool of connections is Backend Deep Dive's. This lesson names the shared limit and hands the reads to the rest of the chapter: the cache, the ways it fails, read replicas, and the edge.

Adding Copies in Time

An autoscaler adds a copy only after it has noticed the load and the new copy has started. Scale the request tier on requests per copy or on CPU. Scale workers on the age of the oldest job in their queue, because the age of that job is the delay a user feels, and CPU does not show it.

Keep headroom running for a spike that arrives faster than a copy starts. It costs idle copies on a quiet day, and a spike that eats the headroom before the autoscaler catches up is the trigger to keep more. Remove copies with the same care: drain one first, so it takes no new requests and finishes the ones it has. How one service drains is in Backend Deep Dive's lesson on health checks and graceful shutdown.

How Interviewers Probe This

Probes on this tier come back to three things: where the state lives, how many copies, and the shared limit that binds next. When the request tier first goes on the board, one line covers the first two. You might say: "Each copy is stateless, so I size for the peak with a zone down: thirty copies, ten a zone."

The first probe is "One of your app servers dies mid-request. What does the user see?" A good answer says that one request fails and is retried, by the client, or by the load balancer when the request is safe to repeat. Nothing saved is lost, and the health check takes the copy out. A retried write needs an idempotency key so that it does not happen twice. Chapter 6 takes those up at scale, and Backend Deep Dive's lesson on idempotency keys covers one service.

The second is "Traffic triples tomorrow. What changes?" A good answer triples the copies in one sentence, thirty become ninety, and spends the rest of the answer on the shared limit that binds next, with a number: three times the database connections, three times the session lookups, and whether the stores were sized for them.

The third is "Why not use sticky sessions?" A good answer names the uneven load and the sessions lost with a copy, then gives the one case where routing by key is fine: when a wrong route costs only a cache miss.

Misconceptions
  • "Stateless means no state." The state moved to a store, and the service scales only as far as that store does.
  • "Sticky sessions are a harmless speed-up." When correctness depends on them, a lost copy takes its users' sessions with it, and copies added in a spike take only new users.
  • "Twice the copies is twice the capacity." Only until a shared thing binds. Each copy also adds database connections and readers of the cache.
  • "A local cache makes the server stateful." A copy whose loss costs only misses is still interchangeable. State is a problem when the copy in the process is the only one.
  • "The autoscaler absorbs the spike." It reacts after the spike begins, late by at least the time a copy takes to start. A faster spike is carried by headroom that is already running.
Why It Matters
  • Name the store for every piece of user state when you draw the request tier.
  • Size the tier for the peak with one zone lost, from a rate per copy you state as an assumption.
  • Turn affinity off for correctness, and route by key only where a wrong route costs a cache miss.
  • Before you say "add more servers", name the shared thing each new copy loads and how much headroom it has.
RelatedBackend Deep Dive one service scaled out, sessions and tokensNetworking Deep Dive load balancers insideCaching at Scale the local cache layer

Knowledge Check

Assume a peak of 20,000 requests a second, 1,000 a second per copy, and three zones. How many copies keep the peak covered with one zone lost?

  • 30 copies, 10 in each zone, so that any two zones carry the full peak
  • 20 copies, since that is exactly what the peak needs at 1,000 each
  • 27 copies, 9 in each zone, about a third more than the peak needs
  • 60 copies, 20 in each zone, so that any single zone carries the whole peak

A copy dies. Its users were pinned to it by sticky sessions that held their login state. What happens?

  • Its users are logged out, and the load on the other copies stays uneven
  • Nothing visible, since the load balancer moves its users elsewhere
  • Every user of the service is logged out until the lost copy is replaced
  • Its users wait until the autoscaler starts a copy with their sessions

Which of these may stay inside one copy's process without making the tier stateful?

  • A small local cache of values that the store also holds
  • The cart a user has filled, copied to the database every few minutes
  • The finished parts of an upload, kept on that copy's disk until the end
  • A login session in this copy's memory, signed so no copy can forge it

The tier grows from 30 copies to 90 for a launch. What should be checked first?

  • The stores, which now see three times the connections and lookups
  • The load balancer's algorithm, which has to change at this size
  • Nothing else, since stateless copies scale out with no limit
  • The local caches, which must be merged into one shared cache

A product must cut off a banned user within one request. Which session design fits, and at what cost?

  • A session store, at the cost of a lookup on every request
  • A signed token, since each copy checks its signature locally
  • A signed token with a long lifetime, renewed only at sign-in
  • Sticky sessions, so that only one copy has to forget the user

You got correct