API Rate Limiting Design: Token Buckets, Quotas, and Backpressure

API Rate Limiting Design: Token Buckets, Quotas, and Backpressure

API security does not end with authentication and authorization. A reliable service must also control how frequently requests arrive, how much data they contain, and how expensive the requested operation may be. Without those controls, a single user, malfunctioning client, or automated attack can put disproportionate pressure on CPU, memory, database connections, third-party services, and cloud spending.

This is why rate limiting, quotas, and backpressure should be designed together. Rate limiting controls request speed over a short interval. A quota limits aggregate consumption over a longer period. Backpressure makes producers slow down, queue work, or stop submitting new work when downstream capacity is exhausted. These mechanisms are related, but they solve different problems.

Why rate limiting matters

Unlimited endpoint access is risky even when traditional network-layer DDoS protection is present. A report-generation request, file conversion, SMS delivery, search operation, or AI inference may look like one HTTP request while consuming substantial server-side resources. OWASP describes this class of weakness as unrestricted resource consumption and recommends limiting not only request frequency, but also payload size, batch size, execution time, pagination, and third-party spending.

HTTP provides the 429 Too Many Requests status code for situations in which a client has exceeded a rate policy. The response can explain the condition and may include Retry-After, telling the client how long to wait before trying again.

Define what is being limited

A common mistake is to apply one rule, such as “100 requests per minute,” to every endpoint. That treats a cheap read operation and an expensive external API call as equivalent. A stronger policy evaluates several dimensions:

  • Identity: IP address, account, API key, tenant, application, or device.
  • Scope: Endpoint, HTTP method, resource type, or entire service.
  • Cost: A simple lookup may consume one unit while a large export consumes many.
  • Time window: Short bursts, sustained rate, and daily or monthly totals.
  • Resource bounds: Request body, page size, upload size, concurrent jobs, and execution time.

IP-only policies can be unfair on mobile networks, corporate NAT, and shared office connections. For authenticated traffic, user, application, or tenant-based limits are usually more meaningful. IP limits still provide a useful additional layer for unauthenticated endpoints such as login, account recovery, and public search.

How the token bucket works

One of the most flexible algorithms is the token bucket. Tokens are added to a bucket at a configured rate, and the bucket has a maximum capacity. Each request consumes one or more tokens. If enough tokens exist, the request is accepted. Otherwise, it is rejected, delayed, or placed into a controlled queue.

This provides two useful properties at once: sustained traffic is constrained by the refill rate, while legitimate short bursts are allowed up to the bucket capacity. For example, a bucket that refills at 5 tokens per second and holds 20 tokens can maintain an average rate near 5 requests per second while allowing a short burst of up to 20 one-unit requests.

capacity = 20
refill_rate = 5 tokens/second
cost = 1 token per request

if tokens >= cost:
    tokens -= cost
    allow_request()
else:
    reject_with_429()

In a multi-instance service, keeping the bucket only in local process memory produces inconsistent decisions: different servers may grant the same client different allowances. A shared store such as Redis, an API gateway, or another distributed counter can provide a common view. That shared dependency introduces its own concerns, including network latency, availability, clock handling, and high write volume.

Fixed windows, sliding windows, and leaky buckets

A fixed-window counter is simple: allow a certain number of requests during each defined interval, such as 100 requests per 60 seconds. Its weakness is the boundary effect. A client may send many requests near the end of one window and many more immediately after the next window begins.

A sliding-window method evaluates recent history more continuously. It can use request logs, rolling counters, or approximations. The result is usually fairer around boundaries, but it requires more state or computation.

A leaky bucket places requests into a queue that drains at a controlled rate. It is useful when the goal is to smooth output rather than immediately reject every burst. The queue still needs a maximum size, and the service must define what happens when that size is reached.

Choose based on the workload, not on the name of the algorithm. Token buckets are suitable when short bursts are legitimate. Fixed windows can work for straightforward product quotas. Queue-based approaches are useful when work can be asynchronous and a stable processing rate is more important than immediate completion.

Separate rate limits from quotas

Rate limiting controls short-term speed. A quota controls aggregate consumption, such as a tenant’s daily requests, monthly data transfer, number of exports, or model-token usage. A client can remain below a per-second limit and still consume its entire daily allowance.

LayerExamplePurpose
Instantaneous rate10 requests/secondControl short traffic bursts
Short window300 requests/5 minutesReduce automation and abuse
Daily quota100,000 requests/dayControl aggregate resource use and cost
Concurrency20 active jobs per tenantProtect queues and workers

Sensitive business flows require endpoint-specific controls rather than a generic global limit. Password recovery, payment, reservation, comment creation, voting, and SMS verification can be abused even when overall service availability remains normal. OWASP identifies unrestricted access to sensitive business flows as a distinct risk because excessive use can cause business harm without creating a conventional technical outage.

Design useful 429 responses

When a limit is exceeded, return a consistent, machine-readable response:

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 8

{
  "type": "rate_limit_exceeded",
  "message": "Request rate exceeded",
  "retry_after_seconds": 8
}

Retry-After can express a delay in seconds or an HTTP date. Clients should use exponential backoff with jitter when retrying. Jitter prevents thousands of clients that received the same failure from retrying at the exact same instant and creating another traffic spike.

Clients must not blindly retry side-effecting operations. Payment, order creation, and account changes should use idempotency keys or an equivalent mechanism so that a retry does not perform the same business action twice.

Backpressure extends beyond HTTP

If an accepted request creates a job in a queue, the HTTP rate limiter is only the first control. Queue length, worker concurrency, database connection pools, and the rate accepted by downstream services must also be bounded. When a queue is full, the system may reject low-priority work, delay acceptance, or return a response instructing the client to try later.

For long-running operations, an asynchronous design is often safer. The API can accept a bounded number of jobs, return a job identifier, and let workers process tasks with controlled concurrency. The client can poll for status or receive a notification when the result is ready. This avoids holding HTTP connections open and makes capacity visible in queue metrics.

Observability and testing

Do not evaluate a limiter using only the number of 429 responses. Track:

  • Rate-limit rejection percentage and distribution by identity
  • Latency, error rate, and queue wait time per endpoint
  • Counter-store or gateway latency
  • CPU, memory, bandwidth, and external-service cost by tenant
  • False-positive blocking of legitimate users

Testing should cover more than a single client increasing its request speed. Exercise multiple application instances, window boundaries, shared-counter failure, network delay, clock differences, queue saturation, and sudden traffic bursts. If the limit store is unavailable, a fail-open policy may preserve availability but increase abuse risk. A fail-closed policy strengthens protection but can block legitimate traffic. The right choice depends on endpoint criticality and threat model.

A practical starting policy

  1. Classify endpoints by business and technical cost.
  2. Separate pre-authentication and authenticated limits.
  3. Use a token bucket for short-term rate and separate counters for longer-term quotas.
  4. Bound payload size, page size, execution time, concurrent jobs, and batch operations.
  5. Standardize 429 responses and Retry-After behavior.
  6. Implement jittered retries and idempotency on clients.
  7. Review limits using real metrics and adjust them gradually.

Rate limiting is not merely a blocking mechanism. It is a capacity-allocation system that helps ensure one caller cannot consume a disproportionate share of a service. Token buckets handle bursts, quotas control long-term consumption, and backpressure prevents queues and dependencies from growing without bound. Designed together, they make APIs more predictable, resilient, and financially safer.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published