Skip to main content

Distributed Rate Limiting

With a rate limiter, work is refused or delayed when a caller goes over an allowed budget. An example is 100 requests per minute for each user. A rate limiter protects your services and paid quotas from overload and abuse.

.NET already includes rate limiters in System.Threading.RateLimiting, and the ASP.NET Core rate-limiting middleware builds on them. However, they count in the memory of one process. When your application has several replicas behind a load balancer, each replica enforces a separate copy of the limit.

Limit: 100 requests/minute per user

In-memory limiter, 5 replicas: each replica allows 100 -> the user gets up to 500
Kahuna limiter, 5 replicas: all replicas share 100 -> the user gets 100

The effective limit also changes when the application scales up or down. A common fix is a shared counter in Redis, updated with INCR or a Lua script. Kahuna's limiters use the same approach. The budget is stored in one shared key. This means that all replicas draw from the same counter, and the limit is the same for any replica count.

Use them when a limit must apply across all instances of an application. Examples are per-tenant API quotas and a cap on concurrent jobs across a worker fleet. Keep the in-memory limiters when a per-instance limit is acceptable. Each Kahuna admission decision costs a network round trip to the cluster.

The .NET client provides four limiters that implement the standard System.Threading.RateLimiting.RateLimiter API. This means that they work with the ASP.NET Core rate-limiting middleware and with code that already uses that API. The TypeScript client (kahuna-client) provides the same four limiters, with KahunaPartitionedRateLimiter and rateLimitKeyFor. Its kahuna-client/middleware entry point has HTTP middleware. For custom algorithms built with scripts, see the Rate Limiting recipe.

Replicas that share a key should use the same limiter type and settings, including the same durability. Settings are copied when a limiter is constructed. A later change to the options object doesn't change the limiter. Reserve separate keys for unrelated policies. Each caller interprets the state with its configuration. This means that a change of limits, or a key shared between algorithms, isn't a coordinated migration.

Packages​

The APIs below target .NET 10 and require Kahuna 1.10.11 or later.

dotnet add package Kahuna.Client
# For ASP.NET Core middleware integration:
dotnet add package Kahuna.Client.AspNetCore

Kahuna.Client.RateLimiting contains the limiters and partition helpers. The separate ASP.NET Core package supplies extensions in Microsoft.AspNetCore.RateLimiting; worker applications do not need the ASP.NET Core shared framework.

In TypeScript, npm install kahuna-client provides the limiters; the HTTP middleware is the kahuna-client/middleware entry point of the same package and depends on no web framework.

Choosing an Algorithm​

Each limiter stores its state in Kahuna under the Key that you configure. For each admission decision, the server executes one short Kahuna Script. The script reads the state and writes it back in a single transaction. A separate read followed by a write would let two replicas see the same count, and both replicas would be admitted. Window and token-bucket scripts read the time from hlc(), the cluster's hybrid logical clock. They don't use the wall clock of the application.

In the diagram, two replicas share one token-bucket key with one permit left. Their admission scripts take effect one at a time. This means that only the first replica is admitted.

ClassState and admission rule
KahunaFixedWindowRateLimiterOne counter with windows aligned to hlc()'s physical milliseconds. Each window admits up to PermitLimit permits. Requests on opposite sides of a boundary can spend two windows' budgets close together.
KahunaSlidingWindowRateLimiterOne value containing segment counters. Permits are reclaimed when their segment leaves the window. This is a segmented approximation. It isn't an exact rolling timestamp log.
KahunaTokenBucketRateLimiterOne value containing tokens and last replenishment time. A missing bucket starts at TokenLimit; requests add TokensPerPeriod for each full ReplenishmentPeriod that elapsed, capped at the limit. No refill timer is required.
KahunaConcurrencyLimiterOne expiring key per acquired lease directly under <Key>/. Admission sums live lease permits and creates a new lease if capacity remains.

Time and window boundaries have these limits.

  • hlc() returns the physical (millisecond) component of the HLC on the coordinating node. It isn't a monotonic elapsed-time timer. This means that clock advances can move window and refill boundaries.
  • Fixed-window and replenishment durations are truncated to milliseconds.
  • The sliding-window segment length is floor(Window.TotalMilliseconds / SegmentsPerWindow). This means that the effective window can be shorter than configured.
  • A sliding window can return a segment's permits up to one segment early, before each individual request in it is a full window old.

Direct Client Use​

using Kahuna.Client;
using Kahuna.Client.RateLimiting;
using System.Threading.RateLimiting;

KahunaClient kahuna = new(["https://kahuna1:8082", "https://kahuna2:8084"]);

