Skip to content

Stateless services

The state lesson in the first module said that state is what a system remembers, and that it is what makes a system hard to copy. This lesson is about that difficulty, and about the way scaling out gets round it.

A service is stateless when any instance can answer any request, because nothing a request needs is remembered by one instance between requests. A service is stateful when the next request needs what a particular instance remembers.

The Twelve-Factor App states it as a rule for its processes: they are stateless and share-nothing, and any data that needs to persist must be stored in a stateful backing service, typically a database. It allows one exception, which is that the memory or filesystem of a process can be used as a brief, single-transaction cache.

Mental model. A stateless instance is a cashier with no notebook. Everything needed to serve the customer is on the ticket or in the shared ledger, so any cashier can serve any customer, and any cashier can leave at any time.

Suppose a login handler keeps the user’s name in a variable in the memory of the instance that handled the login. A load balancer then spreads the user’s next requests across the instances, evenly and at random. The share of requests that reach the instance that knows the user is 1 in N, for N instances.

Instances The next request finds the state The next request does not
1 100% 0%
2 50% 50%
4 25% 75%
14 7.1% 92.9%

With one instance, state in memory works perfectly, which is why it is easy to build and why it fails later. Each instance added makes it work worse. The failure is also silent: a request that reaches the wrong instance does not crash, it sees a user that is logged out or a cart that is empty.

State in memory is also lost when an instance goes. When a group of 14 instances is cut to 4, the 10 that go take their users’ state with them: 10 ÷ 14 = 71.4% of it, if the users were spread evenly. This is why statelessness matters for autoscaling, where instances are added and removed by a policy and nobody chooses the moment.

State does not disappear in a stateless design. It moves to a place that was made to hold it.

  • The database for what must last: profiles, orders, balances.
  • A shared store or cache for what is needed fast and may expire, such as a session. The Twelve-Factor App calls session data a good candidate for a datastore with time-expiration, such as Memcached or Redis.
  • The client, which holds a cookie or a signed token that travels with each request.
  • Object storage for files, instead of an instance’s own disk.
  • A queue for work that is waiting to be done.

Each of these is a service that has to scale for itself. The scalability lesson showed what happens when the API scales and the database does not: the database became the limit. Making a service stateless does not remove the state. It moves the scaling problem to the part that is meant to hold it.

Eight parts of different designs. Say for each whether any instance can answer the next request, or whether it needs what one instance remembers.

Challenge

Stateless or stateful?

A service is stateless when any instance can answer any request, because nothing a request needs is remembered by one instance between requests. A service is stateful when the next request needs what a particular instance remembers. Put each statement under the kind of service it describes.

Sorting needs JavaScript.

Categories

Stateless
Any instance can answer the next request.
Stateful
The next request needs what one instance remembers.
  1. Line 1 of 8An API that reads the user's profile from the database on every request.
  2. Line 2 of 8A service that keeps each user's shopping cart in a map in its own memory.
  3. Line 3 of 8A server that saves uploaded images on its own disk and serves them later.
  4. Line 4 of 8An instance that keeps its last 1,000 lookups in memory to save database calls.
  5. Line 5 of 8A service whose session data is in a shared Redis store that every instance reads.
  6. Line 6 of 8A chat server that holds each user's open connection and the rooms the user has joined.
  7. Line 7 of 8A service that reads the user's identity from a signed token sent with each request.
  8. Line 8 of 8A worker that counts each user's requests in a local variable, to allow at most 100 a minute.

Check your answers at least once before looking at the answers.

A stateless design has a price.

  • A lookup per request. What an instance would have remembered, it now fetches. That is time on every request, and load on the service that holds the state.
  • A new dependency. The state is held by a backing service, and the instances cannot do their work without it. In the vocabulary of dependencies, it is a hard dependency, and its availability and speed become the instances’ own.
  • Work to design. Some work does not split easily. The Azure Architecture Center advises that a long-running task be broken into smaller chunks, or that it save checkpoints to storage any instance can reach, because otherwise it can stop an instance from being shut down cleanly when the group scales in, or lose data if the process is forcibly terminated.

None of this is a reason to keep state in memory. It is the price of being able to add and remove instances freely, and it is usually worth paying.

What happens if you scale in a stateful service?

Section titled “What happens if you scale in a stateful service?”

A shop keeps each cart in the memory of the instance that served the shopper last. At the peak of a sale it runs 14 instances, and when the sale ends a policy cuts the group to 4, as the autoscaling lab in the last lesson does. The 10 instances that are removed held 10 ÷ 14 = 71.4% of the carts, and those shoppers find an empty cart on their next request.

Nothing crashed, no alarm went off, and the shop lost most of its open carts. A stateless version would have lost none: the carts would have been in a database, and the 4 remaining instances would have read them from it.

  • A stateless service lets any instance answer any request, because nothing a request needs is remembered by one instance between requests.
  • State in memory works for 1 instance, then worse with each one added: with 4 instances, a request finds it 25% of the time.
  • State in memory is lost when an instance is removed: cutting 14 instances to 4 loses 10 ÷ 14 = 71.4% of it.
  • The state moves to a database, a shared store, the client, object storage or a queue, each of which must scale for itself.
  • Statelessness costs a lookup per request, a new dependency and some design work. That is the price of adding and removing instances freely.

Next: session handling, and the three places a session can live.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.