Stateless Architecture Doesn't Remove State. It Relocates It | PulseSoft
Skip to content

Stateless Architecture Doesn't Remove State. It Relocates It

PulseSoft Team · · 13 min read

A traffic spike arrives, the autoscaler adds twelve application instances, and latency recovers within minutes. An hour later the autoscaler scales back in, and a few hundred users are suddenly logged out, several large file uploads fail at 80%, and a batch of payment requests is processed twice. The application tier scaled exactly as designed. So what broke?

The answer is that the instances being removed were not actually stateless. They held sessions, partial uploads, and in-flight request records in memory, and the system's correctness quietly depended on those instances continuing to exist.

Stateless architecture is usually described as a scaling technique, but it is better understood as a contract about where state lives and who owns it. Stateless services scale easily because they have pushed every piece of durable or shared state into systems designed to hold it. That relocation is not free. It turns your session store, database, and object storage into the true scaling and consistency boundaries of the system.

This article explains what statelessness actually guarantees, which state must be externalized, how sessions, uploads, and long-lived connections complicate the model, and when keeping local state is the correct engineering decision.

The Core Problem: What "Stateless" Actually Promises

A useful definition: state is any information that outlives a single request and influences the outcome of a future request. A request handler's local variables are not state in this sense. A user's session, a partially uploaded file, a rate limiter's counter, a "this request was already processed" marker, and an open WebSocket connection all are.

A stateless service makes two promises, and both are invariants:

  1. Any instance can serve any request at any time.
  2. Any instance can disappear at any time without losing anything a client depends on.

These invariants are what make horizontal scaling trivial. If they hold, the load balancer needs no routing intelligence, the autoscaler can add or remove instances freely, deployments can replace instances in any order, and a crashed instance is a capacity event rather than a correctness event.

The moment an instance holds state that matters, both invariants break. Requests must be routed to the instance that has the state, so the load balancer needs affinity. Removing the instance now destroys data, so scale-in and deployments need draining logic. A crash becomes a data-loss event.

Statelessness moves the bottleneck

Consider an API service that reads from a database and publishes to a message broker. Because the API tier is stateless, scaling it is easy. But every instance opens its own connection pool to the same database.

Now suppose the database becomes slow rather than unavailable, perhaps because a large query is saturating I/O. The causal chain looks like this:

database latency rises
  → each request holds its DB connection longer
  → connection pools exhaust on every API instance
  → requests queue waiting for a connection
  → API latency rises past client timeouts
  → clients retry
  → more requests arrive at an already saturated tier
  → autoscaler sees high latency and adds instances
  → new instances open more database connections
  → database contention gets worse

The final step is the important one. Scaling a stateless tier in response to a slow stateful dependency increases load on the dependency. Statelessness made the application tier elastic, but it concentrated all shared state, and therefore all contention, in one place. The system did not eliminate the scaling problem; it moved the problem to the component that is hardest to scale.

This is the central insight of stateless architecture: the application tier scales horizontally precisely because the hard parts have been delegated elsewhere. Understanding a stateless system means understanding the systems it delegates to.

Distributed Systems Deep Dive: Where the State Goes

Externalizing state and the cost of the network hop

Externalizing state means moving it into a system whose job is to own it: a database for authoritative records, a cache or key-value store for sessions and ephemeral coordination, object storage for blobs, a queue for pending work.

The mental model is a separation between compute that is disposable and state that is durable. Compute becomes a fungible pool; state gets its own replication, backup, and consistency mechanisms.

The cost appears in three places.

First, latency. State that was a memory read is now a network round trip. A request that touches session data, a feature flag, a rate limit counter, and a database row now makes four remote calls, each with its own tail latency. Tail latencies compound across fan-out: if each call has a 1% chance of being slow, a request making four such calls has roughly a 4% chance of hitting at least one.

Second, availability. The state store is now on the critical path of every request. A stateless tier with 50 instances is only as available as the session store all 50 depend on.

Third, consistency. Once state lives behind a network boundary, it can be replicated, and replication introduces lag. A user who updates their profile through one instance and immediately reads it through another may be served from a replica that has not yet applied the write. Statelessness made "which instance?" irrelevant, but "which replica?" now matters. Read-your-writes guarantees must be designed explicitly, for example by routing reads to the primary for a short window after a write, or by tracking a replication position in the session.

