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

๐Ÿ“š Interview question

Design a rate limiter for a public API used by thousands of partner API keys. Each plan has its own limits, the API runs on many instances in more than one region, and partners need to know when they can retry. Walk me through the algorithm, where the limiter sits, the shared state, and what happens when that state is unavailable.

A full distributed rate limiter design: requirements and plans, algorithm choice (token bucket vs sliding window), placement (edge, gateway, in-app), shared state in Redis with atomic Lua scripts, per-key and per-region limits, 429 with Retry-After, fail-open vs fail-closed, and the .NET 10 rate limiting middleware.

Mid-Level SystemDesign Intermediate api-management aspnet-core rate-limiting redis system-design token-bucket

๐ŸŽฏ Key points

  • Clarify: limit per API key and plan, burst allowance, global vs per-region, which endpoints
  • Token bucket for bursts with an average rate; sliding window counter for strict quotas; cost-weighted tokens for expensive endpoints
  • Layers: Front Door WAF per IP; API Management rate-limit-by-key at the gateway (its own counters, not shared with the app); in-app limits per tenant/endpoint
  • Shared state in Redis; refill and take atomically in a Lua script using Redis TIME, one round trip, key expiry cleans idle buckets
  • Estimate: 50k req/s peak → 50k Redis script calls/s → shard Redis by key; split hot keys across sub-buckets
  • 429 Too Many Requests with Retry-After and RateLimit headers; reject rather than queue so the backend is shed, not delayed
  • Fail open with a local in-memory limiter (limit ÷ instances) when Redis is down; fail closed only for costly endpoints
  • .NET 10: AddRateLimiter, PartitionedRateLimiter, TokenBucketRateLimiter (per process)

โฑ 30-second answer

A rate limiter protects the service and enforces fairness between customers. I'd use a token bucket per API key: capacity = burst, refill rate = plan limit. It allows short bursts but caps the average. Limits sit in layers: per IP at the edge (Front Door WAF), per API key at the gateway or in the API, and per endpoint for expensive operations. With many instances, the bucket lives in Redis, updated by an atomic Lua script in one round trip, sharded by key. Rejections return 429 with Retry-After. When Redis is unavailable I fail open to a local in-memory limiter with the limit divided by instance count, because rejecting all paying traffic is worse than briefly over-admitting. The trade-off is accuracy versus latency and availability: an exact global limit costs a network hop on every request.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"First I'd clarify what we're protecting and from whom. Here it's fairness between [thousands of] partner API keys, each on a plan, say Free at 10 requests a second and Enterprise at 500, plus protecting the backend from overload. I'd ask whether the limit is global or per region, whether bursts are allowed, and whether a few percent over the limit is acceptable. Usually it is, which matters a lot for the design.

Then numbers: say 50,000 requests a second at peak across 30 instances and two regions, with 2 million keys of which maybe 50,000 are active in any minute. If every request does one Redis call, that's 50,000 operations a second. Redis handles that, but a Lua script per request is heavier than a GET, so I'd use a clustered Redis sharded by key. Memory is tiny: 50,000 active buckets at 100 bytes is 5 MB.

For the algorithm I pick a token bucket: each key has capacity for its burst and refills at its plan rate. The check is one Lua script that refills based on elapsed time, takes a token if there is one, and returns the remaining tokens and wait time, atomically, so two instances can't both spend the last token. Placement is layered: Front Door WAF rate rules per IP to absorb floods cheaply, then per-key limits in API Management with rate-limit-by-key, or in ASP.NET Core with a PartitionedRateLimiter if we don't have a gateway. Rejected requests get 429 with Retry-After so well-behaved clients back off.

The mistake I see is using the built-in ASP.NET Core limiter alone on 30 instances: it's per process, so a partner effectively gets 30 times their limit, unevenly. And deciding failure behaviour too late. If Redis goes away I fail open to a local limiter at limit รท instances. A rate limiter that takes the API down is worse than no rate limiter."


Requirements

Type Requirement Assumption
Functional Limit per API key by plan (e.g. 10, 100, 500 req/s) Plans change rarely; cache plan lookups
Functional Stricter limit on costly endpoints (exports, search) Concurrency limit, not rate
Functional Clients learn limits and retry time 429, Retry-After, RateLimit-* headers
Non-functional Adds < 2 ms p99 One Redis round trip in-region
Non-functional ~5% over-admission acceptable Allows per-region buckets and local fallback
Non-functional Limiter failure must not take the API down Fail open by default

Capacity estimate

