How do you configure NGINX rate limiting and connection limiting to protect against DDoS and abuse?
Quick Answer
Use limit_req_zone for request rate limiting (leaky bucket algorithm) and limit_conn_zone for concurrent connection limiting. Configure burst and nodelay for handling traffic spikes without dropping legitimate requests.
Detailed Answer
Rate Limiting (limit_req)
Uses the leaky bucket algorithm. Requests arrive at variable rate but are processed at a fixed rate. Excess requests queue up (burst) or are rejected (503).
Connection Limiting (limit_conn)
Limits the number of simultaneous connections from a single IP or per server.
Key Parameters
- rate: Requests per second (e.g., 10r/s) - burst: Size of the overflow queue - nodelay: Process burst requests immediately rather than queuing - delay: Process first N burst requests immediately, queue the rest
Best Practices
- Apply different limits to different endpoints (strict for login, relaxed for static) - Use $binary_remote_addr (16 bytes) instead of $remote_addr (7-15 bytes) for memory efficiency - Return 429 (Too Many Requests) instead of default 503 - Log rate-limited requests for analysis - Consider using geo module to whitelist internal IPs
Code Example
# Rate limiting zones (defined in http block)
http {
# 10 requests/second per IP, 10MB shared memory
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
# Strict limit for auth endpoints
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
# Connection limit
limit_conn_zone $binary_remote_addr zone=addr:10m;
# Return 429 instead of 503
limit_req_status 429;
limit_conn_status 429;
server {
# General API: 10 req/s with burst of 20
location /api/ {
limit_req zone=api burst=20 delay=10;
# First 10 burst requests processed immediately,
# next 10 queued, beyond 30 total → 429
limit_conn addr 50; # Max 50 concurrent connections per IP
proxy_pass http://backend;
}
# Login: strict 1 req/s
location /api/auth/login {
limit_req zone=login burst=5 nodelay;
proxy_pass http://backend;
}
# Whitelist internal IPs
geo $limit {
default 1;
10.0.0.0/8 0; # Internal network
172.16.0.0/12 0; # Internal network
}
map $limit $limit_key {
0 "";
1 $binary_remote_addr;
}
limit_req_zone $limit_key zone=external:10m rate=5r/s;
}
}Interview Tip
Explain the leaky bucket algorithm and the difference between burst, nodelay, and delay. The whitelist pattern using geo + map is an advanced technique that impresses interviewers.