FALVARIX
FALVARIX
devops --real --no-hype

Nginx as a Load Balancer: Caching and Rate Limiting

Nginx as a Load Balancer: Caching and Rate Limiting

Nginx as a Load Balancer: Caching and Rate Limiting

Almost every production outage I’ve seen during traffic spikes has the same root cause: the backend was getting more requests than it could handle, and nothing in front of it was deciding which ones to let through. A well-configured Nginx load balancer changes that picture. It spreads the traffic, serves cached responses for anything that doesn’t need to hit the app, and holds off abusive clients before they eat up your resources.

This guide walks through the three pieces with the biggest impact: upstream load balancing, response caching and rate limiting, plus a basic layer of DDoS protection. Everything comes with config you can adapt today.

Load Balancing with Upstreams: The Foundation of Performance

The upstream block defines the group of application servers. The bare-minimum config works, but the one that survives production includes a few details almost everyone forgets.

upstream app_backend {
    least_conn;
    server 10.0.1.11:8080 max_fails=3 fail_timeout=15s;
    server 10.0.1.12:8080 max_fails=3 fail_timeout=15s;
    server 10.0.1.13:8080 backup;
    keepalive 64;
}

Choosing the Right Algorithm

  • Round robin (default): even distribution. Works when requests are uniform.
  • least_conn: sends the request to the server with the fewest active connections. This is my default when requests vary in duration.
  • ip_hash: keeps the same client on the same server. Handy if you store sessions in memory, though externalizing them is better.
  • hash $request_uri consistent: ideal for balancing cache servers, since the same URL always lands on the same node.

Keepalive to the Backend

The keepalive directive reuses TCP connections with the application servers and avoids a handshake on every request. For it to work you must force HTTP/1.1 and clear the Connection header in the location:

location / {
    proxy_pass http://app_backend;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_next_upstream error timeout http_502 http_503;
    proxy_next_upstream_tries 2;
}

With proxy_next_upstream, if a node fails, Nginx retries on another one without the user noticing a thing. Cap the retries with proxy_next_upstream_tries so you don’t multiply the load when the whole cluster is degraded.

Passive and Active Health Checks

The open source version of Nginx does passive checks: max_fails and fail_timeout mark a server as unavailable after real errors. Active health checks are in NGINX Plus, the commercial product from F5. If you’re not using it, lean on external monitoring and a /healthz endpoint your orchestrator can poll.

If you’d rather use a proxy with dynamic service discovery in containers, compare this approach with Traefik in Docker with automatic SSL. Nginx wins on fine-grained control and raw performance; Traefik wins on convenience.

Nginx Caching: The Fastest Request Is the One That Never Reaches the Backend

A well-designed cache slashes backend load for content that repeats: catalogs, read APIs, public pages. First define the zone in the http context:

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app_cache:100m
                 max_size=10g inactive=60m use_temp_path=off;

Then enable it in the matching location:

location /api/public/ {
    proxy_pass http://app_backend;
    proxy_cache app_cache;
    proxy_cache_key "$scheme$request_method$host$request_uri";
    proxy_cache_valid 200 301 10m;
    proxy_cache_valid 404 1m;
    proxy_cache_lock on;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503;
    proxy_cache_background_update on;
    add_header X-Cache-Status $upstream_cache_status;
}

The Directives That Make the Difference

  • proxy_cache_lock: if a hundred clients request an uncached resource at once, only one request goes to the backend. It prevents the classic cache stampede.
  • proxy_cache_use_stale: serves stale content if the backend fails. It’s a safety net that turns an outage into an invisible degradation.
  • proxy_cache_background_update: refreshes the cache in the background while the user gets the existing version.
  • X-Cache-Status: an essential debugging header. You’ll see HIT, MISS, STALE or BYPASS and know whether your cache is doing its job.

Microcaching for Dynamic Content

Even “dynamic” pages can tolerate a second of age. Caching responses with proxy_cache_valid 200 1s absorbs enormous spikes: if you get 2,000 requests per second to the same URL, the backend only handles one. It’s one of the optimizations with the best effort-to-result ratio.

What Never to Cache

Exclude authenticated or stateful requests. Use proxy_cache_bypass and proxy_no_cache with variables based on cookies or Authorization headers:

map $http_authorization$cookie_session $skip_cache {
    default 1;
    ""      0;
}
proxy_cache_bypass $skip_cache;
proxy_no_cache $skip_cache;

A mistake here isn’t a performance issue, it’s data leaking between users. Always review this part before going to production.

