4 Hours

8. Rate Limiting with Redis

Rate Limiting

Building Distributed Rate Limiting

Rate limiting controls the rate of requests to APIs and services. Redis is ideal for rate limiting because it's fast, supports atomic operations, and can be shared across servers. This module covers rate limiting algorithms, implementations, and best practices for production deployments.

Rate limiting protects APIs from abuse, ensures fair usage, and prevents overload. Redis supports atomic operations like INCR and EXPIRE, making it perfect for rate limiting. Multiple rate limiting algorithms are available: fixed window, sliding window, and token bucket. Each has different characteristics and use cases. Understanding rate limiting is essential for building robust APIs and services.

This module covers each algorithm in depth with implementation examples, performance characteristics, and production considerations. You'll learn to implement rate limiting that scales to millions of requests.

Fixed Window Rate Limiting

Fixed window rate limiting counts requests in a fixed time window. It's simple to implement and efficient. Use INCR to count requests. Use EXPIRE to reset the window. This pattern is suitable for many use cases where a slight burst at window boundaries is acceptable.

The fixed window algorithm has a limitation: at the boundary between windows, a user can make twice the limit in a short period (e.g., limit 100/hour, 100 at 11:59 and 100 at 12:00). For most applications, this is acceptable. For stricter limits, use sliding window or token bucket.

JavaScript
// Fixed window rate limiter
async function fixedWindowRateLimiter(userId, limit, windowSeconds) {
  const key = `ratelimit:${userId}:${Math.floor(Date.now() / (windowSeconds * 1000))}`;
  
  // Atomically increment and get count
  const count = await redis.incr(key);
  if (count === 1) {
    await redis.expire(key, windowSeconds);
  }
  
  const remaining = Math.max(0, limit - count);
  const reset = Math.floor(Date.now() / 1000) + windowSeconds;
  
  return { allowed: count <= limit, remaining, reset, limit };
}

// Usage
const result = await fixedWindowRateLimiter('user:123', 100, 3600);
if (!result.allowed) {
  throw new Error('Rate limit exceeded');
}

Sliding Window Rate Limiting

Sliding window rate limiting provides more accurate rate limiting. It tracks requests over a sliding time window. Use sorted sets to store request timestamps. This pattern is more accurate but more complex. Use sliding window for strict rate limits where accuracy is critical.

The sliding window algorithm maintains a sorted set of timestamps for each user. Old timestamps are removed, and the count is calculated from the current window. This provides exact rate limiting without the window boundary issue. However, it uses more memory than fixed window.

JavaScript
// Sliding window rate limiter
async function slidingWindowRateLimiter(userId, limit, windowSeconds) {
  const key = `ratelimit:${userId}`;
  const now = Date.now();
  const windowStart = now - (windowSeconds * 1000);
  
  // Remove old requests
  await redis.zremrangebyscore(key, 0, windowStart);
  
  // Add current request
  const member = `${now}-${Math.random()}`;
  await redis.zadd(key, now, member);
  
  // Get count
  const count = await redis.zcard(key);
  
  // Set TTL
  await redis.expire(key, windowSeconds);
  
  const remaining = Math.max(0, limit - count);
  const oldest = await redis.zrange(key, 0, 0, 'WITHSCORES');
  const reset = oldest.length > 0 ? Math.floor(oldest[1] / 1000) + windowSeconds : Math.floor(now / 1000) + windowSeconds;
  
  return { allowed: count <= limit, remaining, reset, limit };
}

Token Bucket Algorithm

The token bucket algorithm provides flexible rate limiting with burst capability. Tokens are added to a bucket at a fixed rate. Each request consumes a token. If the bucket is empty, requests are rejected. Use token bucket for APIs that need burst capability, allowing occasional spikes while maintaining an average rate.

The token bucket algorithm is ideal for APIs that need to handle bursts of traffic without rejecting requests. It allows a user to accumulate unused capacity and use it for bursts. The rate parameter controls the steady-state request rate. The capacity parameter controls the maximum burst size.

JavaScript
// Token bucket rate limiter
async function tokenBucketRateLimiter(userId, rate, capacity) {
  const key = `bucket:${userId}`;
  const now = Date.now() / 1000;
  
  // Get current bucket state
  const data = await redis.hgetall(key);
  if (!data || Object.keys(data).length === 0) {
    // Initialize bucket
    await redis.hset(key, {
      tokens: capacity,
      lastRefill: now
    });
    await redis.expire(key, 3600);
    return { allowed: true, remaining: capacity - 1 };
  }
  
  // Calculate refill
  const elapsed = now - parseFloat(data.lastRefill);
  const refill = Math.floor(elapsed * rate);
  const tokens = Math.min(capacity, parseFloat(data.tokens) + refill);
  
  if (tokens < 1) {
    return { allowed: false, remaining: 0 };
  }
  
  // Consume token
  const remaining = tokens - 1;
  await redis.hset(key, {
    tokens: remaining,
    lastRefill: now
  });
  await redis.expire(key, 3600);
  
  return { allowed: true, remaining };
}

Knowledge Check

Ready to test your understanding of 8. Rate Limiting with Redis?

Back