The Wayback Machine - https://web.archive.org/web/20261201173944/https://www.geeksforgeeks.org/system-design/how-to-design-a-rate-limiter-api-learn-system-design/

Design a Rate Limiter API | Learn System Design

Last Updated : 11 Sep, 2026

Designing a Rate Limiter API means building a system that controls how many requests a user, IP address, API key, or service can make within a specific period of time. In system design interviews, the main focus is on very low latency, distributed coordination, scalability, and preventing abuse.

  • The system should allow requests that are within the configured limit and reject requests that exceed it.
  • It should work correctly even when traffic is distributed across many application servers.

1. Problem Statement

We need to design a Rate Limiter API that checks every incoming request and decides whether it should be allowed or rejected based on predefined rate-limiting rules.

For example:

A user can make a maximum of 100 API requests per minute.

After the user reaches this limit, additional requests should be rejected until the limit becomes available again.

  • Rate limits should be configurable based on User ID, IP Address, API Key, Endpoint, or Service.
  • The system should support multiple rate-limiting policies such as requests per second, minute, or hour.
  • It should work correctly across multiple servers in a distributed environment.
  • The rate limiter should add very little latency to normal API requests.
  • When the limit is exceeded, the API should return an appropriate response such as HTTP 429 Too Many Requests.

2. System Requirements

Before designing the Rate Limiter API, we need to define its functional and non-functional requirements. These requirements decide how limits are configured, enforced, and scaled across multiple servers.

Functional Requirements

  • The system should allow or reject requests based on configured rate limits.
  • It should support rate limiting by User ID, IP Address, API Key, Endpoint, and Service.
  • It should support different limits, including requests per second, minute, and hour.
  • It should support multiple rate-limiting algorithms, including Fixed Window, Sliding Window, Token Bucket, and Leaky Bucket.
  • Rate-limit rules should be configurable and updatable.
  • The system should return the remaining quota and retry information.
  • When the rate limit is exceeded, the system should return HTTP 429 Too Many Requests.
  • Different users or API plans should support different rate limits.

Non-Functional Requirements

  • Low Latency: Rate-limit checks should add very little delay to API requests.
  • High Availability: The rate limiter should remain available even if some nodes fail.
  • Scalability: It should handle millions of requests per second.
  • Consistency: Request counters should remain reasonably accurate across distributed servers.
  • Fault Tolerance: Failure of one rate-limiter node should not affect the complete system.
  • High Throughput: The system should process a very large number of rate-limit checks efficiently.
  • Configurability: Rate-limit policies should be easy to update without redeploying the complete application.
  • Security: The system should prevent users from bypassing limits using malformed or manipulated identifiers.

3. Capacity Estimation

Before designing the Rate Limiter API, we estimate how many requests the system must process and how much memory is needed to store rate-limit counters.

Assumptions

ParameterAssumption
Daily API Requests10 Billion
Average Requests per Second~115,000
Peak Requests per Second1 Million
Active Users / API Keys100 Million
Average Counter Size100 Bytes
Rate Limit Check Latency Target< 5 ms

3.1 Request Rate

Assume the system receives around 10 billion requests per day.

Average RPS = 10 Billion / 86,400
≈ 115,000 requests/second

During peak traffic:

Peak RPS ≈ 1 Million requests/second

Since every request may pass through the rate limiter, the system must support very high throughput.

3.2 Counter Storage

Assume we maintain rate-limit state for around 100 million active users or API keys.

If each counter requires around 100 bytes:

Storage = 100 Million × 100 Bytes
≈ 10 GB

This state can be distributed across multiple Redis nodes.

3.3 Network Traffic

Each rate-limit check may require only a small request containing information such as:

  • User ID or API key
  • Endpoint
  • Current timestamp
  • Rate-limit rule

Because the number of checks is extremely high, the rate limiter should be deployed close to the API Gateway or application servers to reduce network latency.

3.4 Rate Limiter Nodes

Assume one rate-limiter node can process around 50,000 checks per second.

For a peak load of 1 million requests per second:

Nodes Required = 1,000,000 / 50,000
≈ 20 Nodes

In practice, additional nodes should be kept for redundancy, failures, and sudden traffic spikes.

3.5 Cache Requirement

