14 min readSecurity fundamentals

Rate Limiting and Brute-Force Defense: Blocking Attackers, Not Users

Build multi-dimensional rate limiting with GCRA token buckets, trusted proxy parsing, and HTTP 429 cooldowns to block brute force without self-DoS.

Technical illustration: Designing Rate Limiting and Brute-Force Defense Without Locking Out Real Users

At 2

AM, an on-call alert wakes the engineering team. Hours earlier, someone deployed a strict five-attempt login limit to stop automated password guessing, and now nobody on the corporate VPN can sign in, including the engineers trying to roll back the change. One colleague mistyped a password five times, and the rate limiter treated the entire office gateway as a hostile botnet.

Authentication rate limiting behaves like a nightclub bouncer checking identification at the door. If twenty strangers step off the same city bus and one passenger starts shouting, a lazy bouncer bans the entire bus route for the night. Production internet traffic works much like that bus: dozens, hundreds, or even thousands of unrelated users routinely share a single public IP address behind mobile Carrier-Grade NAT (CGNAT), university outbound proxies, coffee-shop routers, and corporate VPN exit nodes.

When brute-force protection is built around a single counter or a permanent account lockout, it trades away system availability for the illusion of security. Separating an automated credential attack from a human having a bad morning requires understanding the economics of password verification, the geometry of network and identity signals, and the exact mechanics of state storage and trust boundaries.

The Cost Asymmetry Behind Password Guessing

Authentication defenses exist because login endpoints have an asymmetric resource profile. An attacker using a lightweight HTTP client can dispatch thousands of guessed passwords per second at negligible compute cost, whereas the server must parse TLS, query a user store, and run a deliberately slow, memory-hard password verification function such as Argon2id or bcrypt.

Modern password hashing functions are intentionally tuned to consume tens of milliseconds of CPU time and tens of megabytes of RAM per check so that offline hash cracking remains expensive. On a live web server, that defensive property cuts both ways: if an attacker can force your authentication workers to compute 2,000 Argon2id hashes per second, they can exhaust your CPU pool long before they ever guess a valid password. Rate limiting restores economic balance by capping both credential guessing throughput and unauthenticated compute consumption.

However, relying on a single rate-limit counter introduces two predictable failure modes:

  • Shared-infrastructure false positives: Counting failures purely by client IP address collapses everyone behind a CGNAT gateway or corporate VPN into one bucket, creating a large blast radius from a single user's typos.
  • Distributed false negatives: Counting only per IP misses credential stuffing attacks spread across thousands of residential proxy IPs, while counting only per account misses wide password spraying where an attacker tries one common password across ten thousand accounts.

Why Single-Counter Rate Limiters Fail Against Real Traffic

Single-key rate limiters fail because they collapse independent threat dimensions into one shared jar. Resilient authentication pipelines partition failure tracking across orthogonal bucket keys so each signal isolates a specific attack pattern without punishing unrelated neighbors.

Instead of one global counter, you evaluate a set of independent buckets scoped to different intersections of network origin and identity:

# Partitioned failure buckets isolate noisy neighbors and catch distributed attacks
bucket:ip_user:<client_prefix>:<canonical_user>   # Tight limit (e.g., 5 failures / 15m)
bucket:user:<canonical_user>                      # Medium limit (catches distributed stuffing)
bucket:subnet:<cidr_prefix>                       # Broad limit (catches wide password spraying)
bucket:preauth_ip:<client_prefix>                 # Generous HTTP flood ceiling before hashing

Notice how the tightest threshold applies strictly to the intersection of a network origin and a specific target account (ip_user). If Alice mistypes her password five times from the corporate VPN, only attempts for Alice from that gateway hit friction, while Bob at the next desk logs in uninterrupted. Meanwhile, the broader user bucket catches a botnet rotating across 5,000 residential IPs to hammer Alice's account, and the subnet bucket catches an attacker testing "Summer2026!" once per account across an entire directory from a single cloud block.

Identifier Canonicalization and IPv6 Subnet Traps

