[Avg. reading time: 9 minutes]
Statefulness
The server stores information about the client’s current session in a stateful system. This is common in traditional web applications. Here’s what characterizes a stateful system:
Session Memory: The server remembers past interactions and may store session data like user authentication, preferences, and other activities.
Server Dependency: Since the server holds session data, the same server usually handles subsequent requests from the same client. This is important for consistency.
Resource Intensive: Maintaining state can be resource-intensive, as the server needs to manage and store session data for each client.
Example: A web application where a user logs in, and the server keeps track of their authentication status and interactions until they log out.
sequenceDiagram
participant C as Client
participant LB as Load Balancer
participant S1 as Server 1
participant S2 as Server 2
Note over C,S2: Initial Session Establishment
C->>LB: Initial Request
LB->>S1: Forward Request
S1-->>LB: Response (Session ID)
LB-->>C: Response (Session ID)
rect rgb(255, 255, 200)
Note over C,S2: Sticky Session Established
end
Note over C,S2: Session Continuation
C->>LB: Subsequent Request (with Session ID)
LB->>S1: Forward Request (based on Session ID)
S1-->>LB: Response (Data)
LB-->>C: Response (Data)
rect rgb(255, 255, 200)
Note over C,S2: Session Continues on Server 1
end
Note over C,S2: Session Termination
C->>LB: Logout Request
LB->>S1: Forward Logout Request
S1-->>LB: Confirmation
LB-->>C: Confirmation
rect rgb(255, 255, 200)
Note over C,S2: Session Ended
end
rect rgb(255, 255, 200)
Note right of S2: Server 2 remains unused due to stickiness
end
Stickiness (Sticky Sessions)
Stickiness or sticky sessions are used in stateful systems, particularly in load-balanced environments. It ensures that requests from a particular client are directed to the same server instance. This is important when:
Session Data: The server needs to maintain session data (like login status), and it’s stored locally on a specific server instance.
Load Balancers: In a load-balanced environment, without stickiness, a client’s requests could be routed to different servers, which might not have the client’s session data.
Trade-off: While it helps maintain session continuity, it can reduce the load balancing efficiency and might lead to uneven server load.
Methods of Implementing Stickiness
Cookie-Based Stickiness: The most common method, where the load balancer uses a special cookie to track the server assigned to a client.
IP-Based Stickiness: The load balancer routes requests based on the client’s IP address, sending requests from the same IP to the same server.
Custom Header or Parameter: Some load balancers can use custom headers or URL parameters to track and maintain session stickiness.