SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • Scalability
  • Availability
  • Reliability
  • Single Point of Failure (SPOF)
  • Latency vs Throughput vs Bandwidth
  • Consistent Hashing
  • CAP Theorem
  • Fault Tolerance and Redundancy
  • Failover
  • Stateless vs Stateful
  • Concurrency vs Parallelism
  • Capacity Planning
  • Back Pressure
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Core Concepts

Stateless vs Stateful

Does the server remember you between requests? This choice decides how easily you can scale.

โฑ 12 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A stateless server keeps nothing about you between requests. A stateful server remembers you (a login, a cart, a game position) in its own memory or disk.

  • With stateless servers, any server can handle any request. You can add, remove or crash servers freely.
  • With stateful servers, a user is tied to the machine that remembers them. Scaling and failure are harder.
  • The usual trick: keep the servers stateless and move the state out into a database, a cache or a token the client carries.

02Concept: What is it?

State is anything the system must remember to answer the next request correctly: who is logged in, what is in the shopping cart, which step of a form you are on, the position of a player in a game.

In a stateful design, the server stores this state itself, usually in memory. The second request must reach the same server, or the state is not found. In a stateless design, every request carries (or can look up) all it needs. The server holds no memory of earlier requests, so the next request can go to any server.

Where does the state live?
Stateful
๐Ÿ‘คUser
โ†“must return to the same server
๐Ÿ–ฅ๏ธServer 1has your session
๐Ÿ–ฅ๏ธServer 2knows nothing
Stateless servers
๐Ÿ–ฅ๏ธServer 1
๐Ÿ–ฅ๏ธServer 2
โ†“read and write the session
๐Ÿ—ƒ๏ธShared storedatabase, cache, or a token in the request
The state does not disappear in a stateless design. It moves out of the web server.
๐Ÿง Stateless does not mean no state
An app always has state. "Stateless" describes the server process: it can be thrown away at any moment without losing anything important, because the important data lives somewhere else.

03Real-Life Example

๐ŸตThe Waiter Who Remembers vs the Order Slip
In a small cafรฉ, one waiter remembers your whole order in their head. If that waiter goes home, nobody knows what you asked for. In a big restaurant, every order goes onto a slip kept at a central counter. Any waiter can pick up your slip, see what you ordered and serve you. If a waiter leaves, nothing is lost. The first cafรฉ is stateful. The second is stateless, with the state held at the counter.
Restaurant
Web system
A waiter who remembers orders
A stateful server with a session in memory
The order slip at the counter
A shared session store (database, Redis)
Any waiter can serve you
Any stateless server can handle the request
Always the same waiter for you
Sticky sessions
The waiter goes home
The server crashes or is scaled down
A wristband that says who you are
A token (such as a JWT) sent with each request
One request in a stateless design
๐Ÿ‘คClientsends token or session id
โ†’โ†“
โš–๏ธLoad balancerpicks any server
โ†’โ†“
๐Ÿ–ฅ๏ธAny serverkeeps no memory
โ†”
๐Ÿ—ƒ๏ธShared storethe session lives here

04Why Do We Need It?

๐Ÿ“ˆEasy to scale
Add a server and it can help at once. No user has to be moved to it.
๐ŸงฏSurvives crashes
If a server dies, the next request goes to another one and nothing is lost.
โš–๏ธSimple load balancing
Plain round robin works. No need to remember which server owns which user.
๐Ÿš€Easy deploys
Replace servers one by one. Nobody is logged out by a restart.
โ˜๏ธFits autoscaling and serverless
Servers can start and stop all the time, because they hold nothing precious.
๐ŸงชEasier to test
A request gives the same answer on any server, so bugs are easier to repeat.
Keep the servers disposable. Put what must not be lost into a place that is built to keep it.

05Where Do We Use It?

๐ŸŒWeb and API servers
Usually stateless behind a load balancer, with a database and a cache behind them.
๐Ÿ”Login sessions
Stored in a shared store, or put into a signed token the client sends.
๐Ÿ—„๏ธDatabases
Stateful by nature. They are the place where the state is meant to live.
๐ŸŽฎGame and chat servers
Often stateful, because a live connection and a game world sit in memory for speed.
๐Ÿ“กWebSockets
A long connection is attached to one server, so it is stateful at the connection level.
ฮปServerless functions
Stateless by design. Any needed state is read from and written to a service.