Partitioning by identity and network fails immediately if an attacker can mutate the bucket key without changing the underlying target. Consider an email-based login where the backend treats [email protected] and [email protected] as the same user, or strips sub-addressing tags ([email protected]). If your rate limiter hashes the raw input string before normalization, an attacker gets unlimited attempts simply by alternating capitalization (Alice, aLice, alIce) or incrementing +probe suffixes.

Network keys carry a similar trap on IPv6. Residential ISPs routinely assign each subscriber an entire /64 or /56 IPv6 prefix containing $2^{64}$ addresses. An attacker running a script locally can bind a new random /128 source address for every TCP connection within that /64 allocation. Keying buckets on exact /128 IPv6 addresses lets an attacker evade per-IP limits on a single laptop; aggregating IPv6 addresses to /64 for ip_user and /48 for subnet spray detection closes that gap while preserving isolation for IPv4 /32 and /24 ranges.

import crypto from "node:crypto";
import net from "node:net";
 
export function canonicalizeIdentifier(raw: string): string {
  const normalized = raw.normalize("NFKC").trim().toLowerCase();
  const atIndex = normalized.lastIndexOf("@");
  if (atIndex === -1) return normalized;
 
  const local = normalized.slice(0, atIndex);
  const domain = normalized.slice(atIndex + 1);
  // Strip plus-tags if your identity store treats sub-addresses as aliases
  const canonicalLocal = local.split("+")[0];
  return `${canonicalLocal}@${domain}`;
}
 
export function extractNetworkPrefix(ip: string, mode: "host" | "spray"): string {
  if (net.isIPv4(ip)) {
    const octets = ip.split(".");
    return mode === "host" ? `${ip}/32` : `${octets[0]}.${octets[1]}.${octets[2]}.0/24`;
  }
  if (net.isIPv6(ip)) {
    const groups = expandIPv6(ip); // Expands :: into 8 zero-padded 16-bit hex groups
    const keepGroups = mode === "host" ? 4 : 3; // /64 for host bucket, /48 for spray bucket
    return `${groups.slice(0, keepGroups).join(":")}::/${keepGroups * 16}`;
  }
  return "invalid-ip";
}
 
export function hashKeyPart(value: string, hmacSecret: string): string {
  // Keyed HMAC avoids storing raw PII usernames inside Redis keyspace
  return crypto.createHmac("sha256", hmacSecret).update(value).digest("hex").slice(0, 32);
}

Hashing the canonicalized identifier with a server-side HMAC secret before constructing Redis keys also solves a subtle privacy problem. Operations dashboards and Redis MONITOR logs frequently inspect key names; storing raw email addresses in cache keys unnecessarily spreads personally identifiable information across monitoring pipelines.

Where Does the Client IP Come From? Securing the Proxy Trust Boundary

A rate limiter is only as trustworthy as the edge boundary that extracts the client IP address. If application code reads X-Forwarded-For blindly, any caller can forge a fresh IP header on every HTTP request and bypass every network bucket.

Most production web applications sit behind load balancers, CDNs, or reverse proxies such as Envoy or Nginx, which means the application's direct TCP socket peer (remoteAddr) is the proxy rather than the end user. Forwarded headers exist to pass the original peer address downstream, yet header parsing is one of the most frequent bypass vulnerabilities in authentication systems.

When an attacker connects to your edge proxy and sends a forged X-Forwarded-For: 198.51.100.77 header, a standard reverse proxy appends the real TCP peer IP to the end of the comma-separated list, producing 198.51.100.77, 203.0.113.14. Applications that naively split on commas and take index 0 (left-to-right parsing) read the attacker's spoofed string 198.51.100.77. Every request carries a different random IP, creating millions of single-count buckets in Redis while the attacker guesses passwords at full speed.

// VULNERABLE: Leftmost element is attacker-controlled unless the edge stripped it
function getClientIpVulnerable(forwardedHeader: string | undefined, socketIp: string): string {
  if (!forwardedHeader) return socketIp;
  return forwardedHeader.split(",")[0].trim();
}
 