Quantity Arithmetic Result
Peak requests given 50,000/s
Redis script calls 1 per request 50,000/s (โ‰ˆ 25k per region)
Active buckets per minute assumption 50,000
Memory 50,000 ร— ~100 B โ‰ˆ 5 MB
Added latency in-region Redis RTT ~0.5โ€“1 ms

Where the limiter sits

Client โ”€โ”€โ–บ Front Door WAF (per-IP rate rule: floods, scrapers)
             โ”‚
             โ–ผ
        API Management (rate-limit-by-key / quota-by-key on subscription or API key)
             โ”‚
             โ–ผ
        ASP.NET Core API (per-tenant + per-endpoint limits, concurrency limits on exports)
             โ”‚
             โ–ผ
        Azure Managed Redis (token buckets, Lua script, keyed rl:{apiKey})

Algorithm comparison

Algorithm Behaviour Good for Weakness
Fixed window Count per minute bucket Simple quotas 2ร— burst at window edges
Sliding window log Store each timestamp Exact Memory per request
Sliding window counter Weighted current + previous window Strict per-minute quotas Approximate
Token bucket Refill rate + capacity APIs with bursts Two parameters to explain
Concurrency limiter Max in-flight Expensive endpoints Not a rate

Production example

For a partner API at [40,000] req/s across two Australian regions, per-region token buckets in Redis added about 0.8 ms p99. During a 4-minute Redis failover the API fell back to local limiters; over-admission peaked at about 7% and no partner saw errors, whereas the previous fail-closed design had returned 429 to everyone.

๐Ÿ” What the interviewer is checking

Checks that the candidate can design a correct distributed limiter and reason about where it lives and how it fails.

Green flags

  • Chooses an algorithm and explains burst behaviour
  • Makes the shared check atomic (Lua script) and handles clock skew
  • Layers edge, gateway and app limits with different keys
  • Decides fail-open vs fail-closed explicitly and returns 429 + Retry-After

Red flags

  • In-memory counters on each instance presented as a global limit
  • Read-modify-write races
  • The limiter is a new single point of failure
  • No mention of telling clients when to retry

๐Ÿ“š Learn in depth

1. Token bucket from first principles

A bucket holds up to capacity tokens and gains rate tokens per second. A request costs one token (or more for expensive calls). You don't need a timer: store tokens and lastRefill, and on each request compute

now      = server time
tokens   = min(capacity, tokens + (now - lastRefill) ร— rate)
allowed  = tokens >= cost
if allowed: tokens -= cost
retryAfter = allowed ? 0 : (cost - tokens) / rate

A plan of "100 req/s, burst 200" is rate = 100, capacity = 200.

2. Why atomicity matters

With GET-then-SET from two instances:

Instance A: GET tokens โ†’ 1        Instance B: GET tokens โ†’ 1
Instance A: SET tokens = 0        Instance B: SET tokens = 0   โ† both admitted

A Lua script runs atomically on the Redis shard that owns the key, so read-modify-write happens without interleaving, and it is one network round trip. Use the Redis server time (TIME) inside the script, or pass a single clock source, so instance clock skew doesn't mint tokens. Keep each key's data in one hash slot (rl:{apiKey}) so Redis Cluster can run the script.

3. Global vs per-region

A truly global limit across Australia East and Southeast needs cross-region Redis calls (~10โ€“15 ms) or active geo-replication, which is eventually consistent anyway. The usual compromise is per-region buckets with the limit split by traffic share, or the full limit per region when ~2ร— over-admission during a failover is acceptable. State the choice explicitly.

4. Built-in options in .NET 10 and Azure

  • Microsoft.AspNetCore.RateLimiting middleware: AddRateLimiter, policies with AddTokenBucketLimiter, AddSlidingWindowLimiter, AddConcurrencyLimiter, and PartitionedRateLimiter.Create to partition by API key. State is in process, so it's per instance.
  • System.Threading.RateLimiting lets you write a custom RateLimiter (e.g. backed by Redis) and plug it into the same middleware.
  • API Management: rate-limit-by-key (short window, per gateway) and quota-by-key (longer quotas). Check the current docs for how counters are shared in multi-region deployments; they are not guaranteed to be exact globally.
  • Front Door WAF custom rate-limit rules per client IP or other match conditions, evaluated at the edge.

5. Telling the client

429 Too Many Requests with Retry-After: <seconds>. Many APIs also send RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset (or the newer combined RateLimit / RateLimit-Policy fields from the IETF draft). Document them so SDKs back off with jitter instead of hammering.