06Types / Parts / How It Works

Stateless vs stateful

StatelessStateful
Remembers earlier requests?No. Each request is complete by itselfYes. Needs earlier context
Which server may answer?Any serverOften one particular server
Scaling outAdd servers, doneMust move or copy the state
A server crashesNothing is lostThat server's state may be lost
Per-request costMay re-read the state each timeState is local and fast
Good forWeb and API tiers, serverlessDatabases, games, live connections, some caches

Three ways to keep servers stateless

ApproachHow it worksGood and bad
Server memory + sticky sessionsLoad balancer always sends a user to the same serverEasy, but a crash loses sessions and load can become uneven
Shared session storeSessions live in Redis or a database. Servers look them upAny server works, and sessions survive crashes. Adds a network call and a store to run
Client-side tokenA signed token (for example a JWT) carries the data in each requestNo lookup needed. Hard to revoke, and the token must stay small
๐Ÿ“Many systems are mixed
The web tier is stateless. The database and cache tier is stateful. The trick is knowing where the state sits, and making that place durable and replicated.
VisualizerCrash a server: who loses their session?Keep sessions in server memory and crash a server. Then try sticky sessions, and finally the shared store. Switch between โ€œEveryone logs inโ€ and โ€œNext clickโ€.
Where is the session kept?
Moment
Crash a server before the next click
๐Ÿ–ฅ๏ธServer 1holds sessions
๐Ÿ›’ U1๐Ÿ›’ U4
๐Ÿ–ฅ๏ธServer 2holds sessions
๐Ÿ›’ U2๐Ÿ›’ U5
๐Ÿ–ฅ๏ธServer 3holds sessions
๐Ÿ›’ U3๐Ÿ›’ U6
Sessions kept
6
of 6 users
Sessions lost
0
cart gone, log in again
Can any server be restarted?
No
it holds user data
Extra work per request
none
memory is local
Each user logs in and the server keeps the session in its own memory. Now switch to โ€œ2. Next clickโ€ to see what happens.

Simplified and fixed (no random numbers): the balancer's second-click choices in the plain mode are a fixed example, and a request for a crashed server moves to the next one. In real life about two in three users would move on 3 servers.

07How to Use It / Steps / Implementation

Making a service stateless

  1. 1
    Find the state
    Look for sessions, carts, uploaded files in a local folder, in-memory counters and local caches that must stay correct.
  2. 2
    Move sessions out
    Use a shared store such as Redis or a database, or switch to a signed token. Set an expiry.
  3. 3
    Move files out
    Store uploads in object storage, not on the server's own disk.
  4. 4
    Keep only a cache locally
    A local cache is fine if you can lose it at any time and rebuild it from the source.
  5. 5
    Make requests self-contained
    Pass the user id, token or session id in every request, and do not rely on an earlier call.
  6. 6
    Make the work repeatable
    Design so that a retried request on another server does no harm (idempotency).
  7. 7
    Test by killing servers
    Stop a random server during a test. If users notice, there is hidden state.
๐Ÿ’กWhen you must be stateful
Some things need state: databases, game rooms, live video. Then make the state safe: replicate it, snapshot it, and be able to rebuild a node from the copy. Use sharding so each server owns a part, with a clear rule of who owns what.
โš ๏ธThe shared store becomes critical
Moving sessions to Redis moves the single point of failure, it does not remove it. Replicate the store and watch it closely.

08Key Terms to Know

TermMeaning in easy words
StateWhat the system must remember to handle the next request correctly
StatelessThe server keeps no memory of earlier requests, so any server can serve any request
StatefulThe server remembers earlier requests, so the same server is needed again
SessionA series of requests from one user, with the data kept between them
Sticky sessionThe load balancer always sends a user to the same server
Session storeA shared place (Redis, database) that holds sessions for all servers
TokenA small signed piece of data the client sends with each request to prove who it is
Horizontal scalingAdding more servers instead of making one bigger
IdempotentSafe to repeat: doing it twice has the same result as doing it once
Shared-nothingServers do not share memory, and any shared data lives in a separate store
Connection affinityA long connection (such as a WebSocket) is tied to one server

