Learn Nginx · 6/13

Load Balancing Traffic

7 min read

Nginx: Load Balancing Traffic 🚦

Welcome! Today, we're diving into one of Nginx's most powerful features: load balancing.

The "What" and "Why" of Load Balancing

Imagine a popular food truck with a single person taking orders, cooking, and serving. As the lunch rush hits, the line gets longer, and customers get hangry. This single point of failure is a bottleneck.

In the digital world, your server can be that food truck. When too many users try to access your website or application at once, it can slow down or even crash. 😱

Load balancing is the solution. It's like our food truck owner hiring more staff and opening up more service windows. A load balancer is a traffic cop that distributes incoming network traffic across multiple backend servers. This ensures that no single server gets overwhelmed, leading to:

  • Higher Availability: If one server goes down, the load balancer redirects traffic to the healthy ones.
  • Better Performance: By distributing the workload, your application can handle more users and respond faster.
  • Easier Scalability: Need to handle more traffic? Just add more servers to the pool.

Now, let's get our hands dirty and see how to make this happen with Nginx.


1. Defining Server Pools with the upstream Context

Before Nginx can distribute traffic, it needs to know which servers are available to handle the requests. This is where the upstream context comes in. It's a block in your Nginx configuration where you define a group, or "pool," of backend servers.

Think of it as creating a team roster. You give your team a name and then list all the players (servers) on that team.

How it works:

You define an upstream block within the http context of your nginx.conf file. Then, inside a server block, you use the proxy_pass directive to forward requests to the named upstream group.

Let's see an example:

nginx
http {
    # Define a group of servers
    upstream my_app_servers {
        server 192.168.1.10:8080;
        server 192.168.1.11:8080;
        server app3.example.com:8080;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://my_app_servers;
        }
    }
}

Breaking it down:

  • upstream my_app_servers { ... }: This defines a server pool named my_app_servers.
  • server 192.168.1.10:8080;: This is the address of a backend server. You can use an IP address or a domain name. If no port is specified, Nginx defaults to port 80.
  • proxy_pass http://my_app_servers;: This directive tells Nginx to forward any requests that come into this location block to the my_app_servers upstream group.

And that's it for a basic setup! Simple, right? Nginx will now distribute incoming requests among the three servers in the my_app_servers pool.


2. Choosing Your Strategy: Load Balancing Algorithms 🧠

Nginx doesn't just randomly throw traffic at your servers. It uses different strategies, or algorithms, to decide which server gets the next request. Let's look at the most common ones.

Round Robin (The Default)

This is the simplest method and Nginx's default behavior. It works like dealing cards in a game; each server gets a request in turn.

  • Request 1 -> Server A
  • Request 2 -> Server B
  • Request 3 -> Server C
  • Request 4 -> Server A
  • ...and so on.

When to use it: Round Robin is great when your servers have similar specifications and can handle a similar amount of load.

Configuration: You don't need to add any special directive for Round Robin, as it's the default.

nginx
upstream my_app_servers {
    server server1.example.com;
    server server2.example.com;
    server server3.example.com;
}

IP Hash

The ip_hash method ensures that requests from the same client IP address will always be directed to the same server. This is useful for applications that require "session persistence" or "sticky sessions," where a user needs to stay on the same server for the duration of their session.

Imagine you're filling out a multi-page form online. If each page you submit goes to a different server, the application might lose track of your progress. IP Hash prevents this by "sticking" you to one server.

How it works: Nginx calculates a hash based on the client's IP address to determine which server should handle the request.

When to use it: Use IP Hash when your application needs to maintain user session data on the server side.

Configuration:

nginx
upstream my_app_servers {
    ip_hash;
    server server1.example.com;
    server server2.example.com;
    server server3.example.com;
}
  • Fun Fact: While ip_hash is a simple way to achieve session persistence, it's not always foolproof. If a user's IP address changes (e.g., they switch from Wi-Fi to cellular data), they might be directed to a different server.

3. Prioritizing Traffic: Assigning Server Weights and Backup Servers ⚖️

Not all servers are created equal. You might have one server that's a beast with lots of CPU and RAM, while others are more modest. In this case, you wouldn't want to send them the same amount of traffic.

Server Weights

This is where the weight parameter comes in handy. You can assign a weight to each server to influence how much traffic it receives. A server with a higher weight will get a proportionally larger share of the requests.

Example:

nginx
upstream my_app_servers {
    server powerful-server.example.com weight=3;
    server standard-server1.example.com; # Default weight is 1
    server standard-server2.example.com;
}

In this setup, for every 5 requests:

  • powerful-server.example.com will receive 3 requests.
  • standard-server1.example.com will receive 1 request.
  • standard-server2.example.com will receive 1 request.