6. Failure modes

  • Redis down or slow: time out the check at ~5 ms and fall back to a local TokenBucketRateLimiter at limit รท instance count. Log and alert.
  • Hot key: one huge partner on one shard. Shard their bucket (rl:{key}:0..n) with limit รท n each, or give them a dedicated limit layer.
  • Retry storms: clients ignoring Retry-After. Count rejections per key; escalate to WAF blocks for abusive keys.
  • Plan lookup on every request: cache plans in memory with a short TTL.

7. AWS mapping

CloudFront + AWS WAF rate-based rules, API Gateway usage plans with throttling per API key, ElastiCache for Redis for custom limits.

Try it yourself

  1. Register the ASP.NET Core token bucket limiter below and hit it with bombardier -c 50 -n 2000; confirm the 429 count matches the maths.
  2. Run two instances and show a key gets twice its limit; then switch to the Redis limiter.
  3. Write the Lua script, call it with ScriptEvaluateAsync, and test two concurrent callers never both take the last token.
  4. Stop Redis mid-test and confirm the fallback keeps serving.
  5. Measure added latency with dotnet-counters and Application Insights dependency timings.

๐Ÿ’ป Code

Per-key token buckets with the built-in middleware (per instance), plus the atomic Redis script for a shared limit.

// Program.cs: built-in limiter, partitioned by API key. Per process only.
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(http =>
    {
        var apiKey = http.Request.Headers["X-Api-Key"].ToString();
        var perSecond = PlanLookup.RequestsPerSecond(apiKey); // cached plan lookup
        return RateLimitPartition.GetTokenBucketLimiter(apiKey, _ => new TokenBucketRateLimiterOptions
        {
            TokenLimit = perSecond * 2,              // burst capacity
            TokensPerPeriod = perSecond,             // refill rate
            ReplenishmentPeriod = TimeSpan.FromSeconds(1),
            QueueLimit = 0,                          // reject, don't queue: clients retry
            AutoReplenishment = true
        });
    });
    options.OnRejected = (ctx, _) =>
    {
        if (ctx.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
            ctx.HttpContext.Response.Headers.RetryAfter = ((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString();
        return ValueTask.CompletedTask;
    };
});

var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/api/orders", () => Results.Ok());
app.Run();

static class PlanLookup
{
    public static int RequestsPerSecond(string apiKey) => string.IsNullOrEmpty(apiKey) ? 1 : 100;
}
// Shared token bucket in Redis (StackExchange.Redis). One atomic round trip per request.
using StackExchange.Redis;

namespace RateLimiting;

public sealed record RateDecision(bool Allowed, double RetryAfterSeconds);

public sealed class RedisTokenBucket(IConnectionMultiplexer redis)
{
    // KEYS[1] = bucket; ARGV = rate, capacity, cost. Uses Redis TIME so instance clocks don't matter.
    private const string Script = """
        local t = redis.call('TIME')
        local now = tonumber(t[1]) + tonumber(t[2]) / 1000000
        local rate, cap, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
        local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
        local tokens = tonumber(b[1]) or cap
        local ts = tonumber(b[2]) or now
        tokens = math.min(cap, tokens + (now - ts) * rate)
        local allowed = 0
        local wait = 0
        if tokens >= cost then tokens = tokens - cost; allowed = 1 else wait = (cost - tokens) / rate end
        redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
        redis.call('EXPIRE', KEYS[1], math.ceil(cap / rate) + 1)
        return { allowed, tostring(wait) }
        """;

    public async Task<RateDecision> TryTakeAsync(string apiKey, double rate, double capacity, CancellationToken ct)
    {
        ct.ThrowIfCancellationRequested();
        var result = (RedisResult[])(await redis.GetDatabase().ScriptEvaluateAsync(
            Script, [new RedisKey($"rl:{{{apiKey}}}")], [rate, capacity, 1]))!;
        return new RateDecision((int)result[0] == 1, double.Parse((string)result[1]!, System.Globalization.CultureInfo.InvariantCulture));
    }
}

โš  Common mistakes

  • Mistake: Relying on the built-in ASP.NET Core limiter alone across many instances. Why it is wrong: its state is per process, so with 30 instances a key gets up to 30ร— its limit, unevenly. Instead: use a shared store (Redis) or a gateway, and keep the in-process limiter as a fallback.
  • Mistake: GET then SET in Redis from application code. Why it is wrong: concurrent instances race and over-admit. Instead: one Lua script (or INCR with expiry for fixed windows) so the check is atomic.
  • Mistake: Using each instance's clock to refill tokens. Why it is wrong: clock skew between pods mints or loses tokens. Instead: use Redis TIME inside the script.
  • Mistake: Failing closed whenever Redis is unreachable. Why it is wrong: a cache outage becomes a full API outage for paying customers. Instead: fail open to a local limiter, except on endpoints where over-use is genuinely costly.
  • Mistake: Fixed windows for burst-sensitive limits. Why it is wrong: a client can send 2ร— the limit across a window boundary. Instead: token bucket or sliding window counter.
  • Mistake: Returning 429 without Retry-After. Why it is wrong: clients retry immediately and amplify the load. Instead: send Retry-After and RateLimit headers and document backoff with jitter.
  • Mistake: Rate limiting only by IP. Why it is wrong: partners behind NAT share an IP, and attackers rotate IPs. Instead: per-IP at the edge for floods, per-key for fairness.

๐Ÿ› Senior insight: trade-offs

The senior conversation is about accuracy versus availability. Exact global limits need a coordinated store on every request; most businesses are happy with ยฑ5% if it means no added outage risk. I also push for buying before building: Front Door WAF and API Management cover most needs, and a custom Redis limiter is justified only when limits depend on business data the gateway can't see (per tenant, per expensive operation, cost-weighted calls).

Placement When it fits Cost When not to
Front Door WAF rules Floods, scrapers, per-IP Cheap, at the edge Per-customer plans
API Management rate-limit-by-key / quota-by-key Plans per subscription key APIM tier cost, approximate across regions Limits need domain data
ASP.NET Core in-process Single instance, or fallback Free Many instances needing a shared limit
Custom Redis limiter Per tenant/endpoint, cost-weighted Redis + code to own When a gateway already does it

I measure it with rejections per key, Redis script latency (p99), over-admission against the plan in load tests, and the fallback activation count.

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate names token bucket without comparing it to window algorithms Why: Checks the differences between fixed window, sliding window, token bucket and concurrency limiters
    How to 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.

  2. When: Candidate mentions running many API instances Why: Checks how one limit is enforced across instances and why the built-in limiter is per process
    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.

  3. When: Candidate sizes Redis without numbers Why: Checks capacity estimation of requests per second and memory for the limiter state
    How to answer

    A capacity estimate turns user numbers into load. Start with daily active users ร— actions per user to get requests per day, divide by ~86,400 s (round to 10^5) for average requests/s, then multiply by a peak factor (2โ€“10ร—, often 3ร—). For storage, multiply writes per day by record size and 365, then add indexes and replicas. For bandwidth, multiply requests/s by payload size.

    Example: 10M DAU ร— 20 reads = 200M reads/day โ‰ˆ 2,300/s average, ~7,000/s peak.

    The point is not precision โ€” it's deciding whether one database and a cache are enough or you need partitioning. The trade-off is speed versus accuracy: round hard, but state every assumption.

๐Ÿ›  Real-world problems: how you handle them

Partner batch job exhausts shared API capacity despite rate limits
Situation
A partner-facing [logistics] API on [Azure Container Apps, 24 replicas] in Australia East. Rate limits used the built-in ASP.NET Core token bucket, [100 req/s] per key.
Signals
Every evening at [7 pm] p95 latency rose from [120 ms] to [2 s] for all partners; Azure SQL CPU at 95%; Application Insights showed one API key at [2,100] req/s, far above its plan.
Investigation
Grouped requests by API key and instance in Log Analytics: the key received ~100 req/s on each of the 24 replicas. The limiter was per process, so the effective limit was 24× the plan. Confirmed by load-testing two replicas locally.
Resolution
Immediate: added an API Management `rate-limit-by-key` policy for that key. Long term: a Redis token bucket via a Lua script behind a custom `RateLimiter`, with the built-in limiter kept as a fallback at limit ÷ replicas, plus `Retry-After` headers and partner docs on backoff.
Prevention
Load test in CI that runs multiple replicas and asserts per-key admission stays within 5% of the plan; dashboards for rejections and admitted rate per key; alert on any key above 120% of plan for 5 minutes.

How to tell it (STAR)

**S:** At [company] our partner API slowed for everyone each evening, and one partner's batch job was the trigger. **T:** I had to find why our rate limits weren't stopping it. **A:** In Log Analytics I grouped requests by key and replica and saw the partner getting their full limit on each of [24] replicas, because the built-in limiter keeps state in process. I added a gateway limit that night, then built a shared Redis token bucket with an atomic Lua script and a local fallback, and added Retry-After so their SDK backed off. **R:** The partner settled at their [100 req/s] plan, evening p95 went back to [130 ms], and database CPU dropped from [95%] to [45%].

โ†ฉ Usually asked after

More in Systems to Design

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me