Session management in distributed systems

Sessions are the canonical stateful concern, and there are three common designs.

Sticky sessions keep session data in instance memory and configure the load balancer to route each user to the same instance. This is simple and fast, but it violates both statelessness invariants. Load distribution depends on how users are spread, not how requests are spread, so a handful of heavy users can create hot instances. Scale-out does not help existing users, because they remain pinned to old instances. Scale-in and deployments must drain instances or log users out.

A centralized session store moves session data into a shared key-value store. Any instance can serve any user. The cost is a remote read on most requests and a new critical dependency. At larger scale, the session store must itself be partitioned, and a single session key under heavy concurrent access becomes a hot partition.

Signed tokens (such as JWTs) put session claims in the client's request, signed by the server. Instances verify the signature locally and need no session store at all. This is the most horizontally scalable option, and it is the clearest illustration of state relocation: the state still exists, it has simply moved to the client.

The complexity reappears in revocation. A signed token is valid until it expires, so logging a user out or revoking a compromised credential requires either short token lifetimes paired with refresh tokens (whose validity is checked against server-side state) or a revocation list (which is server-side state). Key rotation adds another coordination problem: every instance must know which signing keys are currently valid. Signed tokens do not remove session state; they reduce how often you consult it.

Uploads, long-lived connections, and in-flight work

Large file uploads break statelessness in a way that is easy to miss. A 2 GB upload streamed through an API instance ties that upload to the instance's lifetime. If the instance is terminated during a deployment, the upload fails. If uploads are chunked and different chunks land on different instances, the chunks must be reassembled somewhere.

The standard resolution removes the application tier from the data path entirely. The API issues a short-lived, scoped upload URL (a presigned URL, in object storage terminology), and the client uploads directly to object storage, often using multipart uploads that can resume after failure. The API's role shrinks to authorization and recording metadata, and the upload's state (which parts have arrived) is owned by the storage system. The API instance can disappear mid-upload without consequence.

Long-lived connections such as WebSockets are harder, because the connection itself is state: it is bound to a specific process on a specific host. The usual design splits responsibilities. A thin connection gateway tier holds sockets and does little else. Business logic remains stateless and publishes messages to a pub/sub layer, which the gateways subscribe to and fan out to connected clients. The gateway tier is stateful, but its state is cheap to lose: a client whose gateway dies reconnects to another one and resynchronizes from durable storage.

Idempotency: statelessness makes retries routable, not safe

Stateless services encourage retries, because a failed request can simply be retried against another instance. But a retry is only safe if the operation is idempotent. If a client's payment request times out, the client cannot tell whether the charge failed or succeeded with a lost response.

Idempotency keys solve this, and they illustrate the core theme: the deduplication record must live in shared state, because the retry may arrive at any instance.

func (h *Handler) CreatePayment(w http.ResponseWriter, r *http.Request) {
	key := r.Header.Get("Idempotency-Key")
	if key == "" {
		http.Error(w, "missing Idempotency-Key", http.StatusBadRequest)
		return
	}
	ctx := r.Context()
	recordKey := "idem:" + key

	// Claim the key in a shared store. The retry may land on a different
	// instance, so this record cannot live in process memory.
	claimed, err := h.store.SetNX(ctx, recordKey, "pending", 24*time.Hour)
	if err != nil {
		// Fail closed: without the dedup record, a retry could charge twice.
		http.Error(w, "idempotency store unavailable", http.StatusServiceUnavailable)
		return
	}
	if !claimed {
		// Replay the stored result, or return 409 if the first attempt is in flight.
		h.replayOrConflict(w, r, recordKey)
		return
	}

	result, err := h.payments.Charge(ctx, decodePayment(r))
	if err != nil {
		if isDefinitelyNotApplied(err) {
			h.store.Del(ctx, recordKey) // safe to allow a fresh attempt
		}
		// On an ambiguous failure (e.g. timeout), keep the key claimed and
		// reconcile with the payment provider instead of risking a double charge.
		http.Error(w, "payment failed", http.StatusBadGateway)
		return
	}

	h.store.Set(ctx, recordKey, encodeResult(result), 24*time.Hour)
	writeJSON(w, http.StatusCreated, result)
}

