FAHADBIN SHAKIR

Loading essential experience000%

Application Security

Rate Limiting Safely Behind CDNs and Reverse Proxies

A security-first guide to trusted proxy hops, client identity, route-specific limits, distributed counters, failure behavior, and false-positive testing.

Author: Fahad Bin Shakir · Published: · Updated: · 6 min read

Layered reverse proxies enforcing controlled request flow toward an application

Introduction

Rate limiting depends on identity. Behind a CDN, load balancer, Apache, or Passenger, the socket peer is usually a proxy rather than the visitor. Trust every forwarded header and an attacker can choose a different address for each request; trust none and every visitor shares the proxy address, causing one busy client to block the site. The hard part is not the counter algorithm. It is proving which hop is allowed to describe the previous hop.

A safe design models the exact network path, configures trust as narrowly as the framework permits, and limits actions according to their abuse cost. Login, contact, search, password reset, and public assets do not deserve one universal threshold. The result must also work across multiple application processes, handle IPv6 correctly, explain rejections without leaking internals, and preserve an operational path during cache or counter-store failure.

Draw every trusted hop before reading client IP

Document the public CDN, hosting proxy, local web server, process manager, and application in order. For each connection, record the source network and which header is added, replaced, or preserved. Test requests that enter through every reachable path. If an origin is directly public, clients may bypass the CDN and send the same forwarded header themselves unless the firewall or application rejects that route.

In Express, the trust proxy setting controls how request IP, protocol, and hostname are derived. A blanket true value is safe only when the last trusted proxy always removes untrusted forwarded values and no shorter path reaches the application. Prefer exact proxy addresses, CIDR ranges, or a reviewed hop function. Reassess the rule whenever hosting or CDN topology changes.

Verify the address chain with adversarial requests

From the public edge, send a request with a forged X-Forwarded-For value and confirm the application still derives the real client according to the trusted chain. Then test the origin path, IPv4, IPv6, multiple forwarded entries, missing headers, and the provider's canonical client-address header. Log only sanitized derived addresses and a correlation identifier during the test window.

Do not parse comma-separated headers with an ad hoc first-or-last rule. Established proxy-address libraries account for hop traversal and IP ranges, but they still depend on correct trust configuration and patched versions. Normalize IPv4-mapped IPv6 forms and choose an IPv6 subnet policy intentionally; treating every temporary IPv6 address as a new person can make a limit ineffective.

Choose limits by operation and consequence

Protect expensive or sensitive routes more closely than cached public pages. Login may combine per-account and per-network controls; password reset needs anti-enumeration behavior; contact forms need per-client, payload validation, and server-wide abuse ceilings; search may use a cost-based budget. Keep accessibility and shared networks in mind so a school or office is not punished for ordinary use.

Use more than IP where appropriate, but avoid identifiers that can be freely rotated or that expose private data in keys. Account IDs should be hashed or namespaced and applied only after safe normalization. A global emergency ceiling can protect infrastructure while route-level policies preserve usefulness. Document the intended burst, sustained rate, window, and recovery behavior for each limiter.

Use atomic distributed counters

An in-memory counter is process-local and resets on restart, so several Node workers each allow the full threshold. Use a shared store with an atomic increment-and-expire operation or a proven limiter that implements token bucket, leaky bucket, or sliding windows correctly. Include policy version and route class in keys so a configuration change does not collide with old counters.

Set counter retention to the shortest period needed by the algorithm, cap key cardinality, and monitor memory plus latency. Never store complete request bodies or credentials in limiter keys. The counter store belongs on a private network with authentication and bounded timeouts. If it slows, synchronous checks must not consume the entire request budget.

Define failure and response behavior

Decide per route whether counter-store failure should fail open, fail closed, or use a small local fallback. A public article can usually remain available, while a highly sensitive administrative action may need to stop. The choice must consider dependency outages and denial-of-service amplification. Use short timeouts and a circuit breaker so every request does not wait for an unhealthy store.

Return HTTP 429 for an enforced limit, a consistent machine-readable error for APIs, and a Retry-After value when the reset time is meaningful. Do not reveal account existence, internal thresholds for sensitive controls, or proxy topology. Rate limiting is not authentication or input validation; requests that pass the budget still require authorization, CSRF protection, size limits, and safe parsing.

Observe false positives and layered defenses

Track allowed and blocked counts by policy, route, status, derived network class, and store health without collecting unnecessary personal data. Alert on sudden block-rate changes, counter-store errors, and one route consuming a large share of keys. Sample legitimate support reports and synthetic tests from shared networks. A limit that silently blocks real contact or login traffic is a production defect.

Coordinate application controls with CDN or web-application-firewall rules. Edge limits can absorb obvious floods before origin cost, while the application knows accounts and operation semantics. Keep policies consistent enough to debug but do not duplicate identical counters blindly. After deployment, test bypass attempts, direct origin access, multi-process behavior, IPv6, reset timing, and accessible error presentation.

Model evasion and collateral damage before release

Write abuse cases for distributed low-rate traffic, rotating IPv6 addresses, credential stuffing across many accounts, one account from many networks, and a botnet that stays below each local window. Then write legitimate cases: a university NAT, corporate VPN, mobile carrier, accessibility tool, monitoring service, and a user who mistypes a password several times. No single key handles all cases. Layer account, network, device-neutral behavioral, and server-wide budgets only where the data and privacy policy support them.

Simulate these patterns against a non-production environment with production-equivalent proxy headers and a shared counter store. Measure allowed work, blocked work, memory growth, reset accuracy, and application latency. Confirm support can identify the policy without disclosing sensitive security logic and can remove a false block through an audited path. Revisit the threat model after route, proxy, authentication, or traffic changes; a safe threshold and trust chain are properties of the current system, not constants copied between projects.

Deployment checklist

  • Map every CDN, load balancer, web server, and application hop.
  • Restrict Express trust proxy to reviewed addresses, networks, or hop logic.
  • Test forged forwarded headers, direct origin access, IPv4, and IPv6.
  • Set route-specific burst and sustained budgets based on abuse cost.
  • Use atomic shared counters with bounded retention, cardinality, and latency.
  • Define fail-open, fail-closed, and local-fallback behavior per route.
  • Return safe 429 responses and preserve validation plus authorization controls.
  • Monitor false positives, edge interaction, store health, and bypass attempts.

Related portfolio and context

Primary references

Related Engineering Notes

View all Engineering Notes