When to use it: Use weights when you have servers with different capacities.

Backup Servers

What happens if all your primary servers go down? 😨 That's where backup servers come to the rescue. A server marked as backup will only receive traffic if all the non-backup servers in the group are unavailable.

Example:

nginx
upstream my_app_servers {
    server primary-server1.example.com;
    server primary-server2.example.com;
    server backup-server.example.com backup;
}

Here, backup-server.example.com is on standby, ready to jump in if primary-server1 and primary-server2 both fail.


4. Resilience: Handling Backend Server Failures and Basic Health Checks 🛡️

In a perfect world, servers would run forever without any issues. But in reality, they can fail. Nginx has mechanisms to detect these failures and stop sending traffic to unhealthy servers.

Nginx Open Source performs what are known as passive health checks. This means Nginx detects a failure when it tries to send a request to a server and the server doesn't respond correctly.

You can control this behavior with two important parameters on the server directive:

  • max_fails: The number of consecutive failed attempts that must occur within a specific time period for the server to be considered unhealthy. The default is 1.
  • fail_timeout: This sets the duration for max_fails to be counted and also the amount of time the server will be marked as down before Nginx tries sending requests to it again. The default is 10 seconds.

Example:

nginx
upstream my_app_servers {
    server server1.example.com max_fails=3 fail_timeout=30s;
    server server2.example.com max_fails=3 fail_timeout=30s;
}

In this configuration, if Nginx fails to connect to server1.example.com 3 times within a 30-second window, it will mark that server as down for the next 30 seconds. After that time, it will try again.

What counts as a failure? By default, Nginx considers connection errors and timeouts as failures. You can also configure it to treat certain HTTP status codes (like 500, 502, 503, 504) as failures using the proxy_next_upstream directive.

nginx
server {
    listen 80;
    location / {
        proxy_pass http://my_app_servers;
        proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
    }
}

This tells Nginx to try the next server in the upstream group if the current one returns an error, a timeout, or one of the specified 5xx error codes.

  • A note on Active Health Checks: Nginx Open Source's passive checks are great, but they're reactive. Nginx Plus, the commercial version, offers active health checks, where Nginx periodically sends special requests to your servers to check their health, independent of user traffic.

Extra Reading 📚

Challenge

You are tasked with configuring an Nginx instance to act as a highly available and performant load balancer for a critical e-commerce application.

Your configuration must be placed inside the provided http block and meet all of the following requirements:

  1. Define an upstream group named app_backend.
  2. Inside app_backend, add three primary application servers and one backup server:
    • app1.example.com:80
    • app2.example.com:80
    • app3.example.com:80
    • dr.example.com:80 (this is the backup server).
  3. Configure server weights within the app_backend group so that app1.example.com and app2.example.com each receive three times as much traffic as app3.example.com.
  4. Mark dr.example.com to only receive requests if all other primary servers in the app_backend group are unavailable.
  5. Implement passive health checks for the servers in the app_backend group. A server should be marked as down after 2 consecutive failures and remain marked down for 20 seconds before Nginx attempts to send traffic to it again.
  6. Define a second upstream group named checkout_api for handling payment processing. This group contains two servers:
    • checkout1.example.com:8080
    • checkout2.example.com:8080
  7. Configure the checkout_api group to use the IP Hash load balancing method to ensure session persistence.
  8. Create a server block that listens on port 80.
  9. Inside the server block, create a location for / that proxies requests to the app_backend upstream group.
  10. Configure this location block to try the next available upstream server if the currently selected one returns a 502 or 504 status code or if a connection timeout occurs.
  11. Inside the same server block, create another location for /api/v2/checkout that proxies requests to the checkout_api upstream group.

Expected result

Your Nginx configuration should correctly implement two distinct upstream groups with different load balancing strategies and health checks.

A correct solution will contain:

  • An upstream app_backend block.
    • It contains four server directives for app1, app2, app3, and dr.
    • app1.example.com and app2.example.com must have weight=3.
    • dr.example.com must have the backup parameter.
    • All primary servers in this block should have max_fails=2 and fail_timeout=20s.
  • An upstream checkout_api block.
    • It must contain the ip_hash; directive.
    • It contains two server directives for checkout1.example.com:8080 and checkout2.example.com:8080.
  • A server block listening on port 80 (listen 80;).
    • A location / block containing proxy_pass http://app_backend;.
    • The proxy_next_upstream directive must be present in the / location and configured for error timeout http_502 http_504.
    • A location /api/v2/checkout block containing proxy_pass http://checkout_api;.
nginx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.