The rate limiter should avoid hitting a traditional database for every request.

A fast in-memory store such as Redis can be used to maintain:

  • Request counters
  • Token buckets
  • Sliding-window data
  • Rate-limit configuration cache
  • Temporary block information

4. High Level Design

The High-Level Design (HLD) shows how the Rate Limiter works between clients and backend services. Every incoming request is checked against the configured rate-limit policy before it is allowed to reach the application.

frame_3666
Rate Limiter API - High Level Architecture

Core Components

  • Client: Sends API requests to the application.
  • API Gateway: Acts as the entry point for incoming requests.
  • Rate Limiter Service: Checks whether the request should be allowed or rejected.
  • Rate Limit Rules Service: Stores and manages rules such as 100 requests/minute.
  • Redis Cluster: Stores request counters, token buckets, sliding-window data, and temporary blocking information.
  • Application Servers: Process requests that pass the rate-limit check.
  • Configuration Database: Stores permanent rate-limit policies for users, APIs, plans, and services.
  • Local Cache: Keeps frequently used rate-limit rules close to the Rate Limiter Service.
  • Monitoring Service: Tracks allowed requests, rejected requests, latency, and Redis health.
  • Admin Dashboard: Allows administrators to create or update rate-limit policies.

Request Flow

frame_3665
Rate Limiter API - Request Flow Diagram
  • The client sends an API request.
  • The request reaches the API Gateway.
  • The API Gateway identifies the user, IP address, API key, and requested endpoint.
  • The request is sent to the Rate Limiter Service.
  • The Rate Limiter Service loads the applicable rate-limit rule.
  • It checks the current request count or token-bucket state in Redis.
  • If the request is within the limit, the counter is updated and the request is allowed.
  • The API Gateway forwards the request to the Application Server.
  • If the limit is exceeded, the Rate Limiter rejects the request.
  • The client receives HTTP 429 Too Many Requests with retry information.

Data Flow

  • Permanent rate-limit policies are stored in the Configuration Database.
  • Frequently used policies are cached locally or in Redis.
  • Redis stores fast-changing rate-limit state such as counters and tokens.
  • Counter updates should be atomic so multiple Rate Limiter nodes do not incorrectly allow extra requests.
  • Expiration times are attached to temporary counters so old rate-limit data is automatically removed.
  • Monitoring data is sent asynchronously to the Monitoring Service for dashboards and alerts.
  • The main application database is not accessed during every rate-limit check, keeping the request path fast.

5. Technology Stack

Before designing the data model, we identify the technologies that can be used for different components of the Rate Limiter API.

ComponentTechnology
Client CommunicationREST API, HTTPS
API GatewayNGINX, Kong, Envoy, AWS API Gateway
Rate Limiter ServiceJava, Go, Node.js
In-Memory Counter StoreRedis
Distributed CacheRedis Cluster
Configuration DatabasePostgreSQL, MySQL
Local CacheCaffeine, Guava Cache
Distributed Locking / Atomic UpdatesRedis Lua Scripts, Redis Transactions
Message QueueKafka, RabbitMQ
MonitoringPrometheus, Grafana
LoggingELK Stack, OpenSearch
ContainerizationDocker
OrchestrationKubernetes
Service CommunicationREST, gRPC

6. Data Model Design

The data model defines how the Rate Limiter stores rate-limit rules, client identifiers, counters, and usage information. Since request counters change very frequently, fast in-memory storage is more important than complex relational modeling.

  • Store permanent rate-limit rules separately from real-time counters.
  • Keep frequently updated counters in a fast store such as Redis.
  • Use expiration times so old rate-limit data is removed automatically.

Core Entities

The Rate Limiter API can use the following core entities:

frame_3664
Rate Limiter API - ER Diagram
  • RateLimitRule: Stores limit value, time window, algorithm type, and scope.
  • Client: Represents the entity being limited, such as a user, IP address, API key, or service.
  • Endpoint: Stores API endpoint information and its associated rate-limit policy.
  • RateLimitCounter: Stores the current request count for a specific client and time window.
  • TokenBucket: Stores available tokens, bucket capacity, and token refill rate.
  • UsageLog: Stores allowed and rejected request information for monitoring and analytics.

Database Selection

