Design a rate-limiting system
Problem Statement
Design a Rate-Limiting System that helps protect APIs and services from abuse, excessive traffic, or denial-of-service attacks by limiting the number of requests a user, client, or IP address can make within a specified time window.
The system should be scalable, highly available, and configurable to support different rate-limiting policies across microservices, users, and applications in a distributed environment.
🎯 Objective
Build a centralized, low-latency, and fault-tolerant rate-limiting service that can:
✅ Functional Requirements
1. Request Throttling
Example:
2. Configurable Policies
3. Distributed Enforcement
4. Burst Handling
5. Real-Time Feedback
1
2X-RateLimit-Limit: 100
3X-RateLimit-Remaining: 25
4X-RateLimit-Reset: 606. Monitoring and Analytics
⚙️ Non-Functional Requirements
| Attribute | Goal |
| ------------------- | ---------------------------------------------------------- |
| **Scalability** | Support millions of requests per second |
| **Latency** | Add <5ms overhead per request |
| **Availability** | 99.99% uptime |
| **Consistency** | Soft consistency acceptable; focus on performance |
| **Extensibility** | Support multiple algorithms (Token Bucket, Sliding Window) |
| **Fault Tolerance** | Continue operating even if a cache node fails |
| **Security** | Only authorized services can configure or query limits |
🧩 Core Components
Component with Responsibility
Rate Limiter Library (Client SDK)
Embedded in each microservice; communicates with central service or local cache.
Rate Limiter Service
Central system enforcing limits and maintaining counters.
Policy Management Service
Admin UI & API for defining and updating rate-limiting policies.
Storage Layer
Stores counters, tokens, and policies. (Redis / DynamoDB)
Cache Layer
Low-latency storage for token counters and metadata.
Monitoring & Alerts Service
Exposes metrics to Prometheus/Grafana.
Admin Console
GUI for viewing rate limits, violations, and trends.
🧱 High-Level Architecture
1
2 +-----------------------------+
3 | Admin Console |
4 +-------------+---------------+
5 |
6 v
7 +---------+----------+
8 | Policy Management |
9 | Service |
10 +---------+----------+
11 |
12 v
13 +---------------------+-----------------------+
14 | Rate Limiter Service |
15 |---------------------------------------------|
16 | - Token Bucket Logic |
17 | - Counter Storage |
18 | - Sliding Window Management |
19 | - Policy Fetching & Validation |
20 +---------------------+-----------------------+
21 |
22 v
23 +--------+--------+
24 | Cache/Store |
25 | (Redis Cluster) |
26 +--------+--------+
27 ^
28 |
29 +----------------+----------------+
30 | |
31+-------+--------+ +--------+-------+
32| Service A | | Service B |
33| (API Gateway) | | (User Service) |
34+-------+--------+ +--------+-------+
35 | |
36 +---------------------------------+
37 |
38 v
39 +--------------------+
40 | Client / Browser |
41 +--------------------+🔄 Request Flow
1
2checkLimit(user_id, api_endpoint)🧠 Rate-Limiting Algorithms
| Algorithm | Description | Use Case |
| ------------------------------ | -------------------------------------------------------------- | ---------------------------------------- |
| **Token Bucket** | Adds tokens at fixed rate, consumes on request. | Allows short bursts, common in APIs. |
| **Leaky Bucket** | Requests are processed at a fixed rate; excess queued/dropped. | Smooths traffic. |
| **Fixed Window Counter** | Counts requests per fixed window. | Simple, but can spike at window edges. |
| **Sliding Window Log/Counter** | More accurate per-time tracking. | Real-time fairness; higher storage cost. |
🧾 Data Model (Simplified)
RateLimitPolicy
1
2{
3 "policy_id": "user_api_policy_01",
4 "key_type": "user_id",
5 "limit": 100,
6 "window": 60,
7 "algorithm": "token_bucket",
8 "burst_capacity": 20,
9 "applies_to": ["/api/v1/orders", "/api/v1/cart"]
10}TokenBucket
1
2{
3 "key": "user_123:/api/v1/orders",
4 "tokens": 25,
5 "last_refill": "2025-10-24T13:00:00Z"
6}⚡ Scalability and Performance Strategies
| Challenge | Solution |
| --------------------------- | ----------------------------------------------------------- |
| **High traffic volume** | Use Redis cluster for distributed counters. |
| **Hot keys (popular APIs)** | Shard keys by hash or region. |
| **Consistency** | Use Lua scripts in Redis for atomic operations. |
| **Latency** | Embed SDK for local caching; fallback to async updates. |
| **Global rollout** | Region-local rate limiter clusters with sync through Kafka. |
🔒 Security and Access Control
🧰 Tech Stack (Example)
| Layer | Technology |
| ----------------------- | --------------------------- |
| **Gateway Integration** | NGINX / Envoy / API Gateway |
| **Core Logic** | Go / Java / Node.js |
| **Storage** | Redis Cluster / DynamoDB |
| **Queue for sync** | Kafka |
| **Metrics** | Prometheus + Grafana |
| **Policy Admin** | React + REST APIs |
| **Security** | OAuth2, mTLS |
📊 Monitoring & Observability
🚨 Failure Handling
| Failure | Mitigation |
| ------------------------- | --------------------------------------- |
| **Cache Down** | Fallback to in-memory rate limit. |
| **Network Partition** | Allow local decisions; sync later. |
| **Policy Update Failure** | Retry with exponential backoff. |
| **Node Crash** | Stateless nodes with Redis persistence. |
✅ End Goal
Design a highly scalable, low-latency Rate Limiting System that: