Linux Exercise 11b - optional - Sticky-Sessions
Optional Extension: Sticky Sessions (IP Hash) with Nginx
Section titled “Optional Extension: Sticky Sessions (IP Hash) with Nginx”1. Goal
Section titled “1. Goal”In this extension you will:
- Configure sticky sessions using Nginx’s
ip_hashdirective - Ensure that the same client is routed to the same backend server
- Compare behavior with and without sticky sessions
Use your existing backend_pool and loadbalance.local site.
2. Important Notes
Section titled “2. Important Notes”ip_hashcannot be combined with some other upstream features (e.g. per-server weight in classic Nginx upstream).- Sticky sessions are helpful when:
- Backends store session state in memory
- You want one user to hit the same backend most of the time
3. Step 1 – Enable ip_hash in Upstream
Section titled “3. Step 1 – Enable ip_hash in Upstream”Edit:
sudo nano /etc/nginx/sites-available/loadbalance.localFind your upstream block:
upstream backend_pool { server 127.0.0.1:8001; server 127.0.0.1:8002;}Change it to:
upstream backend_pool { ip_hash; server 127.0.0.1:8001; server 127.0.0.1:8002;}Save, test, and reload:
sudo nginx -tsudo systemctl reload nginx4. Step 2 – Test Sticky Behavior
Section titled “4. Step 2 – Test Sticky Behavior”From your client machine (the one with the browser / curl):
for i in {1..10}; do curl http://loadbalance.local/; echo; doneExpected behavior:
- All (or almost all) responses show the same backend (either
1or2)
Because your IP is hashed, you will consistently hit one backend.
5. Step 3 – Compare to Non-Sticky Behavior
Section titled “5. Step 3 – Compare to Non-Sticky Behavior”Comment out ip_hash and reload Nginx:
upstream backend_pool { # ip_hash; server 127.0.0.1:8001; server 127.0.0.1:8002;}Reload, then run the same test:
for i in {1..10}; do curl http://loadbalance.local/; echo; doneNow, responses should alternate between backend 1 and backend 2 (round robin), instead of sticking to one.
6. Step 4 – Document Your Findings
Section titled “6. Step 4 – Document Your Findings”In your protocol, answer:
-
What difference do you observe with and without
ip_hash? -
In which scenarios are sticky sessions useful?
-
What are potential downsides of sticky sessions?
Examples:
- One backend can become overloaded if many users share similar IP ranges.
- Harder to drain a single backend for maintenance.
Optional: If you have access to another client machine with a different IP, repeat the test from that machine and confirm it gets “stuck” to the other backend.