09Pros, Cons and Trade-offs

โœ… Pros
  • Scale by simply adding servers
  • Crashes and restarts lose nothing
  • Plain load balancing works
  • Simple deploys and autoscaling
  • Easier to reason about and test
โš ๏ธ Cons
  • State must live somewhere else, which is one more system to run
  • Extra network call to read the state on each request
  • Token-based state is hard to revoke and must stay small
  • The shared store can become a bottleneck or a single point of failure
  • Some problems (live connections, games) need state in memory

Trade-offs

ChoiceWe gainWe lose
Stateless servers + shared storeFree scaling and crash safetyA store to run, and a lookup per request
Sticky sessionsSimple, fast local memorySessions lost on a crash, uneven load, hard rolling deploys
Client-side tokenNo server lookup at allLarger requests, hard to cancel a token before it expires
Stateful for speedVery low latency, rich local dataHarder to scale, move and recover

10Common Problems and Mistakes

Common mistakes

  1. Hidden state. A global variable, a local file or an in-memory counter that quietly makes the server stateful.
  2. Sticky sessions as a long-term fix. They hide the problem. A crash still logs users out.
  3. Huge tokens. Putting a lot of data into every request slows each call and may leak data.
  4. An unreplicated session store. One Redis node goes down and every user is logged out.
  5. Files on local disk. A user uploads a photo to server 1 and server 2 cannot find it.
  6. Per-server caches that go stale. Different servers show different answers.
  7. Scaling in too fast. Removing servers that still hold live sessions or connections.

Things to watch

๐ŸงŸOrphaned sessions
Set expiry times so old sessions are cleaned up.
๐Ÿ”ŒLong connections
WebSockets pin users to a server. Plan for graceful draining and reconnecting.
๐ŸขSlow store
Every request now waits for the store. Keep it fast and close.
๐Ÿ”“Token safety
Sign tokens, use short lifetimes, and do not put secrets inside them.

11Real-World Examples

๐Ÿ›’Online shops
Web servers are stateless, and carts live in a database or a cache, so any server can show your cart.
โš“Kubernetes apps
Stateless deployments restart freely. Stateful sets and volumes are used for databases.
ฮปServerless
Functions keep no state between calls, and use databases, queues and object storage.
๐ŸŽฎMultiplayer games
A match room lives in the memory of one game server. A matchmaker routes players to it.
๐Ÿ’ฌChat systems
Connections are pinned to servers, while messages are saved in a shared store.
๐ŸŒREST APIs
A design rule: each request carries what the server needs, so no server-side session is required.
Mini case: login with a shared session store
๐Ÿ‘คLogin
โ†’โ†“
๐Ÿ–ฅ๏ธServer 2creates the session
โ†’โ†“save
๐Ÿ—ƒ๏ธSession store
โ†load
๐Ÿ–ฅ๏ธServer 3serves the next click
Stateless servers State
Any server can serve the second request.

12Related Topics to Read Next

Scalabilityโ†’

Stateless servers are what make horizontal scaling easy.

Sticky Sessionsโ†’

A shortcut that keeps servers stateful.

Session vs Token Based Authโ†’

Two ways to keep login state.

JWTโ†’

A token that carries state in the request.

What are Load Balancers?โ†’

They can spread requests freely only when servers are stateless.

Failoverโ†’

Stateless servers fail over with almost no work.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Stateless: the server remembers nothing, so any server can answer any request.
  • โœ”Stateful: the server remembers you, so the next request needs the same one.
  • โœ”Move state out: shared store (Redis, DB), object storage, or a signed token.
  • โœ”Sticky sessions: a quick fix. A crash still loses the sessions.
  • โœ”Gain: easy scaling, crash safety, simple balancing, easy deploys.
  • โœ”Cost: an extra store to run and a lookup per request.
  • โœ”Still stateful: databases, games, WebSockets, some caches. Replicate them.
  • โœ”One line: โ€œKeep servers disposable, and keep the important data somewhere safe.โ€
โ† Previous
Failover
Next โ†’
Concurrency vs Parallelism