Video in progress
What does a stateless service mean, and why is it easy to scale?
A stateless service keeps nothing about the user in its own memory between requests — the state it needs lives in the database, in Redis or inside a token. So any request can land on any instance, and you can add or remove instances freely.
📖 Answer
An example of a stateful service: on login the session is written to the server's memory. If the next request lands on a different server, it doesn't recognize you and asks you to log in again.
To make it stateless, you move the state out:
- sessions — into Redis (Spring Session) or into a JWT;
- uploaded files — not onto local disk but into object storage like S3;
- cron jobs — run on one instance only, using a lock (for example, ShedLock).
As a result the instances are interchangeable. If load grows in the evening, you start 8 instead of 3, and at night you drop back to 3. If one instance dies, the user doesn't notice.
The state doesn't disappear completely, of course — it moves to the database. The database may now become the bottleneck, but that's a different question.
Sign up to mark studied questions and save your progress.