A combination of Redis and a relational database works well for a distributed Rate Limiter.

  • Redis: Stores real-time counters, token buckets, sliding-window data, and temporary blocking state.
  • PostgreSQL / MySQL: Stores permanent rate-limit rules, API plans, endpoint configuration, and client policies.
  • Local Cache: Stores frequently accessed rules inside Rate Limiter nodes to avoid reading the database repeatedly.
  • TTL: Redis keys should have expiration times so counters from old windows are deleted automatically.
  • Atomic Operations: Redis Lua scripts or atomic commands should be used to check and update counters in a single operation, preventing race conditions between multiple Rate Limiter nodes.

7. API Design

The API design defines how the API Gateway or backend services communicate with the Rate Limiter to check limits, manage policies, and retrieve usage information.

  • The rate-limit check API should be extremely fast because it may be called for every incoming request.
  • Administrative APIs should allow rate-limit rules to be created, updated, and deleted.
  • The API should return clear information such as whether the request is allowed, how much quota remains, and when the client can retry.

Rate Limit Check API

MethodEndpointDescription
POST/api/v1/rate-limit/checkCheck whether a request should be allowed
GET/api/v1/rate-limit/statusGet current rate-limit usage
POST/api/v1/rate-limit/resetReset a client's rate-limit state

Policy Management APIs

MethodEndpointDescription
POST/api/v1/rate-limit/policiesCreate a new rate-limit policy
GET/api/v1/rate-limit/policies/{policyId}Get policy details
PUT/api/v1/rate-limit/policies/{policyId}Update a policy
DELETE/api/v1/rate-limit/policies/{policyId}Delete a policy

Sample Check Request

POST /api/v1/rate-limit/check

{
"clientId": "user_101",
"clientType": "USER",
"endpoint": "/api/orders",
"method": "POST"
}

Sample Allowed Response

{
"allowed": true,
"limit": 100,
"remaining": 24,
"resetAfterSeconds": 18
}

Sample Rejected Response

{
"allowed": false,
"limit": 100,
"remaining": 0,
"retryAfterSeconds": 12
}

If the request is rejected at the API Gateway, the client should receive:

HTTP/1.1 429 Too Many Requests
Retry-After: 12
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0

Policy Creation Example

POST /api/v1/rate-limit/policies

{
"name": "standard-user-policy",
"scope": "USER",
"endpoint": "/api/orders",
"limit": 100,
"windowSeconds": 60,
"algorithm": "TOKEN_BUCKET"
}

8. Low Level Design

The Low-Level Design (LLD) defines the main classes used inside the Rate Limiter and how they work together to apply different rate-limiting algorithms.

Core Classes

The Rate Limiter API can be designed using the following core classes:

frame_3663
Rate Limiter API - UML Class Diagram
  • RateLimitRequest: Contains client ID, endpoint, request method, and timestamp.
  • RateLimitResult: Stores whether the request is allowed, remaining quota, and retry time.
  • RateLimiter: Main interface used to check whether a request should be allowed.
  • FixedWindowRateLimiter: Implements the Fixed Window algorithm.
  • SlidingWindowRateLimiter: Implements the Sliding Window algorithm.
  • TokenBucketRateLimiter: Implements the Token Bucket algorithm.
  • LeakyBucketRateLimiter: Implements the Leaky Bucket algorithm.

SOLID Principles

  • Single Responsibility Principle (SRP): Each limiter class handles only one rate-limiting algorithm.
  • Open/Closed Principle (OCP): New algorithms can be added without changing existing rate-limiter logic.
  • Liskov Substitution Principle (LSP): Any RateLimiter implementation can replace another through the common interface.
  • Interface Segregation Principle (ISP): Components depend only on the operations they actually need.
  • Dependency Inversion Principle (DIP): Rate-limiter logic depends on repository and policy interfaces instead of directly depending on Redis or a specific database.

Design Patterns

Design PatternUsage
StrategySwitch between Fixed Window, Sliding Window, Token Bucket, and Leaky Bucket
FactoryCreate the correct RateLimiter implementation based on policy configuration
RepositorySeparate Redis or database access from rate-limiting logic
Cache-AsideLoad rate-limit policies from cache first, then database if needed
SingletonReuse shared configuration or connection-management components where appropriate

