Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Limit Connections in nginx: Rate Limiting Guide

· 6 min read · Home Tech

In this article
  1. Why Limit Connections at All?
  2. How Connection Limiting Works in nginx
  3. Setting Up the Directives Correctly
  4. Choosing the Right Limit and Key
  5. Common Pitfalls and Misconceptions
  6. Connection Limiting vs. Rate Limiting
  7. Testing and Monitoring Your Limits
  8. Frequently Asked Questions

Yes, you can limit connections in nginx using the limit_conn_zone and limit_conn directives, which restrict the number of simultaneous connections per client IP (or another key). This is separate from request rate limiting (limit_req), which controls how many requests a client can make per second; connection limiting caps concurrent open connections.

Why Limit Connections at All?

Unlimited connections can exhaust server resources. Each open connection consumes memory (for buffers, headers, and socket descriptors) and CPU time. A single client—or a small group of clients—can open hundreds or thousands of connections, slowing down or crashing the server for everyone else. Common scenarios include:

  • Slow clients that hold connections open while downloading large files.
  • Web crawlers or scrapers that open many parallel connections.
  • Application bugs that leak connections without closing them.
  • Distributed denial-of-service (DDoS) attacks that aim to exhaust connection slots.

Limiting connections is a basic protective measure. It does not stop sophisticated attacks, but it prevents the simplest resource-exhaustion problems and keeps your server responsive under normal traffic spikes.

How Connection Limiting Works in nginx

nginx tracks connections using a shared memory zone. You define a zone with limit_conn_zone (in the http context) and then apply limit_conn in a server, location, or http context. The zone stores a counter for each key—usually the client IP address—and nginx checks the counter before accepting a new connection.

Here is a minimal configuration:

http {
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    server {
        location /downloads/ {
            limit_conn addr 5;
        }
    }
}

This allows at most 5 simultaneous connections from a single IP address to /downloads/. If a client exceeds that, nginx returns 503 Service Unavailable (by default) for new connection attempts.

Key points:

  • $binary_remote_addr is the client IP in binary form—it uses less memory than the string form $remote_addr.
  • The zone size (10m) allocates 10 megabytes of shared memory. This can hold roughly 160,000 IP addresses (each entry uses about 64 bytes).
  • The limit applies to connections, not requests. A single connection can send many requests (keep-alive).
  • If you use a reverse proxy, the client IP may be the proxy's IP unless you set real_ip_header or use the X-Forwarded-For header.

Setting Up the Directives Correctly

There are three main directives:

  • limit_conn_zone – defines the shared memory zone and the key. Must be in http context.
  • limit_conn – sets the maximum number of connections for the zone. Can be in http, server, or location.
  • limit_conn_status – sets the HTTP status code returned when the limit is exceeded (default is 503).
  • limit_conn_log_level – sets the log level for rejected connections (default is error).

Example with status and logging:

http {
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
    limit_conn_status 429;
    limit_conn_log_level warn;

    server {
        limit_conn conn_limit 10;
    }
}

Here, exceeding the limit returns HTTP 429 (Too Many Requests) and logs a warning. Using 429 is more semantically correct than 503 because the client is doing something wrong, not the server.

Choosing the Right Limit and Key

The key determines who gets grouped together. Common choices:

  • $binary_remote_addr – per IP address. Simple, but multiple users behind a NAT (e.g., a corporate network) share one IP and may be blocked unfairly.
  • $server_name – per virtual host. Useful when you host multiple sites on one server.
  • $http_x_forwarded_for – per original client IP if you trust the header (set by your proxy). Use with caution because clients can spoof it.
  • $request_uri – per URI. This limits connections to a specific resource, but is rarely used because it can be abused.

Choosing the limit number depends on your application:

  • For a normal website, 5–10 connections per IP is usually enough. Browsers open 6–8 connections per domain.
  • For API endpoints, 1–2 connections per IP might be appropriate if clients should reuse connections.
  • For file downloads, you might allow more (10–20) because downloads are long-lived.

Start with a generous limit, monitor logs, then tighten it. If you see legitimate users getting 503s, raise the limit or change the key.

Common Pitfalls and Misconceptions

Several things trip up administrators:

  • It does not limit requests per second. A client can send hundreds of requests over one connection. Use limit_req for that.
  • It counts all connections, including keep-alive idle ones. If a client keeps a connection open, it counts toward the limit even if it is not sending requests.
  • Behind a proxy, all clients appear as one IP. If you use nginx as a reverse proxy, the upstream server sees the proxy's IP. You must pass the real IP via headers and configure nginx to use it.
  • The zone size is not a limit on connections. It is the memory for tracking keys. If the zone fills up, nginx stops tracking new keys and may allow unlimited connections from new IPs (or log errors).
  • Limits apply per worker process? No, the zone is shared across all workers, so the limit is global.

Connection Limiting vs. Rate Limiting

These two features are often confused:

  • limit_conn – caps concurrent connections. Example: “No more than 5 open connections from one IP.”
  • limit_req – caps request rate. Example: “No more than 10 requests per second from one IP.”

They complement each other. Use both for robust protection. For example, allow 10 connections but only 5 requests per second. A client can open 10 connections but still be limited by the request rate.

Configuration for rate limiting:

http {
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=5r/s;

    server {
        limit_req zone=req_limit burst=10;
    }
}

This allows an average of 5 requests per second, with bursts up to 10. Excess requests are delayed (or rejected with 503 if nodelay is not used).

Testing and Monitoring Your Limits

After configuring, test with a tool like curl or ab (ApacheBench). For example, to open multiple connections:

for i in $(seq 1 10); do curl -s -o /dev/null http://example.com/downloads/file.zip & done; wait

Check nginx logs for limiting connections messages. By default, they appear at error level. You can also enable the stub_status module to see active connections:

location /nginx_status {
    stub_status;
}

This shows Active connections, which includes all connections, not just limited ones. To see rejected connections, watch the error log.

Frequently Asked Questions

What is the default limit if I don't configure anything?

There is no default limit. nginx allows unlimited connections unless you explicitly define a limit_conn_zone and limit_conn.

Can I set a different limit for different locations?

Yes. You can define multiple zones with different keys or limits, and apply limit_conn in each location block. For example, allow 10 connections for /api/ but only 3 for /downloads/.

Why do I get 503 even when I have few connections?

Check if you have multiple limit_conn directives that apply to the same request. The most restrictive one wins. Also, if you are behind a proxy, all clients share the proxy IP, so the limit is hit quickly. Use the real IP header or increase the limit.

Does limiting connections affect WebSocket connections?

Yes, WebSocket connections are counted like any other. If you have a WebSocket service, set a higher limit, because each client keeps a connection open for a long time.

Can I whitelist certain IPs?

Yes. Use the geo module to define a variable that is empty for allowed IPs and the client IP otherwise. Then use that variable as the key in limit_conn_zone. For example:

geo $limit_key {
    default $binary_remote_addr;
    192.168.1.1 "";
}
limit_conn_zone $limit_key zone=addr:10m;

This way, the whitelisted IP has an empty key, so it is not counted.

What happens when the zone memory is full?

nginx logs an error and stops tracking new keys. This means new IPs are not limited until memory frees up. Increase the zone size if you see such errors.