Skip to content
advanced Phase 85 · Distributed Fundamentals

Stateless vs Stateful

Stateless vs stateful systems, session handling in distributed systems, and state management strategies

45m
0 problems
Topic Progress 0%

Stateless vs Stateful Systems

Comparison

Stateless:                    Stateful:
Request → Any Node → Response  Request → Same Node → Response
No node affinity              Node affinity required
Easy to scale                 Harder to scale
Fault tolerant                State loss on failure

Magento State Components

Component     | State Type | Location
──────────────|────────────|──────────────────
User Session  | Stateful   | Redis/Memcached
Shopping Cart | Stateful   | Database/Cache
User Context  | Stateless  | Request headers
Configuration | Stateless  | Config files

Statelessness Benefits

1. Horizontal scaling: Any node handles any request
2. Fault tolerance: Node failure doesn't lose state
3. Load balancing: No sticky sessions needed
4. Deployment: Rolling updates without session loss

Session Handling in Distributed Systems

Session Storage Options

Option         | Pros                    | Cons
───────────────|─────────────────────────|─────────────────
Cookies        | Stateless, simple       | Size limited
Redis          | Fast, persistent        | Single point
Memcached      | Fast, simple            | No persistence
Database       | Persistent, queryable   | Slower
JWT            | Stateless, scalable     | No server-side

Magento Session Config

// app/etc/env.php
'session' => [
    'save' => 'redis',
    'redis' => [
        'host' => 'redis-cluster.example.com',
        'port' => '6379',
        'timeout' => '2.5',
        'database' => '0',
        'compression_threshold' => '2048',
        'compression_library' => 'zstd'
    ]
],

Session Best Practices

1. Store minimal data in session
2. Use external session storage (Redis)
3. Set appropriate TTL
4. Compress session data
5. Handle session conflicts gracefully

State Management Strategies

State Partitioning

Strategy      | Description               | Use Case
──────────────|───────────────────────────|──────────────
Sticky Sessions | Route to same node      | Legacy apps
Shared Storage  | External state store     | Modern apps
Event Sourcing | State from events        | Audit trails
CQRS           | Separate read/write      | Complex domains

Event Sourcing for State

// Instead of updating state directly
// Record events that lead to state

class Order {
    private $events = [];
    
    public function addItem($item) {
        $this->events[] = new ItemAdded($item);
    }
    
    public function applyEvents() {
        $state = new OrderState();
        foreach ($this->events as $event) {
            $state = $event->apply($state);
        }
        return $state;
    }
}
// Current state = replay all events

CQRS Pattern

Commands (Write):          Queries (Read):
- Place order              - Get order details
- Update inventory         - List orders
- Process payment          - Search products

Write DB → Events → Read DB
(optimized for writes)    (optimized for reads)

Stateless Design Patterns

Stateless API Design

// BAD: Stateful - depends on server state
$session = $_SESSION['cart']; // Stateful
$cart->addItem($product);

// Stateless - all state in request
$cart = $this->cartService->getCart($request->getCartId()); // From storage
$cart->addItem($product);
$this->cartService->save($cart); // Explicit save

JWT for Stateless Auth

// Stateless authentication with JWT
$token = JWT::encode([
    'user_id' => $userId,
    'exp' => time() + 3600,
    'iat' => time()
], $secret);

// Any node can verify token
$decoded = JWT::decode($token, $secret, ['HS256']);
$user = $this->userService->find($decoded->user_id);

Stateless Microservices

Principle: Each request contains all needed information

1. No server-side session state
2. All state in external storage
3. Requests are self-contained
4. Any node can handle any request

Quiz

1. What is a stateless system?

Question 1 options

2. What is the main benefit of stateless design?

Question 2 options

3. What is event sourcing?

Question 3 options

Flashcards

Question

Stateless system?

Answer

No server-side state between requests, any node handles any request

Question

Stateful system?

Answer

Maintains server-side state, requires node affinity

Question

Event sourcing?

Answer

Reconstruct state by replaying events

Question

CQRS pattern?

Answer

Separate read and write models for optimization

Revision Notes

Key Takeaways

  • 1. Stateless systems enable easy horizontal scaling and fault tolerance
  • 2. Store sessions in external storage (Redis) for distributed systems
  • 3. Event sourcing reconstructs state from event sequences
  • 4. CQRS separates read and write optimization
  • 5. JWT enables stateless authentication

Interview Tips

  • Compare stateless vs stateful trade-offs
  • Explain event sourcing and CQRS patterns
  • Discuss session handling strategies for distributed systems

Cheat Sheet

Stateless vs Stateful:
  Stateless: Easy scaling, fault tolerant
  Stateful: Node affinity, harder to scale

Session Handling:
  Redis: Fast, persistent, recommended
  Memcached: Fast, no persistence
  JWT: Stateless tokens

State Patterns:
  Event Sourcing: State from events
  CQRS: Separate read/write models

Design:
  Minimal session data
  External storage
  Self-contained requests