Stateless vs Stateful Services

Why keeping app servers stateless lets you scale them freely, and where the state goes instead.

What is it?

State is any data a server remembers between requests: a logged-in user's session, a shopping cart, an uploaded file sitting on local disk, an in-memory counter.

A stateful service keeps that data inside a specific server, so the next request must reach the same server. A stateless service keeps nothing between requests: each request carries what it needs (like a token), and any shared data lives in an external store such as a database or cache. With stateless servers, any instance can handle any request.

That property is what makes horizontal scaling easy: add servers, remove servers, or lose a server, and users don't notice. The state still exists; it has just moved to systems built to manage it.

Explain like I'm 10

A stateful service is a shop where only the cashier who started your order can finish it, because the order is in their head. A stateless service is a shop where the order is written on a ticket you carry (or in a shared system), so any cashier can help you, and a cashier going home doesn't lose anything.

Examples

Stateful vs stateless session handling (Express)

// Stateful: sessions live in this process's memory.
const sessions = new Map<string, { userId: string }>();
app.get("/me", (request, response) => {
  const session = sessions.get(request.cookies.sid); // lost on restart,
  response.json(session);                            // missing on other servers
});

// Stateless: the session lives in a shared store (Redis).
app.get("/me", async (request, response) => {
  const raw = await redis.get("session:" + request.cookies.sid);
  response.json(raw ? JSON.parse(raw) : null);       // any server can answer
});

Fully stateless auth with a signed token

import { jwtVerify } from "jose";

app.get("/me", async (request, response) => {
  const token = request.headers.authorization?.replace("Bearer ", "") ?? "";
  // The token carries the user id and is signed, so no lookup is needed.
  const { payload } = await jwtVerify(token, signingKey);
  response.json({ userId: payload.sub });
});

No session store at all, but you can't revoke a token before it expires without adding a denylist (which is state again). That's why such tokens are kept short-lived.

How it works

Where state goes in a stateless design - Database: durable business data (users, orders). The source of truth. - Distributed cache / session store (Redis, Memcached): sessions, rate-limit counters, short-lived data that must be fast and shared. - Object storage (S3-style): uploaded files, instead of the app server's local disk. - The client: signed tokens (JWTs) or signed cookies that carry identity and small claims. - Queues / streams: in-progress background work, so a crashed worker doesn't lose a job.

Sticky sessions are the halfway option: the load balancer pins each user to one server (via a cookie or IP hash), so in-memory sessions keep working. It's simple, but: - Load becomes uneven (one server collects heavy users). - When that server dies or is drained for a deploy, its users lose their session. - Autoscaling down means cutting off pinned users.

Stateful services are still needed, and they're scaled differently. Databases, caches, Kafka brokers, and WebSocket or game servers hold state by nature. They scale with replication (copies for reads and failover) and partitioning/sharding (each node owns part of the data), plus careful routing so requests reach the node that owns the data. These are harder to operate, which is exactly why you push state out of the many app servers and into a few specialised systems.

Stateless app tier (any server, any request)
                 ┌──▶ App 1 ─┐
  Users ─▶ LB ───┼──▶ App 2 ─┼──▶ Redis (sessions, counters)
                 └──▶ App 3 ─┘──▶ Database (source of truth)
                               ──▶ Object storage (files)

Sticky sessions (stateful app tier)
  User A ─▶ LB ─▶ always App 1   (App 1 dies → User A logged out)
  User B ─▶ LB ─▶ always App 2

Why does it exist?

Horizontal scaling, autoscaling, rolling deploys and surviving server crashes all require that servers be interchangeable. If a server holds unique data, every one of those operations risks losing it. Moving state to dedicated stores concentrates the hard problems (durability, replication, consistency) in a few systems designed for them.

When to use it

Make web and API servers, background workers and serverless functions stateless by default. That's the standard for anything behind a load balancer that needs to scale out, autoscale or deploy without downtime.

When not to use it

Some workloads are inherently stateful and fighting that costs too much: long-lived WebSocket connections, multiplayer game rooms, collaborative editing sessions, and in-memory stream processing. Keep the state, but route users consistently (e.g. by room id with consistent hashing) and plan for handover when a node fails. And a single-server app with no scaling needs can keep in-memory state.

Common mistakes

  • Writing uploaded files to the app server's local disk, then losing them (or not finding them) when the next request hits a different server.

  • Keeping caches or counters in process memory and expecting them to be consistent across servers (e.g. an in-memory rate limiter that lets N× the limit through with N servers).

  • Relying on sticky sessions as the scaling strategy, then losing sessions on every deploy or crash.

  • Calling a service 'stateless' while it secretly depends on local scheduled jobs or local temp files.

  • Putting large or sensitive data into client-side tokens, making every request heavy or leaking data (JWT payloads are encoded, not encrypted).

Practice exercises

  1. Easy:

    List every piece of state a typical login + shopping cart flow needs, and say where each should live in a stateless design.

  2. Medium:

    A team's rate limiter keeps counts in a per-process Map, and they just went from 1 to 8 servers. Explain what breaks and redesign it.

  3. Hard:

    Design a chat service where each user holds a WebSocket connection to one server. How does a message from a user on server A reach a user on server B, and what happens when server B crashes?

Interview questions

What does it mean for a service to be stateless?

It keeps no client-specific data between requests. Each request contains everything needed (e.g. a token), and shared data lives in external stores, so any instance can serve any request.

Why do stateless services scale horizontally more easily?

Instances are interchangeable, so a load balancer can send any request anywhere, and you can add, remove or replace instances without moving data or losing user sessions.

If app servers are stateless, where does the state go?

Into the database (durable data), a distributed cache like Redis (sessions, counters), object storage (files), the client (signed tokens), and queues (pending work).

What are sticky sessions, and what are their downsides?

The load balancer pins a user to one server so in-memory state works. Downsides: uneven load, users lose state when that server fails or is drained, and autoscaling or deploys become disruptive.

JWT vs server-side sessions: what's the trade-off?

JWTs need no lookup per request and scale trivially, but can't be revoked before expiry without a denylist and grow request size. Server-side sessions are easy to revoke and keep data private, but need a fast shared store.

Why is an in-memory cache on each app server risky?

Each server has its own copy, so they can disagree, and invalidation must reach every server. It's fine for immutable or slightly stale data; for shared mutable data use a central cache or short TTLs.

How do you scale a stateful service like a database?

Replication for read scaling and failover, and partitioning/sharding so each node owns a subset of data, with routing that sends each request to the owner. Both bring consistency and rebalancing challenges.

How would you scale WebSocket servers, which are inherently stateful?

Keep connection state on the server but route consistently, store durable state elsewhere, and use pub/sub (e.g. Redis or Kafka) so a message published anywhere reaches the server holding the recipient's connection. Clients reconnect to another node on failure.

How does statelessness affect deployments?

Rolling and blue-green deploys become safe: drain an instance, replace it, and no user data is lost. With stateful instances you must migrate or drain state first, or users lose it.

Can a 'stateless' tier become a bottleneck because of state?

Yes. The state moved to the shared store, so that store's throughput and availability now cap the whole tier. You then scale it (replicas, sharding, caching) and treat it as a critical dependency.