// HARDENED: Walk right-to-left, stripping only verified upstream proxy hops
function getClientIpHardened(
  forwardedHeader: string | undefined,
  socketIp: string,
  isTrustedProxy: (ip: string) => boolean
): string {
  if (!isTrustedProxy(socketIp)) {
    // Direct untrusted connection: ignore client-supplied forwarding headers completely
    return socketIp;
  }
  if (!forwardedHeader) return socketIp;
 
  const hops = forwardedHeader.split(",").map((part) => part.trim()).filter(Boolean);
  for (let i = hops.length - 1; i >= 0; i--) {
    const candidate = hops[i];
    if (!isTrustedProxy(candidate)) {
      return candidate;
    }
  }
  return socketIp;
}

Right-to-left parsing works because only proxies inside your trust boundary can be trusted to append accurate addresses. Walking backwards from the TCP socket peer skips every verified CDN or load balancer CIDR and stops at the first untrusted address, which represents the external client connection that entered your perimeter. Better yet, configure your edge proxy itself to overwrite or strip untrusted incoming X-Forwarded-For headers and emit a single dedicated internal header authenticated by network isolation or mutual TLS.

Once the origin is verified, the full request pipeline follows a strict sequence before touching password verification:

flowchart TD Req["Incoming Auth Request"] --> Edge["Trusted Edge Proxy (Strips Spoofed Headers)"] Edge --> Extract["Right-to-Left IP Extraction and Subnet Aggregation"] Extract --> Canon["Canonicalize Identifier (Lowercase and Trim)"] Canon --> Check{"Atomic Redis GCRA Check"} Check -->|"All Buckets Within Budget"| Verify["Verify Password Hash (Argon2id)"] Check -->|"Any Bucket Exceeded"| Decide{"Recognized Device or Step-Up Eligible?"} Decide -->|"No"| Reject["Return HTTP 429 With Retry-After"] Decide -->|"Yes"| Challenge["Require Passkey or MFA Step-Up"] Verify -->|"Valid Credentials"| Reset["Reset Composite Bucket and Issue Session"] Verify -->|"Invalid Credentials"| Penalize["Advance Failure State and Return Generic 401"]

Comparing Rate-Limiting Algorithms: Fixed Windows, Sliding Counters, and GCRA

Choosing the underlying counting algorithm determines whether bursts slip through clock boundaries and how much memory your state store consumes per active user. Fixed windows are trivial to write but fail under boundary bursts, whereas Sliding Window Counters and the Generic Cell Rate Algorithm (GCRA) eliminate boundary cliffs while holding constant memory per key.

Fixed Windows and the Boundary-Burst Cliff

A fixed-window limiter maps each request timestamp to a discrete bucket, such as floor(unix_seconds / 60), and increments a counter with a 60-second TTL. The vulnerability is the boundary cliff: if your limit is 10 requests per minute, an attacker can send 10 requests at 12:00:59 and 10 more at 12:01:01, pushing 20 requests through the gate within two seconds.

Sliding Window Logs vs. Sliding Window Counters

A sliding window log fixes the boundary cliff by storing every attempt timestamp inside a Redis Sorted Set (ZSET), pruning entries older than now - window, and checking ZCARD. While mathematically exact, it requires O(N) memory and write amplification per key, which becomes painful when protecting broad /24 or /48 spray buckets holding thousands of events.

A sliding window counter achieves near-exact smoothing in O(1) space by storing just two integers: the count in the current window and the count in the previous window. If the window is 60 seconds and we are 15 seconds (25%) into the current minute, the estimated rolling count is previous_count * 0.75 + current_count. This interpolation removes the boundary cliff with two atomic counters.

Token Buckets and Virtual Scheduling (GCRA)

For authentication, the Generic Cell Rate Algorithm (GCRA) is often the cleanest formulation of a leaky or token bucket. Instead of storing both a remaining token balance and a last_refill_timestamp, GCRA collapses state into a single timestamp called the Theoretical Arrival Time (TAT), representing when the bucket will be completely empty again.

Suppose a bucket allows a burst of $B$ failures and refills at a steady emission interval $T = \text{window} / B$ (for example, $B = 5$ attempts over 15 minutes gives $T = 180\text{ seconds}$ per token). Let $\text{burst_window} = B \times T$. When a request arrives at time now:

  1. Read stored tat (if missing, treat tat = now).
  2. Clamp tat up to now if the bucket has already rested past empty: effective_tat = max(tat, now).
  3. Compute the new schedule: new_tat = effective_tat + T.
  4. Compute the earliest time this request may proceed: allow_at = new_tat - burst_window.
  5. If now < allow_at, deny the request and return retry_after = allow_at - now without updating tat. Otherwise, allow the request and store new_tat with TTL new_tat - now.
