Atomic Sliding-Window Rate Limiting

Katal v3 includes an enterprise-grade rate limiter that prevents API abuse, credential brute-forcing, and DDoS attacks. It supports an Atomic Sliding-Window algorithm, IP extraction with trusted proxy protection, and distributed Redis clustering with Lua scripts.


1. Quick Start

Apply global rate limiting with one method call:

import { Application, createRateLimitMiddleware } from "katal";

const app = new Application({ port: 3000 });

// 100 requests per 60 seconds globally per client IP
app.use(createRateLimitMiddleware({
    windowMs: 60_000,
    maxRequests: 100,
}));

await app.listen();

2. Sliding-Window Algorithm vs Fixed-Window

Traditional fixed-window limiters reset their counters at fixed intervals (e.g., at :00 and :01). This allows attackers to send 100 requests at :00:59 and another 100 requests at :01:01—effectively executing 200 requests in 2 seconds.

Katal uses an Atomic Sliding Window that calculates the exact rate dynamically across rolling time boundaries:

  Traditional Fixed Window: (Vulnerable to burst at boundaries)
  [  0 to 100 requests at :59s  ][  100 requests at :01s  ]  ==> 200 req in 2 sec! (Exploited)

  Katal Atomic Sliding Window: (Smooth rolling window)
  [────────────── Rolling 60-Second Window ──────────────]  ==> Strictly capped at 100 req

3. Standard Response Headers & HTTP 429

Katal attaches standardized RFC rate limit headers to all HTTP responses:

Header Description Example
X-RateLimit-Limit Maximum requests permitted in the window 100
X-RateLimit-Remaining Remaining requests available before hitting threshold 84
X-RateLimit-Reset UNIX epoch timestamp (in seconds) when the window resets 1776124800
Retry-After Seconds client must wait before retrying (sent on HTTP 429) 32

HTTP 429 Problem Details (RFC 7807 / 9457)

When the threshold is exceeded, Katal terminates the request with HTTP 429 Too Many Requests:

{
  "type": "about:blank",
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded. Please try again later.",
  "instance": "/api/v1/orders"
}

4. IP Extraction & Trusted Proxies

Behind reverse proxies (Cloudflare, AWS ALB, NGINX), direct client IP extraction can be spoofed by malicious headers unless proxies are explicitly validated.

Katal includes Trusted Proxy Validation:

app.use(createRateLimitMiddleware({
    windowMs: 60_000,
    maxRequests: 100,
    // Only trust headers from localhost or internal cloud load balancers
    trustedProxies: ["127.0.0.1", "10.0.0.0/8", "::1"],
}));

IP Resolution Priority:

  1. CF-Connecting-IP (Cloudflare)
  2. X-Real-IP (NGINX)
  3. X-Forwarded-For (First untrusted hop)
  4. Socket Remote Address (Direct TCP peer)

5. Custom Client Key Generators (User ID / API Key)

Rate limit by authenticated user ID or API key rather than shared office IP addresses:

// Rate limit authenticated users by their user ID, and anonymous users by IP
app.use(createRateLimitMiddleware({
    windowMs: 60_000,
    maxRequests: 200,
    keyGenerator: (ctx) => {
        if (ctx.user?.id) {
            return `user:${ctx.user.id}`;
        }
        const apiKey = ctx.request.headers.get("x-api-key");
        if (apiKey) {
            return `api_key:${apiKey}`;
        }
        return ctx.ip; // Fallback to safe client IP
    },
}));

6. Distributed Redis Clustering with Lua Scripts

In multi-instance production deployments (Kubernetes pods or serverless clusters), use the RedisRateLimitStore. Katal executes an atomic Lua script on Redis, preventing race conditions without needing distributed locks:

import { createRateLimitMiddleware, RedisRateLimitStore } from "katal";
import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL ?? "redis://localhost:6379");
const redisStore = new RedisRateLimitStore(redis);

app.use(createRateLimitMiddleware({
    windowMs: 60_000,
    maxRequests: 1000,
    store: redisStore,
}));

7. Tiered Route-Specific Rate Limiting

Apply strict limits on sensitive endpoints (e.g. login, payment checkout) and generous limits on public APIs:

const router = app.getRouter();

// Strict: 5 login attempts per 15 minutes per IP
const loginLimiter = createRateLimitMiddleware({
    windowMs: 15 * 60 * 1000,
    maxRequests: 5,
});
app.middleware("limit:login", loginLimiter);

router.post("/auth/login", LoginController, {
    middleware: ["limit:login"],
});

// Generous: 1,000 requests per minute for public data
const publicLimiter = createRateLimitMiddleware({
    windowMs: 60_000,
    maxRequests: 1000,
});
app.middleware("limit:public", publicLimiter);

router.get("/api/products", ListProductsController, {
    middleware: ["limit:public"],
});

See Also