Rate Limiter API Design

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2021-04-30

Problem Statement

Modern web services need to protect themselves from abuse, ensure fair usage, and maintain system stability. A Rate Limiter is a crucial infrastructure component that restricts how many requests a user, IP address, or service can make in a given time window.


🎯 Problem Statement


Design a Rate Limiting Service that controls the number of API requests clients can make within a specified time interval.


The service should be:


•Highly available
•Low latency
•Scalable across distributed systems


⚙️ Functional Requirements


Request Limiting:

•Limit the number of API calls a client can make within a specific time window (e.g., 100 requests per minute).
•Allow defining different limits per client, API key, or endpoint.

Configurable Rules:

•Each API or customer can have custom rate-limiting rules (e.g., “50 req/sec”, “1000 req/hour”).

Real-time Enforcement:

•Block or throttle requests that exceed the limit.
•Return a standard response (HTTP 429 Too Many Requests) when throttled.

Distributed Support:

•Should work across multiple instances of APIs (no single node dependency).

Monitoring & Metrics:

•Expose metrics (e.g., current rate usage, limit breaches).
•Provide dashboards or logs for debugging and analysis.

Administration API (optional):

•CRUD operations for adding/updating rate-limiting rules.


🚫 Non-Functional Requirements


Requirement with Description


Latency

< 5 ms per request check


Scalability

Must handle millions of requests/sec across distributed nodes


Consistency

Eventually consistent is acceptable, but limit enforcement must be fair


Reliability

Should gracefully degrade under high load


Extensibility

Support new algorithms or dynamic configurations easily


🧩 Key Design Considerations

Algorithms

•Support different rate-limiting strategies:
•Fixed Window Counter
•Sliding Window Log
•Sliding Window Counter
•Token Bucket / Leaky Bucket (recommended for distributed systems)

Data Storage

•Fast access store like Redis, Memcached, or in-memory cache for counters.
•Distributed lock or atomic increment operations for synchronization.

Identifier

•Limit applied per:
•API key
•User ID
•IP address
•Endpoint

Deployment

•As a standalone microservice (RateLimiter API)
•Or as a shared library within each service.


🏗️ High-Level Architecture Components


Client / API Gateway

•Sends requests to backend APIs.
•Forwards metadata (API key, IP, etc.) to the Rate Limiter service.

Rate Limiter Service

•Stateless API layer.
•Receives request info → applies rate-limiting logic → responds with "allowed"/"blocked".
•Caches state (tokens/counters) in Redis or similar fast store.

Storage Layer (Redis / DynamoDB)

•Holds request counters or token buckets.
•Supports atomic operations and TTLs.

Configuration Service

•Stores rules per API/user.
•Supports dynamic reloading without downtime.

Monitoring & Logging

•Prometheus/Grafana for metrics.
•Centralized logging for limit breaches and latency tracking.


🧠 Example Flow


Use Case:

Limit = 5 requests per 10 seconds per user.

1.User A sends a request → RateLimiter checks count in Redis.
2.If under limit → increment count, allow request.
3.If limit reached → block request, respond with 429.
4.Counter automatically expires after 10 seconds (using Redis TTL).


📊 Possible APIs

1 2POST /rate-limit/check 3Content-Type: application/json 4{ 5 "apiKey": "user123", 6 "endpoint": "/api/v1/payment", 7 "timestamp": 1730000000 8}


Response:

1 2{ 3 "allowed": true, 4 "remaining": 2, 5 "reset_in": 3 6}


⚖️ Scalability Enhancements


•Use Redis Cluster or Amazon ElastiCache for horizontal scaling.
•Deploy behind API Gateway (e.g., Nginx, Envoy) with local caching.
•Introduce lazy sync or approximation algorithms for extremely high throughput.


🔒 Bonus Considerations


•Rate Limit Hierarchies: global, per-IP, per-user, per-endpoint.
•Dynamic Quotas: user tiers (Free vs Premium users).
•Burst Handling: allow short bursts but enforce sustained limit.
•Rate Limit Sharing: multiple microservices sharing a central limit quota.


💬 Example Interview Prompt (Final Form)

Design a Rate Limiter API that can control the number of requests a user or client can make within a defined time window.
The service should support multiple rate-limiting algorithms (e.g., token bucket, sliding window), handle millions of requests per second, and work seamlessly across distributed API servers.
Discuss how you would ensure scalability, consistency, and low latency in your design.


Solution

Comments