Handling State in Distributed Systems
### Stateful vs Stateless Systems
In a stateful system, the server remembers client data (state) from one request to the next. In a stateless system, every request contains all the information the server needs to fulfill it.
### The Problem with Stateful Servers
When scaling horizontally, if Server A stores a user's session, what happens if the load balancer routes their next request to Server B? The user appears logged out.
### Solutions for Managing State
1. **Sticky Sessions:** The load balancer ensures requests from a specific user always go to the same server. (Anti-pattern for scaling). 2. **Externalized State:** Store session data in a fast, distributed, in-memory cache like Redis or Memcached. This allows any server to handle any request. 3. **Stateless Tokens (JWT):** The client stores the state securely in a token (JSON Web Token), eliminating the need for server-side session storage entirely.