await using KahunaTokenBucketRateLimiter limiter = new(kahuna, new()
{
Key = "rate-limit/outbound-email",
TokenLimit = 20,
TokensPerPeriod = 5,
ReplenishmentPeriod = TimeSpan.FromSeconds(10)
});

using RateLimitLease lease = await limiter.AcquireAsync(1);
if (!lease.IsAcquired)
{
if (lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
Console.WriteLine($"Retry after {retryAfter}");
return;
}

await SendEmailAsync();

Both limiters execute the same scripts on the same key. This means that a .NET replica and a TypeScript replica configured like this spend one shared budget. Pass a CancellationToken (.NET) or { signal } (TypeScript) to bound the wait when a queue is enabled.

Use AcquireAsync. Synchronous AttemptAcquire can't do the required network I/O, and it always returns a refused lease. Permit counts may range from zero to the configured limit; an oversized request throws. An asynchronous zero-permit request checks whether at least one permit is available, but it doesn't consume a permit. It does not reserve capacity for a later call.

Disposing a window or token-bucket lease does not refund consumed permits. A concurrency lease starts background release when disposed; keep it alive for the duration of the work.

HTTP Middleware Policies​

using Kahuna.Client;
using Kahuna.Client.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
using System.Globalization;
using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(new KahunaClient(
["https://kahuna1:8082", "https://kahuna2:8084"]));

builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = (context, _) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
context.HttpContext.Response.Headers.RetryAfter =
Math.Ceiling(retryAfter.TotalSeconds).ToString(CultureInfo.InvariantCulture);
return ValueTask.CompletedTask;
};

options.AddKahunaFixedWindowLimiter("api", o =>
{
o.PermitLimit = 100;
o.Window = TimeSpan.FromMinutes(1);
});

options.AddKahunaTokenBucketLimiter("per-client",
context => context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
o =>
{
o.TokenLimit = 20;
o.TokensPerPeriod = 5;
o.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
});
});

var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/status", () => "ok").RequireRateLimiting("api");
app.MapPost("/work", () => Results.Accepted()).RequireRateLimiting("per-client");
app.Run();

ASP.NET Core has four extensions.

  • AddKahunaFixedWindowLimiter
  • AddKahunaSlidingWindowLimiter
  • AddKahunaTokenBucketLimiter
  • AddKahunaConcurrencyLimiter

Each extension takes a policy name and a configuration callback. It can also take a Func<HttpContext, string> partition selector and, as the last argument, an explicit client. Otherwise, the client comes from request services. The middleware follows its initial synchronous refusal with asynchronous acquisition. For identity-based partition selectors, configure authentication and place its middleware before UseRateLimiter.

In TypeScript, kahunaRateLimit from kahuna-client/middleware works with Express, Connect, and node:http. For a handler that takes a Request and returns a Response (Hono, Bun, Deno, route handlers), wrap it with withKahunaRateLimit. A refused request gets status 429. When the cluster can tell when the budget frees up, the response also has a Retry-After header in seconds. You can change the response with rejectionStatusCode and onRejected. Invalid settings throw when the middleware is built. Close each policy when the application stops: await api.policy.close().

If you don't set a partition selector (partitionBy in TypeScript), the default state key is rate-limit/<policy>. With one, it is rate-limit/<policy>/<partition>; an empty partition string uses the policy key. Both clients name the same keys. This means that a .NET replica and a TypeScript replica with the same policy name and settings share one budget. Their partition selectors must return the same string for the same caller. In .NET the callback receives this default in o.Key and can replace it; in TypeScript, set keyPrefix or pass a settings function. The callback executes once at registration to validate settings. It executes again when each partition limiter is created. Partition strings are concatenated directly into stored keys; hash sensitive identifiers and choose names that avoid collisions.

Outside middleware, build partitioned limiters with the KahunaRateLimitPartition methods in .NET, such as GetFixedWindowLimiter. In TypeScript, use KahunaPartitionedRateLimiter and rateLimitKeyFor.

using PartitionedRateLimiter<string> tenants =
PartitionedRateLimiter.Create<string, string>(tenant =>
KahunaRateLimitPartition.GetFixedWindowLimiter(kahuna, tenant, key => new()
{
Key = KahunaRateLimitPartition.KeyFor("tenant-api", key),
PermitLimit = 1000,
Window = TimeSpan.FromMinutes(1)
}));

Disposal of an idle partition does not delete its budget state. A later limiter using the same key resumes whatever state remains in Kahuna.

Settings and Queueing​

