APIs & Data Architecture Backend & Data

20. Edge Caching & Sliding Window Rate Limiting

Deploy stateless HTTP Redis caching, defend APIs against brute force attacks with sliding window algorithms, and manage distributed edge state.

redis-ratelimit.ts
typescript
import { Redis } from '@upstash/redis';
import { Ratelimit } from '@upstash/ratelimit';
const redis = Redis.fromEnv();
// Sliding Window Algorithm: 10 requests allowed per 10-second window
export const ratelimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(10, '10 s'),
analytics: true
});
export async function protectApiEndpoint(clientIp: string) {
const { success, limit, remaining, reset } = await ratelimit.limit(clientIp);
return { allowed: success, remaining, resetTimeMs: reset };
}

Edge Caching & Sliding Window Rate Limiting

Sliding window algorithms in Upstash Redis over stateless HTTP prevent traffic burst exploits across fixed window intervals and defend against DDoS attacks.

  • The Fixed Window Burst Vulnerability: In fixed window rate limiting, a client can send its full limit at second 9 and another batch at second 10, executing a 2x burst across the boundary.
  • Sliding Window Smoothness: Tracks a continuous rolling weighted window in Redis memory, ensuring the client never exceeds quota across any arbitrary slice of time.
  • Stateless HTTP Redis: Upstash uses standard HTTPS requests instead of persistent TCP sockets, eliminating connection exhaustion on Cloudflare Workers and serverless edges.
Sliding Window Rate Limiter HTTP 200: OK
Rolling Window: 10s
Remaining Quota:

5 / 5

Active Window Slots:
Edge Gateway Response Log:
Click "Invoke" to simulate incoming edge requests.