Skip to content
intermediatePhase 44 · Web Architecture

Stateful Services

Manage stateful services with session affinity or external state stores.

45m
0 problems
Topic Progress0%

State Management

Stateful services maintain information about client sessions across requests.

Types of State

1. Session State
   - User login information
   - Shopping cart contents
   - User preferences

2. Application State
   - In-memory cache
   - Connection pools
   - Rate limiting counters

3. Distributed State
   - Leader election
   - Distributed locks
   - Coordination data

State Management Patterns

1. In-Process State
   State stored in server memory
   Fast but not shareable
   
   Client → Server A (state in memory)
   Client → Server A (same server required)

2. External State Store
   State stored in Redis/Memcached
   Shareable across servers
   
   Client → Any Server → Redis → State

3. Database State
   State stored in database
   Persistent but slower
   
   Client → Any Server → Database → State

State Consistency

Challenge: Keeping state consistent across servers

Solution 1: Single Source of Truth
- All servers read/write to same store
- Redis, database

Solution 2: State Replication
- State replicated across servers
- Consensus algorithms (Raft)

Solution 3: Eventual Consistency
- State may be temporarily inconsistent
- Conflict resolution strategies

Session Affinity

Session affinity (sticky sessions) routes the same client to the same server.

How Session Affinity Works

Client A → Load Balancer → Server 1 (stores session)
Client A → Load Balancer → Server 1 (sticky)
Client B → Load Balancer → Server 2 (stores session)
Client B → Load Balancer → Server 2 (sticky)

Implementation Methods

1. IP-based
   Hash(Client IP) → Server
   
   Problem: NAT, load balancers hide real IP

2. Cookie-based
   Server sets cookie with server ID
   Client sends cookie on subsequent requests
   
   Example: JSESSIONID=server1

3. URL-based
   Session ID in URL path
   Example: /app/SESSION123/page

Nginx Configuration

# IP Hash
upstream backend {
    ip_hash;
    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
}

# Cookie-based
upstream backend {
    hash $cookie_jsessionid consistent;
    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
}

Session Affinity Problems

1. Server Failure
   - Session data lost
   - User must re-login

2. Uneven Load
   - Long sessions → more traffic to one server
   - Poor load distribution

3. Scaling Difficulty
   - Can't freely add/remove servers
   - Session migration needed

4. Deployment Complexity
   - Must maintain sessions during deployment
   - Can't use blue-green easily

When to Use Session Affinity

Scenario Use? Alternative
Simple apps Maybe External store
Legacy apps Yes (temporarily) Migrate to stateless
Performance critical Yes Redis with connection pooling
High availability No External state store

External State Stores

External state stores decouple state from application servers.

Redis as State Store

Architecture:
Client → Any Server → Redis → Session Data

Benefits:
- Any server can access any session
- Fast (in-memory)
- Persistent options available
- High availability with replication

Redis Session Configuration

const session = require('express-session');
const RedisStore = require('connect-redis').default;
const redis = require('redis');

const client = redis.createClient({
  host: 'redis-cluster.example.com',
  port: 6379
});

app.use(session({
  store: new RedisStore({ 
    client,
    prefix: 'sess:'
  }),
  secret: 'your-secret',
  resave: false,
  saveUninitialized: false,
  cookie: { 
    secure: true,
    httpOnly: true,
    maxAge: 86400000  // 24 hours
  }
}));

Memcached vs Redis

Aspect Memcached Redis
Data types Strings only Multiple types
Persistence No Yes
Replication No Yes
Clustering Yes Yes
Use case Simple caching Complex state

Distributed State with Consensus

For critical state (leader election, locks):

ZooKeeper / etcd:
- Raft/Paxos consensus
- Strong consistency
- Leader election
- Distributed locks

Use Cases:
- Database leader election
- Distributed lock service
- Configuration management
- Service discovery

State Store Best Practices

  1. Choose appropriate store: Redis for sessions, Memcached for cache
  2. Set TTL: All state should expire
  3. Monitor memory: State stores can run out of memory
  4. Plan for failover: Replication and backup
  5. Encrypt sensitive data: Don't store plaintext secrets

Practice Problems

0/3solved
Design Stateful Services System

Design a scalable Stateful Services system. Cover high-level architecture, data model, and API design.

Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliability
Stateful Services Scaling

How would you scale Stateful Services to handle 10x the current load? Identify bottlenecks and solutions.

Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decomposition
Stateful Services Failure Modes

Analyze potential failure modes for Stateful Services and design mitigation strategies.

Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradation

Quiz

1. What is session affinity?

Question 1 options

2. What is the problem with session affinity for server failure?

Question 2 options

3. Why use Redis as an external state store?

Question 3 options

4. What is the difference between Memcached and Redis?

Question 4 options

Flashcards

Question

What is session affinity?

Answer

Routing the same client to the same server consistently. Implementation: IP hash, cookie-based, URL-based. Problem: server failure loses sessions.

Question

What are the problems with session affinity?

Answer

Server failure loses sessions, uneven load distribution, scaling difficulty, deployment complexity. Better to use external state store.

Question

Why use Redis as external state store?

Answer

Any server can access any session, enabling stateless services. Fast (in-memory), supports persistence and replication, high availability.

Question

When would you use ZooKeeper/etcd?

Answer

For critical distributed state: leader election, distributed locks, configuration management, service discovery. Provides strong consistency via consensus.

Question

What is Stateful Services?

Answer

Stateful Services is a key concept in system design.

Revision Notes

Key Takeaways

  • 1.Session affinity is simple but has reliability problems
  • 2.External state stores (Redis) enable stateless services
  • 3.Choose Redis for complex state, Memcached for simple caching
  • 4.Critical distributed state needs consensus (ZooKeeper/etcd)
  • 5.Always plan for state store failover and monitoring

Interview Tips

  • Prefer external state stores over session affinity
  • Discuss Redis for session management in scaled systems
  • Mention ZooKeeper/etcd for distributed coordination
  • Consider state store replication for high availability

Cheat Sheet

Stateful Services - Cheat Sheet

Types of State:

  • Session: User data, cart
  • Application: Cache, counters
  • Distributed: Leader election, locks

Session Affinity:

  • Route same client to same server
  • Methods: IP hash, cookie, URL
  • Problems: Server failure, uneven load

External State Stores:

  • Redis: Fast, multiple types, persistent
  • Memcached: Simple, strings only
  • ZooKeeper/etcd: Distributed state, consensus

Best Practices:

  • Use external stores over affinity
  • Set TTL for all state
  • Monitor memory usage
  • Plan for failover
  • Encrypt sensitive data