Skip to content

Linux Exercise 11c - optional - Weighted-Load-Balancing

Optional Extension: Weighted Load Balancing with Nginx

Section titled “Optional Extension: Weighted Load Balancing with Nginx”

In this extension you will:

  • Configure weighted load balancing for your backend pool
  • Make one backend receive more traffic than the other
  • Verify the distribution using curl

Weights are useful when:

  • One backend server has more CPU/RAM
  • You want to gradually shift traffic to a new version (canary style)

Edit:

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

Find your upstream block and adjust it as follows (ensure ip_hash is NOT used here):

upstream backend_pool {
server 127.0.0.1:8001 weight=3;
server 127.0.0.1:8002 weight=1;
}

Explanation:

  • Backend 1 has weight 3
  • Backend 2 has weight 1
  • Ratio of requests: ~3:1 (about 75% vs 25%)

Save, test, and reload:

Terminal window
sudo nginx -t
sudo systemctl reload nginx

Run multiple requests:

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

Count how many times you see each backend:

  • {"backend":"1"}
  • {"backend":"2"}

You should see backend 1 significantly more often than backend 2.

For a more precise count, you can use:

Terminal window
for i in {1..50}; do curl -s http://loadbalance.local/; echo; done | sort | uniq -c

This will group and count occurrences.


Experiment by changing the weights:

upstream backend_pool {
server 127.0.0.1:8001 weight=5;
server 127.0.0.1:8002 weight=1;
}

Or:

upstream backend_pool {
server 127.0.0.1:8001 weight=1;
server 127.0.0.1:8002 weight=3;
}

Each time:

  1. Save the file
  2. Run sudo nginx -t
  3. Run sudo systemctl reload nginx
  4. Perform the test loop again

In your protocol, describe:

  • The weight values you tried
  • The approximate ratio of responses you observed
  • How weights could be used in real deployments, e.g.:
    • Slowly shifting traffic to a new version
    • Sending most traffic to a more powerful server
    • “Canary testing” a new backend for a small percentage of users