Rate Limiter
Cap how many requests each client may make in a period, so no single caller can exhaust shared capacity or run up costs.
On this page
Problem
Every service has finite capacity, and its clients do not coordinate. One misbehaving integration in a retry loop, a scraper, a buggy mobile release or a credential-stuffing attack can send more traffic than the rest of the user base combined. Without limits, that one caller degrades the service for everyone, and the autoscaler dutifully adds capacity to serve the abuse.
Some resources are expensive per call: an LLM request, an SMS, a password-hash check, a report export. Unbounded access turns them into a cost and security risk even when the system could technically handle the load.
Context
Use this pattern when:
- Requests can be attributed to a client identity: API key, user id, tenant, or IP address as a last resort.
- Fairness matters: one client should not degrade service for others.
- Some endpoints are far more expensive or sensitive than others (login, search, exports).
- The service runs on several instances, so limits may need shared state to be accurate.
Solution
Assign each request to a partition key (for example the API key) and check it against a limiting algorithm before doing any work. If the client is over its limit, reject immediately with 429 Too Many Requests and a Retry-After header, so well-behaved clients know when to come back.
The token bucket is the most common algorithm: each client has a bucket holding up to N tokens, refilled at a steady rate R. Each request takes a token; an empty bucket means rejection. It allows short bursts up to N while enforcing an average of R per second. Fixed windows are simpler but allow double bursts at window edges; sliding-window logs are exact but store a timestamp per request; sliding-window counters approximate them cheaply.
With several instances, either keep limits local (each of K instances allows limit / K, which is approximate but needs no coordination) or keep counters in a shared store such as Redis, updated atomically with a Lua script or an atomic increment with expiry.
How it works, step by step
- 1Identify the client and the policy that applies (per key, per tenant, per endpoint).
- 2Refill the client's bucket based on time elapsed since the last request, capped at capacity.
- 3If at least one token is available, take it and let the request through.
- 4Otherwise reject with 429, a Retry-After value and optionally rate-limit headers describing the quota.
- 5Emit metrics on rejections per client so abuse and mis-sized limits are visible.
Implementation
ASP.NET Core ships rate limiting middleware built on System.Threading.RateLimiting. The TypeScript example implements a token bucket directly, which is also the core of most distributed implementations.
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy("per-api-key", httpContext =>
{
var key = httpContext.Request.Headers["X-Api-Key"].ToString();
var partition = string.IsNullOrEmpty(key)
? "anon:" + httpContext.Connection.RemoteIpAddress
: "key:" + key;
return RateLimitPartition.GetTokenBucketLimiter(partition, _ => new TokenBucketRateLimiterOptions
{
TokenLimit = 20, // burst size
TokensPerPeriod = 10, // sustained 10 req/s
ReplenishmentPeriod = TimeSpan.FromSeconds(1),
QueueLimit = 0, // reject, don't queue
AutoReplenishment = true,
});
});
options.OnRejected = (context, _) =>
{
context.HttpContext.Response.Headers.RetryAfter = "1";
return ValueTask.CompletedTask;
};
});
var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/api/orders", () => Results.Ok(Array.Empty<object>()))
.RequireRateLimiting("per-api-key");
app.Run();These limiters are in-process, so with K instances behind a load balancer the effective limit is roughly K times the configured one. Divide the limit by the instance count or use a shared store when accuracy matters.
type Bucket = { tokens: number; updatedAt: number };
export class TokenBucketLimiter {
private readonly buckets = new Map<string, Bucket>();
constructor(
private readonly capacity: number,
private readonly refillPerSecond: number,
) {}
/** Returns 0 if allowed, otherwise the milliseconds until a token is available. */
take(key: string, now = Date.now()): number {
const bucket = this.buckets.get(key) ?? { tokens: this.capacity, updatedAt: now };
// Refill lazily for the time elapsed since the last request.
const elapsedSeconds = (now - bucket.updatedAt) / 1000;
bucket.tokens = Math.min(this.capacity, bucket.tokens + elapsedSeconds * this.refillPerSecond);
bucket.updatedAt = now;
this.buckets.set(key, bucket);
if (bucket.tokens >= 1) {
bucket.tokens -= 1;
return 0;
}
return Math.ceil(((1 - bucket.tokens) / this.refillPerSecond) * 1000);
}
}
// Usage in a minimal Node HTTP handler.
const limiter = new TokenBucketLimiter(20, 10);
export function handle(apiKey: string): { status: number; headers: Record<string, string> } {
const waitMs = limiter.take(apiKey);
if (waitMs > 0) {
return { status: 429, headers: { 'Retry-After': String(Math.ceil(waitMs / 1000)) } };
}
return { status: 200, headers: {} };
}For a fleet of instances, keep the same two fields (tokens, updatedAt) in Redis and run the refill-and-take step atomically in a Lua script, so concurrent requests cannot both spend the last token.
In production
- Rate limit by the most specific trustworthy identity: API key or user id beats IP address, which is shared behind NATs and trivially rotated by attackers.
- Apply stricter limits to expensive or sensitive endpoints such as login, password reset and exports.
- Return
Retry-After, and consider the IETFRateLimitheaders, so clients can back off precisely instead of guessing. - Decide what happens when the shared store is unavailable: failing open keeps the service up, failing closed protects downstream resources.
- Put coarse limits at the edge (CDN, API gateway) and fine-grained, business-aware limits in the service.
Trade-offs
Benefits
- Protects capacity and keeps latency stable for well-behaved clients when one client misbehaves.
- Caps the cost of expensive operations and slows brute-force attacks.
- Makes usage tiers enforceable (free versus paid quotas).
- Rejections are cheap, so the service sheds abusive load before doing real work.
Costs
- Legitimate bursts can be rejected if limits are tuned too tightly.
- Distributed limits need a shared store, adding latency to every request and a new dependency.
- Local limits are approximate and drift as instances scale in and out.
- Choosing the right key is hard: IP-based limits punish users behind shared NAT, key-based limits need authentication first.
Alternatives
- Load shedding
- Reject work based on the server's own load (queue depth, CPU) instead of per-client counts. Protects the service but not fairness between clients.
- Concurrency limits
- Limit simultaneous in-flight requests rather than requests per second; better when request cost varies widely.
- Queueing with backpressure
- Accept work into a bounded queue and process it at a steady rate; suitable for asynchronous jobs where waiting is acceptable.
Anti-patterns
- Rejecting without Retry-After
- Clients that do not know when to return retry immediately, which turns a rate limit into a retry storm.
- Limiting only by IP address
- Penalises offices and mobile carriers sharing one address while attackers rotate addresses at will.
- Counting after doing the work
- Checking the limit after the expensive part has run protects nothing; check before any significant processing.
- A single global limit
- One shared bucket for all clients lets the noisiest client consume the whole allowance.
Related lessons
Interview questions
Compare the token bucket and fixed window algorithms.
A fixed window counts requests per calendar interval and resets at the boundary, so a client can send a full quota at the end of one window and another at the start of the next. A token bucket refills continuously and caps bursts at its capacity, giving a smooth average rate with controlled bursts.
How would you implement a rate limiter shared by 20 API servers?
Store per-client state in Redis and perform the read-refill-decrement step atomically with a Lua script, keyed by client id with an expiry. To avoid a Redis round trip on every request, some systems allow small local allowances and sync periodically, trading exactness for latency.
What should the client receive when it is rate limited?
A 429 Too Many Requests status with a Retry-After header and ideally headers describing the limit, remaining quota and reset time. That lets clients back off precisely instead of retrying blindly.
Should the limiter fail open or closed when Redis is down?
It depends on what the limit protects. For general API fairness, failing open keeps the product available and a local fallback limit can cap the worst case. For limits that guard money or security, such as SMS sends or login attempts, failing closed is safer.