Skip to content

Linux Exercise 11b - optional - Sticky-Sessions

Optional Extension: Sticky Sessions (IP Hash) with Nginx

Section titled “Optional Extension: Sticky Sessions (IP Hash) with Nginx”

In this extension you will:

  • Configure sticky sessions using Nginx’s ip_hash directive
  • 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.


  • ip_hash cannot 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

Edit:

Terminal window
sudo nano /etc/nginx/sites-available/loadbalance.local

Find 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:

Terminal window
sudo nginx -t
sudo systemctl reload nginx

From your client machine (the one with the browser / curl):

Terminal window
for i in {1..10}; do curl http://loadbalance.local/; echo; done

Expected behavior:

  • All (or almost all) responses show the same backend (either 1 or 2)

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:

Terminal window
for i in {1..10}; do curl http://loadbalance.local/; echo; done

Now, responses should alternate between backend 1 and backend 2 (round robin), instead of sticking to one.


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.