Skip to content
Blog

NGINX limit_conn: Protect slow origin routes

Use NGINX limit_conn as a per-route concurrency cap for slow origin endpoints: what it counts, HTTP/2 and HTTP/3 behavior, dry-run rollout, and false-positive review.

Centinel Analytica
Published
NGINX limit_conn: Protect slow origin routes

NGINX limit_conn caps how many requests a single key, usually a client IP, can have in flight at once, which makes it the right tool for protecting slow or expensive origin routes from pile-ups. It limits concurrency. It does not rate-limit, and it does not tell you who or what is sending the requests.

That distinction decides how you deploy it. A report export that takes eight seconds to render can be tied up by one client opening thirty parallel requests, whether that client is a script, a misconfigured integration or a crawler. limit_conn puts a ceiling on that pile-up for one route at a time, so the origin keeps serving everyone else. This guide covers the config, what gets counted, a dry-run rollout and the false-positive review you should finish before you enforce anything.

What limit_conn does: a concurrency cap, not a rate limit

limit_conn counts requests currently being processed per key and rejects new ones once the count passes your number. When a request finishes, the slot frees up. Nothing else is measured: not requests per second, not bytes, not intent.

The module documentation describes it as limiting the number of connections per defined key, and notes that only connections with a request being processed by the server count, after the full request header has been read (nginx.org). An idle keepalive connection does not use a slot.

That makes it a good fit for routes where cost comes from duration: search endpoints, PDF or CSV generation, report builders, uncached upstream aggregation. A fast route that returns in 20 ms rarely accumulates concurrency, so a cap there does little. A route that holds an upstream worker for seconds is where a cap pays off.

Pick limit_conn when the failure you fear is too many simultaneous slow requests. Don't pick it to stop high-volume fast traffic. That needs a different control, covered below.

Configure limit_conn_zone and limit_conn for one slow route

Define a shared-memory zone once in the http block, then apply the limit inside the one location that needs it. Scope is the whole point: a global cap punishes your fast routes for the sins of your slow one.

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

    server {
        location /api/reports/export {
            limit_conn slow_export 4;
            limit_conn_status 429;
            proxy_pass http://app_origin;
        }
    }
}

The zone key is $binary_remote_addr, the compact binary form of the client address, which keeps per-key state small. The directive syntax is limit_conn zone number, and the response status when enforcement rejects a request defaults to 503; limit_conn_status changes it (nginx.org). We set 429 here because it tells a well-behaved client to back off, while 503 reads like an outage to monitors.

Choose the number from the route, not from a guess. Take the origin's real capacity for that endpoint, divide by the number of simultaneous clients you expect, and leave headroom for a browser that legitimately fires a few parallel calls. Measure your own p95 concurrency per client first, then set the cap above it.

Keep the zone name specific to the route (slow_export, not addr). When you add a second slow route later, a separate zone gives it its own counts and its own logs.

What gets counted: request headers, HTTP/2 and HTTP/3, shared IPs

Counting starts after NGINX has read the full request header and is processing the request. Slow header delivery and idle keepalive connections aren't counted by limit_conn, so it won't stop a slowloris-style header trickle. Handle that with header and body timeouts instead.

HTTP/2 and HTTP/3 change the arithmetic. With either protocol, each concurrent request counts separately, even when many requests share one transport connection. One browser tab that opens a single HTTP/2 connection and fires six parallel calls to your capped route consumes six slots, not one. If you size the cap thinking in TCP connections, you'll set it too low and reject real users.

The key matters just as much. Keyed on $binary_remote_addr, every client behind one address shares one budget: an office NAT, a university, a mobile carrier gateway, a corporate proxy. Fifty employees behind one egress IP can hit a cap of 4 together without any of them doing anything wrong.

If NGINX sits behind a CDN or load balancer, the address it sees may be the proxy's, not the visitor's. Configure the real_ip module with a trusted-proxy list so $remote_addr reflects the actual client, or every visitor collapses into one key and your cap throttles the whole site. Check this before anything else. It's the most common way a correct limit_conn config misfires.

Roll out safely with limit_conn_dry_run and $limit_conn_status

Run the limit in dry-run first, log the outcome, and enforce only after the logs say it is safe. limit_conn_dry_run on; disables enforcement but still accounts for over-limit requests, and $limit_conn_status records what would have happened: PASSED, REJECTED or REJECTED_DRY_RUN (nginx.org).

log_format conn_review '$remote_addr $request_time $status '
                       '$limit_conn_status "$request_uri" "$http_user_agent"';

location /api/reports/export {
    limit_conn slow_export 4;
    limit_conn_dry_run on;
    access_log /var/log/nginx/export_conn.log conn_review;
    proxy_pass http://app_origin;
}

Leave it in dry-run for at least one full business cycle, including your busiest day and any scheduled batch jobs. A week that skips month-end reporting will miss exactly the traffic most likely to trip the cap.

The rollout sequence:

  1. Ship dry-run with logging on one route.
  2. Count REJECTED_DRY_RUN lines per client and per hour.
  3. Review the clients behind them (next section).
  4. Raise the number or change the key if real users appear.
  5. Turn dry-run off for that route only.
  6. Keep the log format in place so REJECTED lines stay visible after enforcement.

Watch the origin too. If dry-run shows few would-be rejections but the origin still saturates, the cap is too high or the problem is spread across many addresses, which a per-IP cap can't fix.

