Module 1 · Start Here: Two Classic Cases · Lesson 2 of 15
Case: Rate Limiter for a Multi-Instance ASP.NET Core API
Rate limiter algorithms treat sudden bursts of requests differently. A fixed window can admit twice the limit around the moment one window ends and the next begins. A sliding log never admits more than the limit in any rolling period. A token bucket lets a client save unused allowance and spend it in a burst later. Across ASP.NET Core instances, one fleet-wide limit needs shared enforcement, not separate in-memory counters.
What promise should a rate limiter enforce?
A rate limiter decides whether work may start under a defined allowance. Before choosing an algorithm, make five decisions:
- Identity: What shares the allowance? It might be one authenticated user, API key, or tenant. A tenant is a customer organization whose users share an account.
- Allowance: Is the promise 1,000 requests in each calendar minute, 1,000 in any rolling minute, or a permitted burst followed by a refill rate?
- Location: Does enforcement happen at a shared API gateway, inside ASP.NET Core, or at both? An API gateway is a common entry point that forwards requests to services.
- Scope: Is this an allowance for one instance or the entire fleet?
- Store outage: What happens when the shared counter cannot be reached?
A calendar window has fixed boundaries, such as 12:00:00 through just before 12:01:00. A rolling window looks backward from each arriving request, such as the preceding 60 seconds.
These are different promises: a customer quota might use calendar minutes, while protecting a downstream service may need a strict rolling cap.
The examples below use one identity and one permit per request. A permit is permission to start one unit of work. Rate limits can also measure bytes or operation cost, as the Rate Limiting pattern explains.
Fixed window vs sliding log: what happens at the boundary?
A fixed window keeps one counter per time bucket and admits requests until the bucket reaches its limit. A sliding log stores the timestamps of admitted requests and drops those outside the rolling interval, which gives an exact rolling cap at the cost of one timestamp per admitted request.
Consider a limit of 10 requests per 60 seconds:
| Arrival time | Requests arriving | Fixed window admits | Sliding log admits |
|---|---|---|---|
| 59.9 seconds | 10 | 10 | 10 |
| 60.1 seconds | 10 | 10 | 0 |
The fixed window admits 20 requests within 0.2 seconds because the batches fall in different buckets. The rolling log still sees the first batch when the second arrives.
Run this teaching model to check the table. It uses supplied timestamps, not real waits or ASP.NET Core timers.
var arrivals = Enumerable.Repeat(59.9, 10)
.Concat(Enumerable.Repeat(60.1, 10));
var buckets = new Dictionary<int, int>();
var acceptedTimes = new Queue<double>();
int fixedAdmitted = 0;
int rollingAdmitted = 0;
foreach (double now in arrivals)
{
int bucket = (int)(now / 60);
buckets.TryGetValue(bucket, out int count);
if (count < 10)
{
buckets[bucket] = count + 1;
fixedAdmitted++;
}
while (acceptedTimes.Count > 0 && acceptedTimes.Peek() <= now - 60)
acceptedTimes.Dequeue();
if (acceptedTimes.Count < 10)
{
acceptedTimes.Enqueue(now);
rollingAdmitted++;
}
}
Console.WriteLine($"Fixed admitted: {fixedAdmitted}");
Console.WriteLine($"Rolling admitted: {rollingAdmitted}");Fixed admitted: 20 Rolling admitted: 10
This model uses calendar-aligned buckets. The built-in fixed-window limiter does not: each key's window is timed from when its limiter was created, so the double burst can happen at any second, not only at :00.
The state costs below are per limited identity. They exclude waiting requests and storage-system overhead.
| Algorithm | Main retained state | Trade-off |
|---|---|---|
| Fixed window | Current window and count | Small state; boundary double burst. |
| Exact sliding log | Up to the allowed number of accepted timestamps | Exact rolling cap; more memory and timestamp cleanup. |
| Weighted sliding counter | Two counts and window timing | Small state; approximate rolling usage. |
| .NET segmented sliding window | One count per configured segment, plus bookkeeping | More segments retain finer-grained history, not exact timestamps. |
| Token bucket | Token balance and refill timing | Explicit burst credit; not a strict rolling count. |
| Concurrency limiter | Outstanding permit count | Protects simultaneous capacity, not request rate. |
How does a weighted sliding counter estimate usage?
A weighted sliding counter approximates rolling usage with two counts: the previous window and the current window. It estimates how much of the previous count still belongs in the rolling interval.
Fifteen seconds into a 60-second window, 45/60 of the previous window still overlaps the rolling interval:
estimate = current count + previous count × remaining fraction
With 8 previous and 3 current requests, that gives 3 + 8 × 0.75 = 9, so one more request fits a limit of 10.
It assumes the previous requests were spread evenly; if they clustered, the estimate is off in either direction.
ASP.NET Core's segmented sliding window is neither this formula nor a timestamp log: it counts usage in SegmentsPerWindow segments and recycles permits as old segments leave the window. See the .NET 10 implementation.
How many requests can a token bucket admit?
A token bucket stores spendable permits up to a capacity. Requests consume tokens, and refills restore tokens without exceeding that capacity. Saved tokens allow a burst after an idle period.
A leaky bucket queues requests and lets them out at a fixed rate, so output is smooth and bursts wait or are dropped. A token bucket instead lets saved bursts through immediately.
Starting full, a bucket with capacity 100 and a continuous refill of five tokens per second can admit up to:
100 + 5 × 60 = 400 one-token requests over 60 seconds
Arrival timing matters. Refills that arrive while the bucket is full are lost rather than saved above capacity.
In .NET, a standalone TokenBucketRateLimiter with its own timer adds TokensPerPeriod tokens once per ReplenishmentPeriod, in steps. ASP.NET Core policies refill from one shared timer in proportion to elapsed time, close to the continuous refill above. Exact counts can still differ.
How do you enforce one limit across 20 API instances?
ASP.NET Core's built-in rate limiters keep state in each instance. With 20 independent instances, a 1,000-request allowance can become 20,000 across the fleet. Partitioning by tenant creates separate tenant counters inside each instance; it does not share those counters.
For a fleet-wide limit, enforce it at a shared gateway or use shared counters.
flowchart TD
A["API instance A"] -->|"checks allowance"| S["Shared tenant counter"]
B["API instance B"] -->|"checks allowance"| S
Both instances consult the same tenant counter rather than granting independent allowances.
For 1,000 requests per calendar minute per tenant, a shared fixed-window design can use Redis, a shared data store that supports server-executed scripts:
- Derive a stable tenant ID from validated authentication, not an untrusted caller-supplied tenant header.
- Calculate the minute number from an agreed time source:
floor(Unix seconds / 60). - Build a key such as
rl:reports:tenant-42:minute-30000000. - Execute one atomic script per attempt, then admit only when its returned count is at most 1,000.
The script increments the counter and sets expiry only on its first increment:
local count = redis.call('INCR', KEYS[1])
if count == 1 then
redis.call('PEXPIRE', KEYS[1], ARGV[1])
end
return countKEYS[1] is the tenant-and-window key. ARGV[1] is a validated positive lifetime in milliseconds, covering the remaining window plus a small cleanup margin. Expiry removes old counters; the window identifier in the key determines which allowance is current.
Separate INCR and EXPIRE commands leave a gap: the caller could crash after incrementing but before setting expiry. Putting both in one script removes that caller-side gap.
Rejected attempts still increment the counter, but they neither extend its expiry nor touch the next minute's key.
Add a local safety cap too: an instance-level ceiling that limits damage when shared enforcement is slow or down, sized to the instance's capacity rather than copied from the fleet quota.
The mistake to avoid. A tenant partition, a policy named “global,” or a distributed cache registration does not make the built-in limiter's counters shared.
Should a rate limiter fail open or fail closed?
A fail-open policy allows work when the limiter cannot decide. A fail-closed policy refuses work when it cannot decide.
Choose this per endpoint:
| Endpoint | Example outage choice | Reason |
|---|---|---|
| Low-cost catalog read | Fail open behind a local safety cap | Availability can matter more than exact quota enforcement. |
| Expensive paid export | Fail closed | Unchecked work could create unacceptable cost. |
| Sensitive recovery operation | Fail closed | Bypassing protection could increase abuse risk. |
Give the shared check a short timeout, chosen from the endpoint's latency budget and measured store calls. A timeout means the caller does not know the result: the increment may already have happened, as the timeout model under Going deeper shows, and a blind retry counts it again. That is usually fine for protection, but billing per completed operation needs an idempotency key so a retry is recognized rather than charged again.
If a known quota is exhausted, return 429. If enforcement is unavailable and the endpoint fails closed, 503 can describe that dependency failure more accurately. Keep those reasons separate in monitoring.
How do you configure ASP.NET Core rate limiting and test scale-out?
AddRateLimiter registers policies and UseRateLimiter applies them; rate limiting and multi-tenancy shows the four built-in limiters and how to attach policies, and the rate limiting middleware internals goes deeper. A partitioned policy selects a separate limiter for each identity within the current instance.
Configure HTTP 429 explicitly. The middleware's RejectionStatusCode defaults to 503, so merely enabling a policy is not enough. A rejected lease, the limiter's answer to a permit request, can carry extra information, called metadata. For example, RetryAfter is the limiter's estimate of how long the client should wait. In OnRejected, copy available RetryAfter metadata to the Retry-After response header.
QueueLimit = 0 rejects at once when no permit is free; a small positive bounded queue trades fewer rejections for waiting time, so keep it short enough that queued requests still finish in time.
The following offline example combines configuration with a scale-out demonstration. TestServer runs the ASP.NET Core request pipeline in memory without opening a listening port. See integration tests in ASP.NET Core.
It creates two instances for each experiment:
- Independent: Each instance has its own partitioned allowance of three. Together they admit six requests.
- Shared: Both instances also consult the same counter fake. Together they admit only three.
The local window is one hour and the shared fake uses a frozen minute, so the test never crosses a boundary; nothing waits for replenishment or calls Redis.
using System.Globalization;
using System.Security.Claims;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
if (new Microsoft.AspNetCore.RateLimiting.RateLimiterOptions().RejectionStatusCode != 503)
throw new InvalidOperationException("Unexpected default rejection status.");
Console.WriteLine($"Independent admitted: {await RunPair(shared: false)}");
Console.WriteLine($"Shared admitted: {await RunPair(shared: true)}");
static async Task<int> RunPair(bool shared)
{
var counter = shared ? new SharedCounterFake() : null;
await using var a = await StartInstance(counter);
await using var b = await StartInstance(counter);
using var clientA = a.GetTestClient();
using var clientB = b.GetTestClient();
int admitted = 0;
for (int i = 0; i < 4; i++)
{
using var responseA = await clientA.GetAsync("/work");
using var responseB = await clientB.GetAsync("/work");
if (responseA.IsSuccessStatusCode) admitted++;
if (responseB.IsSuccessStatusCode) admitted++;
}
return admitted;
}
static async Task<WebApplication> StartInstance(SharedCounterFake? shared)
{
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.WebHost.UseTestServer();
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = (context, cancellationToken) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retry))
{
context.HttpContext.Response.Headers["Retry-After"] =
Math.Ceiling(retry.TotalSeconds).ToString(CultureInfo.InvariantCulture);
}
return ValueTask.CompletedTask;
};
options.AddPolicy("tenant", context =>
RateLimitPartition.GetFixedWindowLimiter(
context.User.FindFirst("tenant_id")?.Value ?? "anonymous",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 3,
Window = TimeSpan.FromHours(1),
QueueLimit = 0,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
AutoReplenishment = true
}));
});
var app = builder.Build();
app.UseRouting();
// Test authentication only. Production uses validated credentials.
app.Use(async (context, next) =>
{
context.User = new ClaimsPrincipal(new ClaimsIdentity(
new[] { new Claim("tenant_id", "tenant-a") }, "test"));
await next(context);
});
app.UseRateLimiter();
app.Use(async (context, next) =>
{
string tenant = context.User.FindFirst("tenant_id")!.Value;
if (shared is not null && !shared.TryAdmit(tenant, minute: 42, limit: 3))
{
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
// Frozen test time is halfway through the shared minute.
context.Response.Headers["Retry-After"] = "30";
return;
}
await next(context);
});
app.MapGet("/work", () => "accepted").RequireRateLimiting("tenant");
await app.StartAsync();
return app;
}
sealed class SharedCounterFake
{
private readonly object gate = new();
private readonly Dictionary<(string Tenant, long Minute), long> counts = new();
public bool TryAdmit(string tenant, long minute, int limit)
{
lock (gate)
{
var key = (tenant, minute);
counts.TryGetValue(key, out long count);
counts[key] = ++count;
return count <= limit;
}
}
}Independent admitted: 6 Shared admitted: 3
Needs ASP.NET Core (a web project) and the package Microsoft.AspNetCore.Mvc.Testing 10.0.12. Built and run on the in-memory TestServer: the output above is what it printed.
Each request first receives a test identity, then passes through the local limiter. Requests that pass the local limiter reach the shared check, if enabled. Rejected requests never reach /work.
Without shared enforcement, each instance admits three. With it, the first three shared checks pass and later checks fail.
A shared rejection does not restore the local permit already consumed. The fake models shared admission only, not Redis expiry, network failures or failover.
Your interview answer
In an interview, say: “First I pin down the promise: who shares the allowance, a calendar window or a rolling cap, and whether it holds across the fleet. A fixed window can admit twice the limit around a boundary, a sliding log is exact but stores timestamps, and a token bucket allows saved bursts. ASP.NET Core's built-in limiters count per instance, so for 1,000 requests a minute per tenant across 20 instances I run one atomic Redis script per request that increments a per-tenant, per-window key and sets its expiry on the first hit. A local limiter caps each instance, and each endpoint fails open or closed by policy, because a timed-out increment may already have counted. I set RejectionStatusCode to 429, since the default is 503, and send Retry-After from the RetryAfter metadata.”
Check yourself
A policy allows 10 requests per calendar minute. Ten arrive at second 59.9 and ten at second 60.1. What can a fixed window admit?
Show answer
Correct answer: B
Each calendar window has its own allowance. An exact 60-second rolling log would still contain the first ten timestamps and reject the second batch.
A shared-counter call times out. Which statement is safe?
Show answer
Correct answer: D
A lost response does not reveal whether the increment happened. Use a short timeout, an endpoint-specific fail-open or fail-closed policy, and a local safety cap where appropriate.
Going deeper
On .NET 10 the built-in fixed-window limiter reports the whole window as RetryAfter (60 seconds even when one second is left) and the sliding-window limiter reports none; .NET 11 reports the time left for both. The token bucket reports whole replenishment periods. A concurrency limiter cannot know when current work will finish, so it never provides RetryAfter.
Several limiters can form a chain, built with RateLimiter.CreateChained or with middleware in sequence. Order matters: time-based permits that an earlier limiter granted are not returned when a later one rejects, which is why a shared rejection in the HTTP example still consumes local allowance.
For a production shared counter, instances that disagree about the minute use different keys, so let a gateway or one time source supply the window. Also state what a Redis failover, a replica taking over from the failed main server, may lose: increments the replica had not received, so counts can go back down.
This timeout model increments a counter, then simulates losing the response; the outage policy decides whether to admit the work.
int count = 0;
bool TryStart(bool failOpen)
{
try
{
count++;
throw new TimeoutException("Simulated lost response.");
}
catch (TimeoutException)
{
return failOpen;
}
}
Console.WriteLine($"Fail open admits: {TryStart(failOpen: true)}");
Console.WriteLine($"Fail closed admits: {TryStart(failOpen: false)}");
Console.WriteLine($"Counter after two timed-out attempts: {count}");Fail open admits: True Fail closed admits: False Counter after two timed-out attempts: 2
Both attempts incremented the counter, even though neither received its result.
Do not let untrusted partition keys create unlimited counters: define permitted identities, cleanup and limits on retained state.
Clients should still bound their retries and add a small random delay so they do not all retry together. The Rate Limiting pattern discusses this coordination.
For a case where provider allowances and retries shape the whole design, see the notification system case study.
Sources
- Rate limiting middleware in ASP.NET Core | Microsoft Learn: Instance-local counter scope, partitioned policies, limiter configuration, rejection status and metadata, bounded queues, concurrency behavior, and chained permit consumption.
- TokenBucketRateLimiter Class (System.Threading.RateLimiting) | Microsoft Learn: The built-in token-bucket API and the distinction between configured replenishment and the continuous teaching model.
- Rate Limiting Pattern - Azure Architecture Center | Microsoft Learn: Operation and cost-based allowances, shared enforcement considerations, concurrency as a distinct protection mechanism, and coordinated bounded retries with random delays.
- runtime/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiter.cs at v10.0.12 · dotnet/runtime · GitHub: Distinguishing .NET's segment counters and permit recycling from an exact timestamp log and a weighted two-counter estimate.
- Integration tests in ASP.NET Core | Microsoft Learn: Testing an ASP.NET Core pipeline with an in-memory test server and a test client, with an infrastructure fake instead of a live dependency.
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 1 Dec 2026 ·