Rate Limiting: Deciding Who Gets to Consume Your Resources

The limit_req module implements the leaky bucket algorithm. It defines how many requests per second each client is allowed and how many it can accumulate in a burst.

limit_req_zone $binary_remote_addr zone=general:20m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
limit_req_status 429;

server {
    location / {
        limit_req zone=general burst=20 nodelay;
        proxy_pass http://app_backend;
    }
    location /login {
        limit_req zone=login burst=5;
        proxy_pass http://app_backend;
    }
}

Burst and nodelay, Properly Understood

Without burst, any request that exceeds the rate is rejected instantly, and a browser loading a page with ten resources would get errors. With burst=20, Nginx allows up to 20 extra requests. With nodelay it processes them immediately instead of spacing them out, consuming the burst slots. For a login you should not use nodelay: you want to slow things down, not just count.

Limiting Concurrent Connections

limit_conn complements the above against clients that keep many connections open:

limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn perip 30;

The Real IP Problem

If Nginx sits behind another proxy or CDN, $binary_remote_addr will be that intermediary’s IP and you’ll limit all users as if they were one. Fix it with the realip module:

set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;
real_ip_recursive on;

Only declare trusted ranges. Accepting X-Forwarded-For from anyone lets an attacker spoof their IP and dodge your limits.

Basic DDoS Protection with Nginx

Let’s be clear: Nginx won’t stop a volumetric attack of hundreds of gigabits. That takes edge filtering or a specialized provider. What it does very well is withstand low- and medium-intensity layer 7 attacks, plus bots that drain resources without needing to be massive.

Timeouts and Buffers That Slow Clients Can’t Beat

Slowloris-style attacks keep connections open by sending data a trickle at a time. Tighten the wait times:

client_body_timeout 10s;
client_header_timeout 10s;
send_timeout 10s;
keepalive_timeout 30s;
client_max_body_size 5m;
client_body_buffer_size 16k;
large_client_header_buffers 4 8k;

Adapt client_max_body_size to each location: a file upload endpoint needs more, the rest doesn’t.

Worker Capacity

Make sure worker_processes auto; is active and that worker_connections (say 4096) and worker_rlimit_nofile are consistent with the system’s file descriptor limit. An Nginx that runs out of descriptors rejects legitimate traffic even with the CPU idle.

Selective Blocking

You can cut off obvious patterns with map and deny, for instance empty user agents or common scan paths:

map $http_user_agent $bad_agent {
    default 0;
    ""      1;
    ~*(sqlmap|nikto|masscan) 1;
}
if ($bad_agent) { return 444; }

Code 444 closes the connection without responding, which saves bandwidth. Only use if with return, which is its safe use inside Nginx.

Defense in Depth with the OS

Nginx logs feed other tools. With Fail2ban configured in depth you can ban at the firewall level the IPs that rack up 429 or 403 responses, so they never even reach a worker. If you manage a fleet, automate these tweaks along with the rest of your hardening; the article on hardening 50 servers with Ansible shows how to do it reproducibly.

Observability: What You Don’t Measure, You Can’t Tune

Customize the log format to record what matters on a load balancer:

log_format lb '$remote_addr [$time_local] "$request" $status '
              'rt=$request_time urt=$upstream_response_time '
              'uaddr=$upstream_addr cache=$upstream_cache_status';
access_log /var/log/nginx/lb.log lb;

With urt and uaddr you spot which backend is slow; with cache you calculate your hit rate; with the 429s you see how many clients hit the limit. Also enable stub_status on an internal route to export active connections to Prometheus.

Safely Deploying the Configuration

A config this size deserves a serious workflow. Always validate with nginx -t before reloading, and use nginx -s reload, which doesn’t drop in-flight connections. Version the files in Git and run validation in the pipeline; in CI/CD with GitHub Actions a single job that spins up a container and runs nginx -t against the changes is enough. The official Nginx documentation details every directive and its defaults, and it’s worth keeping close when tuning parameters.

Conclusion: Three Layers, One Goal

A high-performance load balancer isn’t just about distributing requests. It’s a chain of decisions: the upstream distributes and tolerates failures, caching avoids unnecessary work, and rate limiting keeps a handful of clients from degrading the service for everyone. Add strict timeouts, real IP properly resolved and useful logs, and you’ll have a solid foundation against legitimate spikes and basic abuse.

Start with what pays off most: enable least_conn with keepalive, apply microcaching to a public route and protect the login with a strict limit. Measure, tune the values with real data and repeat.

Keep Reading