Review false positives before you enforce

Every REJECTED_DRY_RUN line is a request that enforcement would have refused, so read them as a list of people you were about to break. Group them by client address and user agent, then ask who each one is.

The usual legitimate sources:

  • Shared egress addresses. Offices, schools and carrier NAT. Many users, one key. Raise the cap or key on something finer than IP, such as a session or API key header, where one exists.
  • HTTP/2 and HTTP/3 browsers. A single page that fans out several parallel calls to the capped route. Count your own front end's maximum parallelism and set the cap above it.
  • Your own tooling. Monitoring probes, internal batch jobs, partner integrations. Exempt them with a separate location, a different zone or a geo/map key that gives trusted sources an empty key (requests with an empty key are not counted).
  • Legitimate crawlers. A search or approved crawler that fetches several slow pages at once. A concurrency cap can slow it down, and you should decide on purpose whether that is acceptable.

That last point deserves a rule: don't enforce a cap on a route that a crawler you want must reach until you've seen what that crawler's concurrency looks like in your logs. The logs show request volume and user agent strings. A user agent string is a claim, not proof, so don't allowlist on it alone.

If the review turns up nothing but a few clear outliers with hundreds of concurrent requests, enforce. If it turns up a mix of real users and abusers on the same key, the cap is the wrong shape for that route, and you need a better key or a different control.

limit_conn vs limit_req: when to use each, and where both stop

limit_conn bounds simultaneous requests. limit_req bounds the rate at which requests arrive. They fail in different places, so they complement each other rather than replace each other.

limit_req uses a leaky-bucket model with a configured rate such as rate=1r/s, optional burst, and nodelay or delay behavior. It also has its own dry-run and a $limit_req_status variable (nginx.org).

SituationBetter fit
Slow route, many parallel requests pile uplimit_conn
Fast route, a flood of sequential requestslimit_req
Login or password-reset endpointslimit_req
Expensive export or report generationlimit_conn, often with limit_req too
Slow header or body trickleTimeouts, not either module

A client sending one request every two seconds to an eight-second route never trips a rate limit but stacks four requests deep. A client sending a thousand 10 ms requests in a second may never exceed a concurrency cap but still burns CPU. Use both on a route that is both slow and public.

Both modules stop at the same place. Each keys on a value you choose, usually an address, and neither knows what the client is. If your problem is traffic spread across thousands of rotating addresses, per-key limits see thousands of small, innocent-looking clients. For rate-limit patterns on proxies in general, see our guide to HAProxy stick tables and rate limits, which covers the same ideas on a different proxy.

Where limit_conn ends and bot identification begins

limit_conn caps concurrency. It does not identify bots, and it shouldn't be described as bot protection. It can't tell a scraper from a customer, a real crawler from one faking a crawler's name, or a headless browser from a person. It sees an address, a count and a number, and it acts on those alone.

That's a strength when the goal is origin protection: the cap is predictable, cheap and easy to reason about. It's a weakness when the goal is deciding who deserves access. A scraper that spreads requests across many addresses stays under every per-IP cap. A cap tuned tightly enough to slow that scraper will also slow a real office full of users behind one NAT.

The question after the cap is different: of the requests that get through, which come from real visitors and which from scrapers that look like them? That is the problem Centinel Analytica works on. Centinel tells real visitors from scrapers and applies allow, challenge or block policy through your existing CDN or edge, so your CDN and your WAF stay where they are. Its published research found that 84% of requests claiming to be GPTBot on a typical news site were fake, a gap that a user agent string or an IP cap can't close on its own.

A sensible split: keep limit_conn on the slow routes as the concurrency backstop, and use identification to decide policy per visitor type. For the CDN side of that decision, see how Fastly bot protection splits pre-cache and post-cache checks.

Cap the slow route today, then audit who is hitting it

Put limit_conn on your single slowest route in dry-run this week, log $limit_conn_status, and enforce only after you've read the REJECTED_DRY_RUN lines and found no real users in them. Then ask the question the cap can't answer: who is sending the traffic that stays under your limits?

Frequently asked questions

What does NGINX limit_conn actually limit?

It limits the number of requests being processed at the same moment for a given key, usually the client IP. It is a concurrency cap, not a rate limit. Counting begins after NGINX reads the full request header, and idle keepalive connections are not counted. It does not identify who or what is sending requests.

Does limit_conn count HTTP/2 and HTTP/3 requests separately?

Yes. With HTTP/2 or HTTP/3, each concurrent request counts separately, even when several requests share one transport connection. A browser sending six parallel calls over one connection uses six slots. Size your cap by concurrent requests per client, not by TCP connections, or you will reject legitimate users.

How do I test limit_conn without blocking real users?

Set `limit_conn_dry_run on;` so NGINX accounts for over-limit requests without rejecting them, and log `$limit_conn_status`, which reports PASSED, REJECTED or REJECTED_DRY_RUN. Review the REJECTED_DRY_RUN entries by client and user agent across a full business cycle before you turn enforcement on.

Can limit_conn stop scrapers and bots?

Not by itself. limit_conn caps concurrency per key and cannot tell a scraper from a customer or a real crawler from a fake one. Scrapers that spread requests across many addresses stay under per-IP caps. Centinel Analytica tells real visitors from scrapers and applies policy through your existing CDN or edge.