Rate Limiter API

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2022-11-03

Problem Statement

🎯 Objective


Design a Rate Limiting System (API) that controls how many requests a user, client, or IP address can make to a service within a specified time window β€” ensuring fair usage, preventing abuse, and protecting backend resources.


🧾 Context


In large-scale systems (e.g., APIs like Twitter, AWS, or Google Maps), users may send excessive requests, intentionally or accidentally.


To ensure system reliability and fairness, we must limit the number of allowed requests per user within a certain time frame β€” such as 100 requests per minute or 1000 requests per hour.


This problem focuses on designing a Rate Limiter that:


β€’Can handle millions of API calls per second,
β€’Works in distributed systems, and
β€’Enforces rate limits accurately and efficiently.


🧱 Problem Statement

Design a distributed and scalable Rate Limiting API that ensures users or clients do not exceed a specified number of allowed API requests within a given time window.
The system should support various rate-limiting strategies, work across multiple instances of services, and maintain fairness and consistency even under high concurrency.


πŸ“‹ Functional Requirements


1.Rate Limit Rules
β€’Configure rules like β€œ100 requests per minute per user” or β€œ1000 requests per hour per IP.”
β€’Support dynamic configuration and custom limits per client or API key.
2.Rate Limiting Algorithms
β€’Support common algorithms like:
β€’Fixed Window Counter
β€’Sliding Window
β€’Token Bucket
β€’Leaky Bucket
3.API Interface
β€’allowRequest(userId) β†’ returns true or false depending on whether a request is allowed.
β€’Expose rate limit info via headers (e.g., X-RateLimit-Remaining).
4.Distributed Support
β€’Works consistently across multiple service nodes (e.g., load-balanced microservices).
5.Monitoring & Logging
β€’Track metrics: request count, blocked requests, usage per user.
β€’Generate alerts when thresholds are breached.
6.Persistence
β€’Maintain counters or token states across instances, possibly in a centralized store (like Redis).


βš™οΈ Non-Functional Requirements


Requirement and Description


Scalability

Should handle millions of concurrent users and requests.


Low Latency

Must introduce minimal delay (<5ms per request).


Consistency

Rate limit enforcement must be accurate across distributed nodes.


Availability

Should work even if one rate-limiting node fails.


Extensibility

Easy to integrate with new APIs or dynamic user plans.



Observability

Logs, dashboards, and alerts for limit usage and breaches.



🧩 High-Level Architecture


Core Components


1.API Gateway / Reverse Proxy
β€’Intercepts all incoming API requests.
β€’Communicates with Rate Limiter Service.
2.Rate Limiter Service
β€’Core logic for request counting and throttling.
β€’Implements rate-limiting algorithms.
3.Data Store
β€’Stores counters, tokens, or timestamps for each user/key.
β€’Example: Redis, Memcached.
4.Configuration Service
β€’Defines rate limit rules per user, plan, or endpoint.
5.Monitoring System
β€’Exposes metrics for dashboards (Grafana, Prometheus).


Architecture Diagram (Text Representation)

1 2 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” 3 β”‚ Client App β”‚ 4 β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 5 β”‚ 6 β–Ό 7 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” 8 β”‚ API Gateway β”‚ 9 β”‚ (Rate Limiter Plug) β”‚ 10 β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 11 β”‚ 12 β–Ό 13 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” 14 β”‚ Rate Limiter Serviceβ”‚ 15 β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 16 β”‚ 17 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” 18 β”‚ Redis / Distributed β”‚ 19 β”‚ In-memory Store β”‚ 20 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜


βš™οΈ Algorithmic Options


Algorithm, Description, Pros and Cons


Fixed Window Counter


Track requests in a fixed time window.

Simple, fast.

Bursty near window edge.


Sliding Window Log

Track timestamps of recent requests.

Accurate, fair.

High memory use.


Sliding Window Counter

Weighted average of two windows.

Smooth behavior.

Slight inaccuracy.


Token Bucket

Tokens refill at fixed rate; requests consume tokens.

Flexible (allows bursts).

Needs token synchronization.


Leaky Bucket

Enforces steady request rate.

Prevents burst.

Less flexible for real-time systems.


πŸ’Ύ Data Model Example (Redis)


KeyValueTTL

rate:user:123

count=45

expires_in=60s


βš™οΈ Flow Example


1.User U123 sends a request to the API Gateway.
2.Gateway calls RateLimiterService.allowRequest("U123").
3.Rate limiter checks in Redis:
β€’If count < limit, increments count and returns true.
β€’If count β‰₯ limit, blocks request (HTTP 429: Too Many Requests).
4.Gateway either forwards to backend or returns error.


πŸ“Š Scaling Strategies


β€’Sharding: Partition users across Redis shards using consistent hashing.
β€’Replication: Use Redis Cluster for high availability.
β€’Local Cache + Distributed Sync: Maintain local counters with periodic sync.
β€’Async Logging: Offload analytics to a Kafka-based pipeline.


🧠 Key Challenges & Discussion Points


Challenge and Discussion


Race Conditions

Multiple instances incrementing same counter β€” use atomic Redis ops (INCR, EXPIRE).


Global vs User-based Limits

How to design multi-tier limits (per IP, per endpoint, per org).


Dynamic Config Updates

Push updated rate rules without restart.


Rate Limit Bursting

Allow brief bursts without sustained overuse.


Multi-datacenter Setup

Sync counters across regions (e.g., Redis replication or vector clocks).


🧰 Tech Stack


ComponentExample


API Gateway

Nginx, Kong, AWS API Gateway


Rate Limiter Store

Redis, Memcached


Service Language

Go, Java, Node.js, Python


Metrics

Prometheus + Grafana


Queue (optional)

Kafka for logging and async updates


🧩 Sample API Response

1 2HTTP/1.1 429 Too Many Requests 3Content-Type: application/json 4X-RateLimit-Limit: 100 5X-RateLimit-Remaining: 0 6Retry-After: 60 7 8{ 9 "error": "Rate limit exceeded. Try again in 60 seconds." 10}


πŸ“˜ Interview Discussion Prompts


β€’Which algorithm would you choose for global-scale APIs (e.g., Twitter)?
β€’How would you handle distributed counters across multiple Redis nodes?
β€’How do you ensure fairness between users with different traffic patterns?
β€’How do you detect and prevent spikes or DDoS attempts?
β€’What happens when Redis crashes β€” how do you maintain state?


βœ… Deliverables


Deliverable and Description

Architecture Diagram

Depicts API gateway, rate limiter, and Redis.

Algorithm Justification

Comparison between LRU, token bucket, etc.

Scaling Strategy

How to distribute rate limits across nodes.

Error Handling & Monitoring

Metrics and fallback handling.


πŸ”Ή Final Summary

Design a distributed rate limiter that enforces request quotas across APIs or users in real-time.
The system must support configurable limits, TTL-based counters, consistency across distributed instances, and expose monitoring data for analytics and observability.


Solution

Comments