While basic round-robin or least-connected load balancing is effective for many scenarios, real-world applications often require more sophisticated techniques to ensure a seamless user experience and optimal server utilization. This section delves into advanced load balancing methods, focusing on how Nginx can be configured to handle these complexities.
Sticky sessions, also known as session persistence or session affinity, are crucial for applications that maintain user session state on a specific backend server. Without sticky sessions, a user's subsequent requests might be routed to a different server, causing them to lose their session data and potentially encounter errors. Nginx provides two primary methods for implementing sticky sessions.
The first method involves using cookies. When a client connects to a backend server for the first time, Nginx can set a cookie in the client's browser that identifies the backend server. Subsequent requests from that client will then carry this cookie, allowing Nginx to route them back to the same server. This is achieved using the sticky cookie directive within your upstream block.
upstream backend_servers {
sticky cookie srv_id expires=1h;
server 192.168.1.10;
server 192.168.1.11;
server 192.168.1.12;
}In this example, srv_id is the name of the cookie that Nginx will set. The expires=1h parameter specifies that the cookie should be valid for one hour. You can adjust this duration based on your application's session timeout.
The second method for sticky sessions relies on the client's IP address. This approach, known as 'client IP affinity' or 'least_conn' with IP hashing, directs all requests from a particular client IP address to the same backend server. While simpler to implement and requiring no cookie manipulation, it can lead to uneven load distribution if a significant number of users share the same IP address (e.g., users behind a corporate NAT).
upstream backend_servers {
ip_hash;
server 192.168.1.10;
server 192.168.1.11;
server 192.168.1.12;
}The ip_hash directive ensures that a client's requests are always sent to the same server as long as the server list remains the same. If a server goes down, its clients will be redirected to another server, but this is done only once, and then those clients will be sticky to the new server.