Skip to main content
Rate Limiting Algorithms

Problem Statement

Design a rate limiter that:
  • Limits requests per user/API key to prevent abuse
  • Works across multiple servers (distributed)
  • Has minimal latency impact
  • Supports different rate limits per tier
This is a medium difficulty problem but very important! Rate limiting is asked frequently because it touches on distributed systems concepts. Know the algorithms well!

Step 1: Requirements

Functional Requirements

  • Limit requests per user/IP/API key
  • Different limits for different endpoints
  • Different tiers (free: 100/hour, paid: 10,000/hour)
  • Return appropriate error when limit exceeded

Non-Functional Requirements

  • Low Latency: < 10ms overhead per request
  • Accurate: No significant over-limiting or under-limiting
  • Distributed: Work across multiple servers
  • Fault Tolerant: Fail open if rate limiter is down

Quick Estimation

Step 2: Rate Limiting Algorithms

Algorithm 1: Token Bucket ⭐ (Most Common)

Algorithm 2: Sliding Window Log

Step 3: Algorithm Comparison

Step 4: High-Level Design

Response Headers

Step 5: Distributed Rate Limiting

Challenge: Multiple Servers

Redis-Based Solution

Step 6: Rate Limiting by Tier

Step 7: Complete Architecture

Key Design Decisions

Common Interview Questions

Fail open strategy:
  1. If Redis unavailable, allow all requests
  2. Log warning for monitoring
  3. Availability > perfect rate limiting
  4. Have backup local rate limiter (approximate)
Alternative: Fail closed for critical endpoints (auth, payments)
  1. Use Redis server time, not client time
  2. Redis TIME command for consistency
  3. NTP sync on all servers
  4. Allow small tolerance in window boundaries
Layer the limits:
Use atomic operations:
  1. Redis Lua scripts (atomic execution)
  2. INCR command (atomic increment)
  3. WATCH/MULTI/EXEC (optimistic locking)
  1. Token bucket naturally allows bursts up to capacity
  2. Use higher limit with shorter window
  3. Queue excess requests instead of rejecting
  4. Implement retry with exponential backoff on client
  5. Consider adaptive rate limiting based on system load

Quick Reference Card