📌The Interview Question
"Design a rate limiter that limits API requests to 100 requests per minute per user"
📌Why Rate Limiting?
📌Step 1: Requirements
Functional
Non-Functional
📌Algorithm 1: Token Bucket
How it works:
public class TokenBucket { private final int capacity; private final int refillRate; // tokens per second private double tokens; private long lastRefillTime; public synchronized boolean tryConsume() { refill(); if (tokens >= 1) { tokens--; return true; } return false; } private void refill() { long now = System.currentTimeMillis(); double tokensToAdd = (now - lastRefillTime) / 1000.0 * refillRate; tokens = Math.min(capacity, tokens + tokensToAdd); lastRefillTime = now; }}Pros: Allows bursts, smooth rate limiting Cons: Memory for storing tokens
📌Algorithm 2: Leaky Bucket
How it works:
Pros: Smooth output rate Cons: Recent requests may wait long
📌Algorithm 3: Fixed Window Counter
How it works:
public class FixedWindowCounter { private final int limit; private final long windowSizeMs; private long windowStart; private int count; public synchronized boolean tryConsume() { long now = System.currentTimeMillis(); if (now - windowStart >= windowSizeMs) { windowStart = now; count = 0; } if (count < limit) { count++; return true; } return false; }}Pros: Simple, memory efficient Cons: Burst at window boundaries
📌Algorithm 4: Sliding Window Log
How it works:
Pros: Accurate, no boundary issues Cons: Memory intensive
📌Algorithm 5: Sliding Window Counter
How it works:
Requests = Previous window count * overlap% + Current window countBest choice for most cases!
📌Distributed Rate Limiting
Challenge
Solution: Redis
// Using Redis with Lua script for atomicityString script = """ local current = redis.call('INCR', KEYS[1]) if current == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end return current""";Long count = jedis.eval(script, 1, "user:123:minute", "60");return count <= limit;📌System Architecture
System Architecture
Live
Client
Rate Limiter
Middleware
Redis Cluster
Cache
API Server
⚡ High Availability🔄 Auto-scaling🛡️ Fault Tolerant
📌Interview Tips
What if Redis is down?
Our System Design course includes hands-on implementation of all these algorithms.