Common optionDefaultMeaning
Keyempty; requiredShared state key or concurrency bucket.
DurabilityEphemeralMemory state; lost state resets counters or releases concurrency capacity. Persistent uses persistent script commands and durable transaction finalization.
QueueLimit0Maximum number of permits (not requests) waiting in this process. With 0, a request that can't be admitted fails at once.
QueueProcessingOrderOldestFirstLocal queue order. NewestFirst can refuse oldest waiters to make room.
FailureModeThrowBehavior when a decision cannot be obtained: propagate, admit (Allow), or refuse (Deny).
MaxRetries8Additional attempts for Aborted or MustRetry, with randomized bounded backoff. Other failures are not retried by the limiter.

The TypeScript limiters take the same options in camelCase (key, durability, queueLimit, queueProcessingOrder, failureMode, maxRetries) with the same defaults and the same retry rule. Duration options are in milliseconds and end in Ms, for example windowMs and leaseDurationMs.

Each algorithm has required settings.

  • Fixed and sliding windows: a positive PermitLimit and window.
  • Sliding windows also need SegmentsPerWindow between 1 and 1000, and at least one millisecond per segment.
  • Token buckets: positive TokenLimit and TokensPerPeriod, and a replenishment period of at least one millisecond.
  • Concurrency: a positive PermitLimit, a LeaseDuration of at least 30 ms (default 30 seconds), and a QueuePollInterval of at least 1 ms (default 50 ms).

Queues and fairness are local, even though the budget is shared.

  • Window and bucket refusals normally carry RetryAfter. It is a computed wait. It doesn't reserve capacity or guarantee admission. Concurrency refusals don't have a retry time.
  • Queued requests retry after the RetryAfter delay. If there isn't a delay, they poll at 50 ms intervals. The concurrency limiter polls at its configured QueuePollInterval.
  • A local concurrency release wakes the queue after its release attempt completes.
  • Cancellation removes a waiting request. With a queue enabled, Deny can keep a caller waiting through cluster failures. Use cancellation to bound the wait.

GetStatistics() returns the successful and failed lease counts of this limiter, with its local queued permit count. Available permits show its last observation, and another replica may already have spent them. These statistics aren't authoritative for the cluster.

Guarantees and Failure Limits​

Each decision is a transaction. When callers compete for the same budget, Kahuna's transaction conflict handling makes their admissions take effect one at a time. However, a request and its external work don't become one transaction. Also, admission isn't exactly-once across a lost response. A transport failure doesn't mean that no state was consumed. For more information, see transaction outcome handling.

When acquisition fails, FailureMode.Allow grants a lease but doesn't record a cluster permit. This means that it deliberately stops enforcing the limit. With Deny, the request is refused. With Throw, the error is propagated. Caller cancellation remains cancellation under all three modes.

Choose durability by the cost of a reset. The two levels differ in both price and failure behavior.

  • Ephemeral (the default) state is stored only in the memory of the partition leader. An admission doesn't need replication. However, a node restart or a leader change loses the state, and eviction can also lose it. Window and bucket budgets then start over, and held concurrency permits are freed.
  • Persistent turns each granted admission into a replicated write. The script's write commits only after a quorum of the partition's replicas stores it. This means that each admission pays Raft replication latency. A refusal doesn't write anything.

For the general trade-off, see Durability Levels.

Persistent state is replicated and stored on disk. This means that it survives restarts and failover. However, persistence doesn't remove clock effects or TTL expiry. It also doesn't remove uncertain responses or lease renewal failures. Fixed-window and token-bucket ephemeral scripts can use the single-key fast path. Sliding-window scripts and concurrency bucket scans use the general transaction path.

Concurrency leases renew at intervals of about LeaseDuration / 3. The renewal is a conditional write that updates only an existing key. This means that an expired lease isn't recreated.

  • When a renewal returns NotSet, the limiter removes its local held-lease entry and wakes its queue. A network failure alone leaves the lease eligible for another renewal round.
  • Renewal is best-effort. If the key expires while its holder works, another caller can acquire that capacity. The returned lease does not signal the loss or cancel the work.
  • The limiter bounds the number of live permit keys. It doesn't bound the number of operations that continue after a pause or a lost connection. No fencing token protects the external work.

Release and Disposal​

  • Lease disposal deletes the key in the background. If the delete fails, the key expires when its lease ends.
  • Limiter disposal stops renewal, and queued waiters are refused. It doesn't delete outstanding leases at once.
  • Async limiter disposal waits for release tasks that are already pending. When prompt release matters, dispose held leases before the limiter.
  • Don't store unrelated keys directly under the bucket of a concurrency limiter. Its admission script reads all live values there as permit counts.