Rate limiting vs throttling, the four common limiter algorithms (fixed window, sliding window, token bucket, concurrency), their burst behaviour, and signalling limits with 429 and Retry-After.
Rate limiting caps how many requests a client may make in a period and rejects the excess; throttling usually means slowing or queueing the excess instead of failing it. The common algorithms are: fixed window (N requests per minute, simple but allows a 2N burst across a window boundary), sliding window (the window is split into segments so the boundary burst is smoothed), token bucket (tokens refill at a steady rate, the bucket size is the allowed burst) and a concurrency limiter (caps requests in flight, not per second). A good API returns 429 Too Many Requests with Retry-After so clients back off instead of hammering. The trade-off is precision versus cost: exact, distributed limits need shared state; per-instance in-memory limits are cheap but approximate.
"Rate limiting and throttling both protect an API from more traffic than it should accept, but they react differently. Rate limiting is a hard policy: client X gets 100 requests a minute and request 101 is rejected with 429 Too Many Requests. Throttling is softer: the excess is queued, slowed or moved to a degraded path. In ASP.NET Core the same middleware does both, because every limiter has a
QueueLimit: zero means reject straight away, a positive value means wait for a permit.The algorithm decides what shape of traffic you allow. A fixed window counter resets every minute, which is cheap but lets a client send 100 requests at 12:00:59 and another 100 at 12:01:00. A sliding window splits the minute into segments and carries the count forward, so that boundary burst mostly disappears. A token bucket is what I reach for on partner APIs: the bucket size is the burst you tolerate and the refill rate is the sustained rate, so a client can send 20 at once but averages 5 a second. A concurrency limiter is different again: it caps how many requests are in progress, which protects a slow dependency such as a reporting query much better than a per-second limit.
The mistake I see is returning 503 or a bare 400 when a limit is hit, with no hint when to try again. Clients then retry in a tight loop and make it worse. Always send 429 with
Retry-After, and document the limits. A rate limit is part of the API contract, not just a defence."
| Rate limiting | Throttling | |
|---|---|---|
| Excess requests | Rejected (429) | Delayed, queued or degraded |
| Client experience | Fast failure, must retry later | Slower responses |
| Server cost | Very low per rejection | Holds connections and memory while queued |
| Typical use | Public and partner API quotas, abuse protection | Smoothing bursts, fair sharing of a slow resource |
| Algorithm | State per key | Allows bursts? | Weakness |
|---|---|---|---|
| Fixed window | One counter + window start | Up to 2N at a boundary | Boundary burst |
| Sliding window | One counter per segment | Smoothed | More memory, still approximate |
| Token bucket | Token count + last refill | Yes, up to bucket size | Two numbers to tune |
| Concurrency | In-flight count | N/A (caps parallelism) | Doesn't limit request rate for fast calls |
X-RateLimit-Limit/Remaining/Reset. The IETF RateLimit and RateLimit-Policy fields are still an Internet-Draft (draft -11, May 2026), so treat them as emerging, not standard.On a partner pricing API, switching from a 600-per-minute fixed window to a token bucket (bucket 50, 10 tokens a second) cut 429s for well-behaved partners by roughly 80%, because their batch jobs could burst briefly, while one misbehaving client was still held to about 10 requests a second.
Checks that the candidate understands limiter algorithms as traffic shapes and treats limits as part of the HTTP contract.
Green flags
Red flags
An API has finite capacity: threads, database connections, downstream quotas, money (cloud egress, third-party per-call fees). Without limits, one client's bug (a retry loop, a cron job started on 200 servers) consumes capacity meant for everyone. Limits give fairness between clients, protection for dependencies and a commercial lever (free tier 1,000/day, paid tier 100,000/day).
window 12:00-12:01 [count=100 -> reject]
window 12:01-12:02 [count reset to 0]
12:00:59 ---- 100 requests ----|---- 100 requests ---- 12:01:00
boundary: 200 in 2 seconds
One integer per key, incremented atomically (INCR + EXPIRE in Redis). The boundary problem is the cost of that simplicity.
A segment is a fixed slice of time inside the window. With a 60 s window and SegmentsPerWindow = 6, each segment is 10 s long and has its own counter. The limiter allows a request if the sum of the last six segment counters is below N; every 10 s the oldest segment drops out and its count is returned to the available permits.
window = 60 s, 6 segments of 10 s
[ 12 | 30 | 8 | 20 | 15 | 10 ] sum = 95 of 100
^ oldest: expires next tick, its 12 permits come back
A boundary burst can now reach only about N + N/6. Memory: one integer per segment per key, so 6 counters instead of 1; with 100,000 active keys that is 600,000 counters instead of 100,000, still small (a few MB). More segments give smoother limits for more memory and more timer work. An exact sliding log (store every request timestamp) is precise but costs memory proportional to the limit: a 1,000-per-minute limit stores up to 1,000 timestamps per key.
refill: R tokens every period
|
+-----v-----+
| bucket | capacity B (max burst)
| o o o o |
+-----+-----+
| each request takes 1 token
v
allowed, or rejected/queued if empty
Sustained rate = R per period, burst = B. This matches real client behaviour (bursty batch jobs) better than windows. A leaky bucket is the queueing variant: requests drain at a fixed rate, which is classic throttling.
Counts permits held by in-flight requests and releases them when the request finishes. It protects against slow requests piling up (a 30 s report query) where a per-second limit would let thousands of them overlap. It is the bulkhead pattern applied at the API edge.
System.Threading.RateLimiting (since .NET 7) provides FixedWindowRateLimiter, SlidingWindowRateLimiter, TokenBucketRateLimiter and ConcurrencyLimiter, all deriving from RateLimiter. You call AttemptAcquire or AcquireAsync and get a RateLimitLease; lease.IsAcquired says whether you may proceed, and TryGetMetadata(MetadataName.RetryAfter, ...) gives a retry hint. PartitionedRateLimiter<TResource> keeps one limiter per partition key. ASP.NET Core's rate limiting middleware wraps all of this, and Microsoft.Extensions.Http.Resilience uses the same limiters on the client side.
client -> CDN/WAF -> API gateway (APIM) -> app instance (middleware) -> dependency
IP floods per-subscription per-user, per-endpoint concurrency
Coarse limits belong at the edge (Azure Front Door WAF rules, API Management rate-limit-by-key / quota-by-key); fine-grained, business-aware limits in the app. IP-based limits at the edge should be generous, because NAT puts many legitimate users behind one address.
X-RateLimit-* headers are a de facto convention, not a standard. The IETF httpapi working group's RateLimit and RateLimit-Policy fields were at draft -11 (May 2026) and not yet an RFC when this was written (November 2026); check the IETF Datatracker for the current status before you commit to the format.
FixedWindowRateLimiter (10 per second) and fires 25 AttemptAcquire calls straddling a window boundary; count how many succeed within one second.SlidingWindowRateLimiter (6 segments) and TokenBucketRateLimiter and compare.QueueLimit = 5 and observe requests waiting instead of failing.curl -i against a rate-limited endpoint and check the status and Retry-After header.k6 or bombardier at twice the limit and graph 429s per second.Comparing limiter shapes directly with System.Threading.RateLimiting (no ASP.NET Core needed):
using System.Threading.RateLimiting;
namespace RateLimitDemo;
public static class Program
{
public static async Task Main()
{
// Token bucket: burst of 20, then 5 tokens per second sustained.
using var bucket = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions
{
TokenLimit = 20,
TokensPerPeriod = 5,
ReplenishmentPeriod = TimeSpan.FromSeconds(1),
QueueLimit = 0, // 0 = reject (rate limiting); > 0 = wait (throttling)
AutoReplenishment = true
});
var allowed = 0;
for (var i = 0; i < 30; i++)
{
using RateLimitLease lease = bucket.AttemptAcquire();
if (lease.IsAcquired)
{
allowed++;
}
else if (lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
{
// This is the value you would put in the Retry-After header.
Console.WriteLine($"Rejected, retry after {retryAfter.TotalSeconds:N1}s");
}
}
Console.WriteLine($"Allowed {allowed} of 30 in the first burst"); // 20
// Concurrency limiter: at most 2 in flight, others wait in a queue of 10.
using var concurrency = new ConcurrencyLimiter(new ConcurrencyLimiterOptions
{
PermitLimit = 2,
QueueLimit = 10,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst
});
var work = Enumerable.Range(1, 5).Select(async n =>
{
using RateLimitLease lease = await concurrency.AcquireAsync();
Console.WriteLine($"Job {n} running");
await Task.Delay(500);
});
await Task.WhenAll(work);
}
}
What a client should see when it hits the limit:
HTTP/1.1 429 Too Many Requests
Retry-After: 2
Content-Type: application/problem+json
{"type":"https://api.example.com.au/problems/rate-limit","title":"Too many requests","status":429,"detail":"Limit of 5 requests per second for this API key exceeded."}
QueueLimit accordingly.Retry-After.UseForwardedHeaders and known proxies, and a generous limit.Rate limits are a product decision as much as a technical one: they encode who gets how much capacity. I start by asking what we are protecting (a database, a third-party quota, cost, fairness between tenants) because that decides the algorithm and the key. A per-tenant token bucket protects fairness; a global concurrency limiter protects a database. Most real systems layer two or three: a coarse edge limit against floods, a per-key quota for fairness, and a concurrency cap in front of an expensive endpoint.
Precision costs money. An exact global limit across 10 instances needs shared state (Redis, API Management), which adds latency and a new failure mode; I usually accept approximate per-instance limits (limit / instance count) unless the limit is contractual or billed.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Fixed window | Simple quotas, internal APIs | Lowest | Burst-sensitive dependencies |
| Sliding window | Public APIs needing smoother limits | Slightly more memory | Very high-cardinality keys in memory |
| Token bucket | Partner APIs with bursty batch clients | Two parameters to tune | When you need hard per-period quotas for billing |
| Concurrency | Slow endpoints, fragile dependencies | Needs latency knowledge to size | Fast endpoints where request rate is the issue |
A bulkhead partitions shared resources so one failing dependency can only exhaust its own share, like the watertight compartments in a ship. In .NET the shared resources are thread-pool threads, sockets, database connection-pool slots, memory and request slots.
AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.AddRateLimiter concurrency policies per endpoint group.MaxConcurrentCalls.A bulkhead limits concurrent work. Rate limiting limits requests per time window. Size limits with Little's Law (concurrency = rate x latency) plus headroom, and pair them with timeouts. The trade-off is containment against rejecting work when a compartment is full.
The built-in middleware keeps counters in each process, so 10 instances allow roughly 10x the limit. Options: divide the limit by the instance count (cheap, approximate, and wrong as soon as autoscaling changes the count); enforce at a shared edge such as Azure API Management rate-limit-by-key / quota-by-key; or use a Redis-backed limiter (sliding window or token bucket in an atomic Lua script) for exact limits, at the cost of a network hop per request. Decide up front what happens when Redis is unreachable: fail open with a per-instance local limiter as a fallback, or fail closed for abuse-sensitive endpoints such as login.
Last updated 23 Nov 2026.