Course contentsShow
← System Design
Lesson 62 of 1,9192. Scaling FoundationsFree lesson

When Stateful Services Are Necessary

Use cases like WebSockets, streaming, and long-lived connections that require maintaining server state.

When Stateful Services Are Necessary

What you'll learn: When maintaining server state is unavoidable and actually the right choice for certain application types.

The Reality of Long-Lived Connections

While we've seen many benefits of stateless services, some applications fundamentally require a server to "remember" an ongoing relationship with a client. These aren't design flaws—they're inherent to how the application works.

WebSockets are a prime example. Unlike traditional HTTP requests that complete quickly, a WebSocket opens a persistent, two-way communication channel. The server must track which client owns which connection to route messages correctly. Think of it like a phone call—the connection stays open, and both parties can speak at any time. You can't just "forget" who's on the other end.

Streaming applications (video calls, live audio, gaming) need the server to maintain buffers, connection quality metrics, and synchronization state for each active session. A video conference server tracking who's muted, their video quality, and their audio stream can't simply restart that conversation on a different server mid-call.

Long-running transactions or workflows that span multiple steps over minutes or hours—like filling out a multi-page form with real-time validation, or a collaborative editing session—benefit from keeping that context alive in memory rather than constantly retrieving it from external storage.

The Trade-off

These stateful services are harder to scale (you need sticky sessions or connection-aware load balancing) and more fragile (a server crash drops all active connections). But attempting to force them into a stateless model creates worse problems: constant database hits, reconnection storms, and terrible user experience.

Key Takeaway: Stateful services are necessary when maintaining an active, persistent connection or session is core to the application's functionality—WebSockets, streaming, and real-time collaboration are classic examples where server state is unavoidable.