Algorithm State Per Key Boundary Burst Immune Smooth Refill Memory Cost at 10M Keys
Fixed Window 1 integer No (allows 2x at edge) Step reset Low (~640 MB)
Sliding Window Log Sorted set of timestamps Yes Exact High (grows with limit $N$)
Sliding Window Counter 2 integers Mostly (interpolated) Approximate Low (~900 MB)
GCRA / Token Bucket 1 timestamp (TAT) Yes Exact continuous Very low (~640 MB)

Eliminating Race Conditions With Atomic Redis Lua Scripts

Implementing any of these algorithms with separate GET and SET round trips introduces a Time-of-Check to Time-of-Use (TOCTOU) race condition. If an attacker opens 40 parallel TCP connections and fires 40 login requests simultaneously, all 40 application workers read remaining = 5 before any worker writes back the updated state, allowing 40 guesses past a limit of 5.

Running the state transition inside a single-threaded Redis Lua script (EVALSHA) guarantees atomicity. Equally important, pulling the current clock directly from Redis via redis.call("TIME") prevents clock skew across horizontally scaled application pods from corrupting TAT comparisons.

-- KEYS[1] = bucket key
-- ARGV[1] = emission_interval_ms (e.g., 180000 for 5 req / 15m)
-- ARGV[2] = burst_capacity (e.g., 5)
-- ARGV[3] = cost (0 for read-only pre-check, 1 to consume token)
local time_parts = redis.call("TIME")
local now_ms = tonumber(time_parts[1]) * 1000 + math.floor(tonumber(time_parts[2]) / 1000)
 
local emission_ms = tonumber(ARGV[1])
local burst = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local burst_window_ms = emission_ms * burst
 
local raw_tat = redis.call("GET", KEYS[1])
local tat = raw_tat and tonumber(raw_tat) or now_ms
if tat < now_ms then
  tat = now_ms
end
 
local increment = emission_ms * cost
local new_tat = tat + increment
-- For a read-only check (cost == 0), test whether 1 token would fit
local probe_tat = cost == 0 and (tat + emission_ms) or new_tat
local allow_at = probe_tat - burst_window_ms
 
if now_ms < allow_at then
  local retry_after_ms = allow_at - now_ms
  return { 0, 0, retry_after_ms }
end
 
if cost > 0 then
  local ttl_ms = new_tat - now_ms
  if ttl_ms > 0 then
    redis.call("SET", KEYS[1], tostring(new_tat), "PX", ttl_ms)
  end
end
 
local used_ms = (cost > 0 and new_tat or tat) - now_ms
local remaining = math.max(0, math.floor((burst_window_ms - used_ms) / emission_ms))
return { 1, remaining, 0 }

Notice the cost parameter in that script. Authentication requires a two-phase pattern: first run a read-only check (cost = 0) on the failure buckets (paired with a generous cost = 1 flood ceiling on preauth_ip so an attacker cannot launch 100 parallel guesses before any failure writes back). If the user passes Argon2id verification, immediately delete the ip_user failure bucket so legitimate typos do not accumulate across weeks. Only when verification fails do you invoke the script with cost = 1 to advance the failure buckets.

Non-Blocking Cooldowns, Timing Oracles, and Progressive Friction

Enforcing a rate limit by calling sleep() inside an application worker converts an attacker's brute-force script into a thread-pool Denial of Service. Production services must reject throttled attempts immediately with HTTP 429 Too Many Requests and explicit retry metadata while carefully avoiding timing side channels.

When a handler sleeps for five seconds before responding, it holds open a worker thread, a database pool slot, and an upstream proxy socket for the entire duration. Five hundred concurrent requests from one script will starve a typical web tier of connections and knock legitimate users offline without cracking a single password. Returning a fast, non-blocking 429 response frees the worker in under a millisecond and signals well-behaved clients when they may retry:

HTTP/1.1 429 Too Many Requests
Retry-After: 45
RateLimit-Limit: 5
RateLimit-Remaining: 0
RateLimit-Reset: 45
Cache-Control: no-store
Content-Type: application/json
 
{"error":"too_many_attempts","retry_after_seconds":45}

Guarding Against Short-Circuit Timing Oracles

Returning 429 before running Argon2id protects your CPUs, yet it introduces a subtle account-enumeration risk if designed carelessly. Suppose an attacker guesses wrong passwords for two emails: [email protected] and [email protected]. If your backend skips password hashing for nonexistent users (returning 401 in 2 ms) while taking 110 ms to hash passwords for real accounts, an attacker can measure response latency to build a clean list of valid users. Worse, if you only increment user failure buckets when an account exists in the database, hitting a 429 itself proves the email is registered.

The clean fix is symmetric handling on both code paths. Always perform a dummy Argon2id computation against a static, pre-generated salt/hash when a username is not found in the database, and update the ip_user and user failure buckets identically regardless of whether the account exists. That keeps both response latency and rate-limit state transitions indistinguishable between registered and unregistered identifiers.

sequenceDiagram participant Attacker as Attacker Script participant Edge as Edge Proxy participant Auth as Auth Service participant Redis as Redis State Store Attacker->>Edge: POST /login (Attempts 1 to 5) Edge->>Auth: Forward with verified client IP Auth->>Redis: EVALSHA pre-check failure buckets Redis-->>Auth: Allowed (tokens remaining) Auth->>Auth: Run Argon2id (real hash or dummy hash) Auth->>Redis: EVALSHA consume 1 failure token Auth-->>Attacker: HTTP 401 Invalid credentials Attacker->>Edge: POST /login (Attempt 6 burst) Edge->>Auth: Forward with verified client IP Auth->>Redis: EVALSHA pre-check failure buckets Redis-->>Auth: Denied (retry_after = 180s) Note over Auth: Fast-rejects before Argon2id CPU work Auth-->>Attacker: HTTP 429 Too Many Requests (Retry-After: 180)

Progressive Friction vs. Permanent Account Lockouts

Legacy compliance checklists sometimes still prescribe locking an account permanently after five failed attempts until a helpdesk agent resets it. In public-facing applications, permanent lockouts hand attackers a zero-effort Denial-of-Service weapon: anyone holding a list of executive or customer email addresses can intentionally submit five bad passwords for every user each morning, paralyzing the entire organization without guessing a single credential.

Instead of permanent lockouts, combine progressive backoff with risk-based step-up challenges:

Defense Model Primary Signal Threat Coverage Blast Radius Operational Trade-Off
IP-Only Fixed Window Single client IP High-speed single-source brute force High: breaks shared VPNs, CGNAT, and campus NAT Simple code, high false-positive rate
Account-Only Hard Lockout Username or email Distributed guessing on one account Severe: enables trivial targeted self-DoS Heavy support ticket burden
Multi-Bucket + Progressive 429 ip_user, user, and subnet GCRA Single-source, distributed stuffing, and spraying Minimal: isolates attacker path from clean peers Requires atomic state store and trusted proxy headers
Risk-Based Step-Up Multi-bucket + device/passkey context Sophisticated residential-proxy credential stuffing Near zero for returning users with valid device tokens Highest implementation depth; best user experience

In a progressive friction design, consecutive failure streaks trigger escalating Retry-After delays (for example, 30 seconds, then 2 minutes, then 10 minutes), OR pivot to a step-up challenge rather than blocking the legitimate owner outright. If Alice signs in from a browser carrying an HMAC-signed recognized-device cookie (issued after a previous MFA login) or authenticates via a WebAuthn passkey, she bypasses the password-failure cooldown imposed by an attacker hammering her email from unknown infrastructure.

Protecting Adjacent Endpoints and Operating Safely in Production

Attackers rarely remain on /login once it is hardened; they immediately pivot to adjacent authentication routes that share the same trust assumptions. Operating rate limits safely in production also requires explicit failure modes, shadow testing, and observability so a cache outage never takes down logins worldwide.