Two details matter more than the syntax. When the idempotency store is unavailable, the handler fails closed, choosing correctness over availability. And an ambiguous downstream failure does not release the key, because releasing it would reintroduce the exact double-execution risk the key exists to prevent. Note also that the claim and the charge are separate operations; the strongest form of this pattern writes the idempotency record in the same database transaction as the business effect.

Enjoying this so far?

Join thousands of engineers receiving practical engineering, Cloud, Distributed Systems, Infrastructure and AI engineering insights.

No spam. Unsubscribe anytime.

Architecture: A Stateless System With Explicit State Ownership

Consider a hypothetical multi-tenant SaaS document platform. Users authenticate, edit document metadata, upload files, and receive real-time notifications.

                    Client
          |           |            |
          | HTTPS     | direct     | WebSocket
          v           | upload     v
   Load Balancer      |     Connection Gateways (stateful, disposable)
          |           |            ^
          v           |            | subscribe
   API Instances (stateless)       |
     |      |      |      |        |
     v      v      v      v        |
 Session  Primary  Read    Pub/Sub ┘
  Store     DB    Replicas    ^
                     ^        |
   Object Storage <--┘        |
          |                   |
          v                   |
      Event Queue --> Worker Pool (stateless, idempotent)

Request flow. The load balancer distributes requests with no affinity. An API instance validates a token locally, consults the session store only for revocation and refresh, and reads from replicas or the primary depending on the request's consistency needs.

State ownership. Each piece of state has exactly one owner:

StateOwnerLoss tolerance
User and document recordsPrimary databaseNone
Session validity, revocationSession storeLow (users re-authenticate)
File contents and upload progressObject storageNone
Pending background workEvent queueNone (at-least-once delivery)
Open client connectionsConnection gatewaysHigh (clients reconnect)
Idempotency recordsShared store or primary DBNone within the retry window
Hot lookups, parsed configsLocal in-process cacheTotal (rebuilt on demand)

Failure boundaries. Losing an API instance or worker costs capacity only. Losing a gateway costs a reconnect. Losing the session store degrades authentication. Losing the primary database stops writes. The table above is effectively the system's failure model: correctness depends only on the rows with zero loss tolerance.

Scaling boundaries. API instances, workers, and gateways scale horizontally without coordination. The primary database, the session store, and the pub/sub layer do not; they scale through replication, partitioning, or vertical capacity, each with its own operational cost. When this system runs out of headroom, it will almost certainly be in one of those three places.

Recovery behavior. Workers consume from the queue with at-least-once semantics, so a worker that crashes mid-task causes redelivery. That is only correct because worker tasks are idempotent. Statelessness made the worker disposable; idempotency made disposal safe.

Tradeoffs: Stateful vs Stateless Services

Stateless is a strong default, not a universal rule. The relevant question is not "is this service stateless?" but "what does losing this state cost, and who pays for it?"

Session strategy comparison

ApproachSolvesMakes harderAt scaleFailure mode
Sticky sessionsFast, simple session accessLoad balancing, deploys, scale-inHot instances; scale-out helps only new usersInstance loss logs users out
Centralized session storeTrue request portabilityAdds a remote hop and critical dependencyStore must be partitioned; hot keys emergeStore outage blocks authenticated traffic
Signed tokensRemoves per-request lookupsRevocation, key rotation, token sizeScales with compute; verification is localCompromised tokens stay valid until expiry

When local state is justified

Local state is appropriate when losing it costs latency, not correctness. Several categories qualify:

  • Caches of immutable or derivable data. Compiled templates, parsed configuration, reference data that changes rarely. Losing them means recomputation.
  • Connection pools. These are stateful by nature and entirely reconstructible.
  • Approximate local rate limiting. Dividing a global limit across instances tolerates imprecision in exchange for avoiding a remote call on every request. This is acceptable for abuse protection and unacceptable for billing-grade quotas.
  • Deliberately stateful, partitioned services. Multiplayer game sessions, collaborative editing, and stream processors with large working sets often perform better when a specific node owns a specific partition of state in memory. This is a legitimate architecture, but it requires what stateless services avoid: partition assignment, failover, state checkpointing, and rebalancing. It should be chosen deliberately, not drifted into.

