Design a rate-limiting system

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2025-05-01

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:


•Control the rate of API requests from users, IPs, or clients.
•Support configurable policies (per endpoint, per user, per method).
•Integrate easily with multiple microservices.
•Provide near real-time enforcement with minimal latency overhead.
•Offer dashboards, alerts, and metrics for observability.


✅ Functional Requirements


1. Request Throttling


•Limit the number of API requests allowed in a given time window.

Example:

•100 requests/min per user.
•1000 requests/hour per IP.


2. Configurable Policies


•Define rate limits based on:
•User ID / API Key
•IP Address
•Endpoint (API path)
•Service Type (internal/external APIs)
•HTTP method (GET, POST, etc.)
•Policies can be defined dynamically by admins.


3. Distributed Enforcement


•Should support rate limiting across multiple servers or regions.
•Ensure consistent enforcement even in horizontally scaled systems.


4. Burst Handling


•Allow short bursts of traffic within limits using algorithms like token bucket or leaky bucket.


5. Real-Time Feedback


•Return appropriate HTTP responses:
•200 OK → Allowed.
•429 Too Many Requests → Limit exceeded.
•Include headers like:
1 2X-RateLimit-Limit: 100 3X-RateLimit-Remaining: 25 4X-RateLimit-Reset: 60


6. Monitoring and Analytics


•Track request counts, violations, latency.
•Provide admin dashboards for policy management and traffic insights.


⚙️ 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.A client sends an API request → Service A.
2.Service A calls the Rate Limiter Service (or local SDK) with:
1 2checkLimit(user_id, api_endpoint)
1.Rate Limiter:
•Fetches policy for the key (e.g., user_id + endpoint).
•Checks tokens/counter in cache (Redis).
•If tokens available → allow request and decrement token.
•Else → block request and respond with 429.
2.Returns updated headers and metrics to the client.


🧠 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

•AuthN/Z for policy management APIs (e.g., JWT or service tokens).
•Signed requests between services and rate limiter.
•IP whitelisting for trusted systems.
•Audit logs for all policy changes.


🧰 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

•Metrics:
•requests_allowed_total
•requests_blocked_total
•latency_avg
•cache_hit_ratio
•Dashboards per service/user.
•Alerts on:
•Spike in blocked requests.
•Latency > threshold.
•Cache unavailability.

🚨 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:

•Can throttle millions of requests across distributed services.
•Provides configurable and adaptive rate-limiting policies.
•Ensures consistent user experience while protecting APIs from misuse.


Solution

Comments