← Back to writing
Cyber Security Oct 12, 2026 5 min read

Zero-Trust Edge Defense: Rate-Limiting and Token-Bucket Ingress on Distributed Workers

Defending public API endpoints against automated brute-force attacks and credential stuffing using Cloudflare Workers edge enforcement without adding latency.

Zero-Trust Edge Defense: Rate-Limiting and Token-Bucket Ingress on Distributed Workers

The Economics of Ingress Protection

Allowing abusive requests to reach your origin database is expensive: compute costs surge, connection pools starve, and database latency degrades for genuine users.

Edge defense intercepts and evaluates ingress traffic at 300+ global points of presence within 15 milliseconds of the client, mitigating malicious actors before compute resources are consumed.


1. Token-Bucket Algorithm at the Edge

A fixed rate-limit (e.g. 60 requests per minute) causes bursts at boundary transitions. The Token Bucket algorithm allows natural bursting while enforcing strict long-term rate control:

interface RateLimitBucket {
  tokens: number;
  lastRefillTimestamp: number;
}

export function consumeToken(
  bucket: RateLimitBucket,
  capacity: number,
  refillRatePerSec: number
): boolean {
  const now = Date.now() / 1000;
  const elapsed = now - bucket.lastRefillTimestamp;
  
  // Calculate newly accrued tokens
  bucket.tokens = Math.min(capacity, bucket.tokens + elapsed * refillRatePerSec);
  bucket.lastRefillTimestamp = now;

  if (bucket.tokens >= 1) {
    bucket.tokens -= 1;
    return true; // Request allowed
  }

  return false; // Rate limit exceeded
}

2. Edge Implementation with Cloudflare Workers

By pairing edge workers with low-latency key-value memory:

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const clientIp = request.headers.get('CF-Connecting-IP') || 'unknown';
    const rateLimitKey = `ratelimit:${clientIp}`;

    const { success } = await env.RATE_LIMITER.limit({ key: rateLimitKey });

    if (!success) {
      return new Response(JSON.stringify({
        error: 'Too Many Requests',
        retryAfter: 60
      }), {
        status: 429,
        headers: {
          'Content-Type': 'application/json',
          'Retry-After': '60'
        }
      });
    }

    return fetch(request);
  }
};

3. Layered Progressive Tarpitting

Instead of immediately terminating connections with 429 errors—which alerts scrapers to rotate residential proxy IPs—implement progressive tarpitting:

  1. Zone 1 (Normal): Sub-50ms pass-through.
  2. Zone 2 (Elevated): Inject an artificial 1.5s delay into edge response stream.
  3. Zone 3 (Abusive): Issue lightweight non-interactive cryptographic proof-of-work challenges.

This drives up the compute and economic cost for attackers by orders of magnitude while preserving frictionless experiences for authentic users.

Primidac
Engineering notes
← More notes
Notification