📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between rate limiting and throttling for an HTTP API? Explain the fixed window, sliding window, token bucket and concurrency limiter algorithms, what each one allows and prevents, and how a well-behaved API tells a client it has hit a limit (429 Too Many Requests, Retry-After).

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.

Intermediate Theory Intermediate aspnet-core http-429 rate-limiting throttling token-bucket web-api

🎯 Key points

  • Rate limiting rejects over-limit requests; throttling delays or degrades them (queue, slower tier)
  • Fixed window: N per window, cheap, allows up to 2N at a window boundary
  • Sliding window: window split into time segments, smooths the boundary burst for one counter per segment
  • Token bucket: bucket size = allowed burst, refill rate = sustained rate
  • Concurrency limiter caps in-flight requests, not requests per second
  • 429 Too Many Requests plus Retry-After (seconds or HTTP date); 503 is for server overload
  • Partition by API key, user or tenant; IP partitions lump NAT and mobile-carrier users together
  • IETF RateLimit / RateLimit-Policy fields: Internet-Draft -11 (May 2026), not yet an RFC

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 vs throttling

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

The algorithms

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

Telling the client

  • 429 Too Many Requests (RFC 6585) for a client exceeding its limit; 503 Service Unavailable when the server is overloaded regardless of who is calling.
  • Retry-After: delay in seconds or an HTTP date (RFC 9110).
  • Optional quota headers: many APIs send 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.
  • A ProblemDetails body (RFC 9457) explaining which limit was hit.

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands limiter algorithms as traffic shapes and treats limits as part of the HTTP contract.

Green flags

  • Explains the fixed-window boundary burst and how sliding windows and token buckets address it
  • Distinguishes per-second limits from concurrency limits
  • Returns 429 with Retry-After and mentions documenting limits
  • Talks about the partition key (API key, user, tenant) and NAT/proxy pitfalls
  • Mentions per-instance vs distributed limits

Red flags

  • Thinks 503 or 400 is the right status for quota exhaustion
  • Can only describe "count requests per minute"
  • No idea what clients should do when limited

📚 Learn in depth

1. Why limit at all

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).

2. Fixed window

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.

3. Sliding window

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.

4. Token bucket

        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.

5. Concurrency limiter

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.

6. How .NET implements them

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.

7. Where to enforce

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.

8. Quota headers

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.

Try it yourself

  1. Write a console app that creates a FixedWindowRateLimiter (10 per second) and fires 25 AttemptAcquire calls straddling a window boundary; count how many succeed within one second.
  2. Repeat with SlidingWindowRateLimiter (6 segments) and TokenBucketRateLimiter and compare.
  3. Add QueueLimit = 5 and observe requests waiting instead of failing.
  4. Use curl -i against a rate-limited endpoint and check the status and Retry-After header.
  5. Load test with k6 or bombardier at twice the limit and graph 429s per second.

💻 Code

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."}

⚠ Common mistakes

  • Mistake: Using "rate limiting" and "throttling" as if they always mean the same thing. Why it is wrong: rejecting and delaying have very different client and server costs. Instead: say which behaviour you want and set QueueLimit accordingly.
  • Mistake: Returning 503 or 400 when a client exceeds its quota. Why it is wrong: 503 says the server is unhealthy and 400 says the request is malformed; clients and monitoring misread both. Instead: return 429 with Retry-After.
  • Mistake: Choosing a fixed window for a partner API and being surprised by double bursts. Why it is wrong: fixed windows allow up to 2N across a boundary. Instead: use a sliding window or token bucket when bursts matter.
  • Mistake: Using a per-second limit to protect a slow dependency. Why it is wrong: 10 requests a second that each take 30 s means 300 in flight. Instead: add a concurrency limiter.
  • Mistake: Partitioning only by client IP. Why it is wrong: NAT (corporate networks, mobile carriers using carrier-grade NAT, school and university Wi-Fi) puts hundreds or thousands of users behind one public IP, so one heavy user gets everyone behind that address rejected; behind a reverse proxy without forwarded headers every request shows the proxy's IP and the whole API shares one bucket. Instead: partition by API key, user or tenant; use IP only for anonymous endpoints, with UseForwardedHeaders and known proxies, and a generous limit.
  • Mistake: Large queues to "be nice". Why it is wrong: every queued request keeps its Kestrel connection, request buffers and any memory already allocated, while the client's own timeout keeps running; under sustained overload the queue never drains, latency climbs to the queue length times service time, clients time out and retry, and the server ends up doing work for callers who have already gone. Instead: keep queues short (a few requests, or zero), fail fast with 429 and let clients back off.
  • Mistake: Not documenting limits. Why it is wrong: clients discover them in production. Instead: publish them in the API docs and response headers.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions a concurrency limiter protecting a slow dependency Why: Checks whether they can connect API-edge concurrency limits to the bulkhead pattern
    How to answer

    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.

    • Outbound: a concurrency limiter per dependency. Use Polly's AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.
    • Inbound: ASP.NET Core AddRateLimiter concurrency policies per endpoint group.
    • Messaging: separate queues and consumers with their own 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.

  2. When: Candidate says the built-in limiter is in-memory Why: Checks distributed-state trade-offs: Redis, API Management, approximate per-instance limits
    How to answer

    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.

↩ Usually asked after

More in API Reliability

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me