The anti-pattern is accidental state: an in-memory map that "temporarily" holds pending jobs, a local lock assumed to be global, a scheduled task that runs on every instance because nobody noticed there were twenty of them. These are not design decisions; they are invariant violations that remain invisible until the instance count or deployment pattern changes.

Failure Modes and What Happens at Scale

The illustrative numbers below show how behavior changes as constraints change; they are not benchmarks.

At 10 requests/second, a single instance (or two for redundancy) handles everything. Statelessness matters mainly for deployments: without it, every deploy logs users out or drops in-flight uploads. Adding a distributed session store at this scale may be premature; a database-backed session table is often sufficient.

At 1,000 requests/second, the API tier might run dozens of instances, and arithmetic starts to matter. Forty instances with a pool of 20 database connections each means 800 connections. PostgreSQL, for example, uses a process per connection, so connection count itself becomes a resource problem, and a connection pooler between the application and database becomes necessary. Deployments that replace all instances at once also replace all warm local caches at once, sending a burst of cache misses to the database. Rolling deployments and cache warming become capacity concerns.

At 100,000 requests/second, the shared state systems dominate the design. The session store must be partitioned, and popular tenants or users create hot keys. Per-request session lookups become expensive enough that signed tokens with short lifetimes are attractive. Retry behavior becomes a first-order risk: when an instance fails, the load balancer and clients retry its in-flight requests elsewhere, and if the underlying cause is a slow dependency, those retries multiply load on the component that is already struggling. Without retry budgets, jittered backoff, and circuit breakers, a partial failure in one state store becomes a cascading failure across the stateless tier.

Across all scales, the pattern is consistent: the stateless tier rarely fails on its own. It fails by amplifying problems in the stateful systems behind it.

Engineering Principles

Statelessness relocates state; it never eliminates it. Every stateless service depends on stateful systems, and its real scalability is bounded by theirs.

Classify state by the cost of losing it. State whose loss costs only latency can live locally. State whose loss costs correctness needs a durable owner.

Every piece of state should have exactly one owner. When two components both believe they own the same data, consistency becomes a negotiation rather than a guarantee.

Retries are only safe when operations are idempotent. Stateless routing makes it easy to send a retry anywhere; it does nothing to make the retry harmless.

Scaling the stateless tier can worsen a stateful bottleneck. More instances mean more connections, more concurrent queries, and more contention on the shared dependency.

Move large data out of the request path. Uploads, downloads, and long-running work should flow through systems designed to own them, leaving the API to authorize and coordinate.

Deliberate state beats accidental state. A partitioned stateful service with explicit failover is sound engineering. An in-memory map that silently became load-bearing is a latent outage.

Final Thoughts

Stateless architecture is often presented as a checkbox: keep servers stateless and scaling becomes easy. The more accurate framing is that statelessness is a boundary-drawing exercise. It separates disposable compute from durable state, and in doing so it makes one tier trivially elastic while concentrating every hard problem (consistency, coordination, contention, durability) in a smaller number of systems designed to handle them.

That concentration is the real benefit. It is far easier to reason about three stateful components with explicit ownership than about fifty application instances each holding fragments of state nobody documented.

Experienced engineers evaluate a stateless system by asking where its state went, who owns it, what happens when that owner is slow, and what a retry does to it. These are the kinds of engineering problems that sit at the center of modern software systems: understanding where state lives, how components interact, and what happens when the assumptions between them stop being true.

Key Takeaways

  • Stateless services scale horizontally because any instance can serve any request and any instance can disappear safely; both properties depend on all meaningful state living in external systems.
  • Externalizing state adds a network hop, a critical dependency, and replication lag, so read-your-writes behavior must be designed rather than assumed.
  • Sticky sessions trade simple session access for uneven load distribution, painful deployments, and data loss on instance failure.
  • Signed tokens remove per-request session lookups but move complexity into revocation and key rotation, which still require server-side state.
  • Direct-to-object-storage uploads keep large transfers out of the API tier, so instance replacement no longer breaks in-flight uploads.
  • Idempotency records must live in shared storage, because a retry may reach a different instance than the original request.
  • Local state is justified when losing it costs only latency; when losing it costs correctness, it needs a durable owner or a deliberately designed stateful service.

Get insights like this in your inbox

Join thousands of engineers receiving practical engineering, Cloud, Distributed Systems, Infrastructure and AI engineering insights.

No spam. Unsubscribe anytime.