Interactive Lab

Serverless Redis & Sliding Window Rate Limiting

Implement stateless HTTP Redis caching and protect serverless APIs with high-precision sliding window rate limiters.

upstash-ratelimit.ts
import { Redis } from '@upstash/redis';
import { Ratelimit } from '@upstash/ratelimit';

// 1. Serverless HTTP Redis Client (Zero TCP socket exhaustion)
export const redis = new Redis({
  url: process.env.UPSTASH_REDIS_REST_URL!,
  token: process.env.UPSTASH_REDIS_REST_TOKEN!
});

// 2. Sliding Window Counter Rate Limiter
// Allows 5 requests per 10-second rolling window per identifier
export const ratelimit = new Ratelimit({
  redis,
  limiter: Ratelimit.slidingWindow(5, '10 s'),
  analytics: true,
  prefix: '@ratelimit/api'
});

// 3. Edge/Serverless Middleware Guard
export async function handleRequest(ip: string) {
  const { success, limit, remaining, reset } = await ratelimit.limit(ip);

  if (!success) {
    return new Response(JSON.stringify({ error: 'Too Many Requests' }), {
      status: 429,
      headers: {
        'X-RateLimit-Limit': limit.toString(),
        'X-RateLimit-Remaining': remaining.toString(),
        'X-RateLimit-Reset': reset.toString(),
        'Retry-After': Math.ceil((reset - Date.now()) / 1000).toString()
      }
    });
  }

  return new Response(JSON.stringify({ status: 'ok', remaining }));
}

Sliding Window vs. Fixed Window

  • The Fixed Window Burst Flaw: In fixed window rate limiting, a user can fire all 5 requests at second 9 and another 5 requests at second 10, causing a 2x burst across the boundary.
  • The Sliding Window Solution: Tracks rolling weighted sub-windows in Redis memory, ensuring the client never exceeds the limit across any arbitrary 10-second slice.
  • Stateless HTTP Protocol: Upstash uses standard HTTPS requests instead of persistent TCP sockets, making it compatible with Cloudflare Workers and serverless functions without connection leaks.
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 edge requests.