Every credential-adjacent endpoint must carry dedicated, proportionally tuned rate limits:

  • MFA verification (/auth/mfa/verify): A standard 6-digit TOTP code has only $1{,}000{,}000$ possibilities, and codes typically remain valid for 30 to 90 seconds with clock skew tolerance. Bind a strict single-use failure counter directly to the MFA challenge ID (for example, invalidate the challenge token after 5 wrong digits) in addition to ip_user limits.
  • Password reset and magic links (/auth/forgot-password): Unthrottled reset endpoints enable email-bombing attacks against victims and can leak account existence or exhaust outbound mail quotas. Apply strict user and subnet GCRA buckets alongside uniform "If an account exists, instructions were sent" responses.
  • OAuth token and API batching endpoints (/oauth/token, /graphql): Never limit solely by outer HTTP request count on endpoints that accept arrays or GraphQL aliases. Count each authentication operation inside the batch against the bucket before executing resolvers.

Fail-Open vs. Fail-Closed and Local Fallbacks

Because an authentication rate limiter sits on the critical path of every login, its Redis cluster becomes a potential single point of failure. If Redis suffers a network partition or failover spike, strict fail-closed behavior blocks every legitimate user globally, turning a cache blip into a total authentication outage.

For customer-facing login endpoints, the resilient default is fail-open with a local in-memory fallback:

interface BucketDecision {
  allowed: boolean;
  retryAfterSeconds: number;
  source: "redis" | "local_fallback";
}
 
async function checkWithSafeFallback(
  key: string,
  shadowMode: boolean,
  evalRedis: (k: string) => Promise<{ allowed: boolean; retryAfterMs: number }>,
  evalLocalFallback: (k: string) => { allowed: boolean; retryAfterMs: number }
): Promise<BucketDecision> {
  try {
    // Enforce a strict timeout (e.g., 25ms) so a hung Redis socket never stalls login
    const res = await evalRedis(key);
    if (!res.allowed && shadowMode) {
      logShadowBlock(key, res.retryAfterMs);
      return { allowed: true, retryAfterSeconds: 0, source: "redis" };
    }
    return {
      allowed: res.allowed,
      retryAfterSeconds: Math.ceil(res.retryAfterMs / 1000),
      source: "redis",
    };
  } catch (err) {
    incrementMetric("auth.ratelimit.redis_error");
    // Local per-process token bucket absorbs single-node floods while Redis recovers
    const local = evalLocalFallback(key);
    return {
      allowed: shadowMode ? true : local.allowed,
      retryAfterSeconds: Math.ceil(local.retryAfterMs / 1000),
      source: "local_fallback",
    };
  }
}

Wrapping the Redis call in a tight 20 to 30 millisecond timeout ensures that a degraded cache node fails fast into an in-memory per-pod LRU token bucket rather than exhausting application threads waiting on TCP timeouts. That fallback does not share state across pods, so distributed attackers gain slightly higher burst headroom during an outage, but individual pods remain protected against CPU starvation while real users stay able to sign in.

Shadow Mode Rollout and Telemetry That Actually Matters

Before enforcing new thresholds in production, run them in shadow mode (dry-run) for at least one full traffic cycle. Instead of returning 429, log which bucket (ip_user, user, or subnet) would have rejected the request and whether the subsequent Argon2id check succeeded or failed.

That single piece of telemetry tells you almost everything you need to tune the system safely:

  • Valid-credential block rate: How often a throttled bucket actually intercepted a correct password. Even a small spike here signals that a shared corporate proxy or mobile CGNAT prefix is hitting your subnet or ip_user limits too aggressively.
  • Bucket collision breakdown: Comparing 429 counts across ip_user, user, and subnet shows whether you are facing a focused attack, distributed stuffing, or wide spraying.
  • Argon2id saturation and pre-hash drop ratio: Tracking how many requests are dropped by 429 before password hashing confirms whether your rate limiter is meaningfully shielding backend CPU during an active attack.

When rate limiting combines verified proxy boundaries, partitioned identity and network buckets, atomic GCRA state transitions, and non-blocking progressive friction, authentication stops being a fragile trade-off between security and uptime. Attackers lose their speed and compute leverage while real users behind messy shared networks barely notice the guardrails exist.

References & Sources

Related Security Reads

Comments

No comments yet.

Comments are moderated before they appear.

Get new posts by email

No ads, no tracking. Just new posts, unsubscribe any time.