9. Scalability & Performance

Scalability and performance are very important for a Rate Limiter because every incoming API request may need to pass through it. The system should handle very high traffic while adding only a few milliseconds of latency.

frame_3656
Rate Limiter API - Scalability Architecture
  • Horizontal Scaling: Run multiple Rate Limiter instances behind the API Gateway or Load Balancer.
  • Stateless Rate Limiter Nodes: Keep Rate Limiter servers stateless so any request can be handled by any instance.
  • Redis Cluster: Distribute counters and token-bucket state across multiple Redis nodes.
  • Sharding: Partition rate-limit data using User ID, API Key, IP address, or another consistent key.
  • Local Caching: Cache frequently used rate-limit policies inside each Rate Limiter node.
  • Atomic Redis Operations: Use Lua scripts or atomic commands to check and update counters in a single operation.
  • Connection Pooling: Reuse Redis and database connections to reduce network overhead.
  • Batching: Monitoring and usage events can be sent in batches instead of writing every event synchronously.
  • Asynchronous Logging: Send analytics and rejected-request logs through Kafka or another message queue.
  • Auto Scaling: Increase Rate Limiter instances based on request rate, CPU usage, or latency.
  • Multi-Region Deployment: Deploy Rate Limiter services close to users or API gateways to reduce network latency.
  • Policy Replication: Keep rate-limit configuration cached and replicated across regions.
  • Fail-Open / Fail-Closed Strategy: Define how the system should behave if Redis or the Rate Limiter becomes unavailable.
  • Fail-Open: Allow requests temporarily to maintain availability.
  • Fail-Closed: Reject requests when strict protection is more important.
  • TTL-Based Cleanup: Automatically expire old counters to reduce memory usage.
  • Hot-Key Protection: Distribute very high-traffic clients across multiple partitions or use local pre-allocation techniques when required.

10. Bottlenecks & Improvements

This section discusses the common problems a Rate Limiter API may face at scale and the techniques used to improve correctness, availability, and performance.

Common Bottlenecks

  • Redis Bottleneck: A very high number of counter updates can overload Redis.
  • Hot Keys: A single popular user, API key, or endpoint can generate extremely high traffic on one Redis key.
  • Network Latency: Remote calls between the API Gateway, Rate Limiter, and Redis can increase request latency.
  • Race Conditions: Multiple Rate Limiter nodes may update the same counter at the same time.
  • Clock Skew: Different servers may have slightly different timestamps, which can affect time-window calculations.
  • Memory Usage: Sliding-window algorithms may require storing more request history than simpler algorithms.
  • Redis Failure: If the central counter store becomes unavailable, rate-limit decisions may fail.
  • Configuration Propagation: Updated policies may not reach all Rate Limiter nodes immediately.
  • Cross-Region Consistency: Maintaining a strict global rate limit across multiple regions can be expensive.
  • Traffic Bursts: Sudden bursts can overwhelm backend services even if the average request rate is within the configured limit.

Possible Improvements

  • Redis Cluster: Distribute rate-limit state across multiple Redis nodes.
  • Atomic Operations: Use Redis Lua scripts or atomic commands to perform check-and-update safely.
  • Local Caching: Cache rate-limit policies and temporary state close to the Rate Limiter.
  • Token Bucket Algorithm: Allow controlled bursts while maintaining an average request rate.
  • Consistent Hashing: Distribute clients across Redis shards in a predictable way.
  • Hot-Key Protection: Split extremely busy keys or use local token allocation for high-traffic clients.
  • TTL-Based Cleanup: Automatically expire counters when their time window ends.
  • Circuit Breaker: Protect the Rate Limiter when Redis or another dependency becomes unhealthy.
  • Fail-Open / Fail-Closed Policy: Decide whether requests should be allowed or blocked when the Rate Limiter is unavailable.
  • Policy Versioning: Attach versions to rate-limit rules so configuration changes can be propagated safely.
  • Regional Rate Limits: Apply limits per region when strict global consistency is not required.
  • Monitoring & Alerting: Track rejected requests, Redis latency, hot keys, error rate, and rate-limit check latency.
  • Load Testing: Test the system with burst traffic and millions of requests to verify that limits remain accurate under high concurrency.
Comment

Explore