Managing Distributed Sessions
1. Understanding Session Management Strategies
| Strategy | Storage | Trade-offs |
|---|---|---|
| Sticky sessions | Memory on one server | Simple; uneven load, lost on restart |
| Centralized store | Redis/Memcached/DB | Stateless servers; extra hop |
| Session replication | Replicate across servers | HA; bandwidth overhead |
| Token (JWT) | Client-side, signed | Stateless; revocation hard |
2. Implementing Sticky Sessions
| Method | Detail |
|---|---|
| Cookie-based | LB inserts cookie |
| IP hash | NGINX ip_hash |
| Application cookie | App-set; LB reads |
| Risks | Hot backend; failover loses session |
3. Implementing Session Replication
| Mode | Detail |
|---|---|
| All-to-all | Every node has all sessions |
| Buddy / pair | Replicate to one peer |
| Tomcat DeltaManager | Multicast deltas |
| Cost | Network + memory linear in replicas |
4. Implementing Centralized Session Store
Example: Spring Session + Redis
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
public class SessionConfig {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(
new RedisStandaloneConfiguration("redis-host", 6379));
}
}
| Store | Detail |
|---|---|
| Redis | Most common; TTL via EXPIRE |
| Memcached | Volatile; LRU eviction |
| DynamoDB | Managed, TTL items |
5. Implementing Token-Based Sessions (JWT)
| Part | Content |
|---|---|
| Header | {"alg":"RS256","typ":"JWT"} |
| Payload | Claims: sub, exp, iat, aud, custom |
| Signature | HMAC or asymmetric |
| Storage | Cookie (HttpOnly, Secure, SameSite) or Authorization header |
| Revocation | Short TTL + refresh token; or revocation list |
Warning: Never store secrets in JWT payload — it's only base64-encoded, not encrypted. Use JWE for confidentiality.
6. Handling Session Expiration
| Type | Detail |
|---|---|
| Idle timeout | N minutes since last activity |
| Absolute timeout | Hard cap from creation |
| Sliding window | Renew on activity |
| Server-initiated | Force logout (password change) |
7. Implementing Session Affinity
| Method | Detail |
|---|---|
| Cookie | Set by LB or app |
| Connection (L4) | TCP connection pinned |
| Source-IP hash | Risk: NAT collapses many users |
8. Understanding Stateless vs Stateful Services
9. Implementing Session Migration
| Trigger | Action |
|---|---|
| Node drain | Persist sessions; forward to peer |
| Rolling deploy | Replicate to replacement before old shutdown |
| Failover | Recover from centralized store |
10. Handling Session Security
| Concern | Mitigation |
|---|---|
| Hijacking | HttpOnly + Secure cookies; HTTPS only |
| Fixation | Rotate session id on login |
| CSRF | SameSite=Lax/Strict; CSRF tokens |
| XSS | HttpOnly cookies; CSP headers |
| Replay | Short TTL; nonce / jti claim |