Rate Limiting
Rate limiting protects shared resources. When a caller goes over an allowed request budget, the work is refused or delayed. When many service instances enforce one limit, they must share the counter. With Kahuna, the check and the increment are one atomic script on the server, much like a Redis Lua script. The client doesn't need several round trips.
For the built-in limiters in the .NET and TypeScript clients, and their ASP.NET Core and Node.js middleware, see Distributed Rate Limiting. The built-in limiters support more algorithms than this recipe, such as token buckets and concurrency limits.
This recipe uses an ephemeral key because rate-limit counters are temporary state. The key expires automatically when the window ends.
An ephemeral counter is stored only in the memory of the partition leader. A Kahuna node restart or a leader change drops it, and memory eviction can also drop it. The window then starts again from zero, and callers can briefly exceed the limit. This is acceptable for most throttling.
When a reset could cause real harm, use persistent keys. Examples are a cap on paid API calls and a limit on password attempts. Change eget and eset to get and set. The counter then survives restarts and leader changes. However, each admitted request becomes a replicated Raft write, and the script no longer takes the single-key fast path. For more information, see Durability Levels.
The examples below match Kahuna's single-key script fast path. Each example is one auto-commit script that reads and writes one ephemeral key and doesn't use blocking statements. This means that rate-limit checks are atomic, at a lower cost than a multi-key transaction.
Fixed Window Counter
Use one key for each subject and time window.
rate-limit/{scope}/{subject}/{window-start}
These keys are for a login limit by IP address and an API limit by user.
rate-limit/login/203.0.113.10/1718391900
rate-limit/api/user-42/1718391900
This recipe derives window keys from the application clock. Clock skew between application instances can put their requests in different windows. This means that the window boundary isn't exact across instances. The built-in .NET fixed-window limiter computes boundaries in its decision script, with the hybrid logical clock of the cluster (hlc()).
The script below creates the counter if it doesn't exist and increments it if it exists. When the count reaches the limit, the script returns 0, and the request is refused. Pass @expires_ms as the remaining time in the current window, optionally with a small grace period. Don't pass the full window length with each request. That would turn the counter into a sliding-expiration counter.
let current = eget @counter_key
if not found then
eset @counter_key 1 ex to_int(@expires_ms)
return 1
end
let count = to_int(current)
if count >= to_int(@limit) then
return 0
end
eset @counter_key count + 1 ex to_int(@expires_ms)
return 1
Script parameters arrive as strings. The script converts them with to_int before it compares them or passes them to ex.
Run the script from a client with parameters.
- .NET
- TypeScript
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
long windowMs = 60_000;
long windowStartMs = nowMs - (nowMs % windowMs);
long windowEndMs = windowStartMs + windowMs;
long expiresMs = Math.Max(1, windowEndMs - nowMs + 1_000);
KahunaKeyValueTransactionResult result = await client.ExecuteKeyValueTransactionScript(
"""
let current = eget @counter_key
if not found then
eset @counter_key 1 ex to_int(@expires_ms)
return 1
end
let count = to_int(current)
if count >= to_int(@limit) then
return 0
end
eset @counter_key count + 1 ex to_int(@expires_ms)
return 1
""",
parameters:
[
new() { Key = "@counter_key", Value = $"rate-limit/login/203.0.113.10/{windowStartMs}" },
new() { Key = "@limit", Value = "10" },
new() { Key = "@expires_ms", Value = expiresMs.ToString() }
]
);
bool allowed = result.FirstValueAsString == "1";
const nowMs = Date.now();
const windowMs = 60_000;
const windowStartMs = nowMs - (nowMs % windowMs);
const windowEndMs = windowStartMs + windowMs;
const expiresMs = Math.max(1, windowEndMs - nowMs + 1000);
const script = client.loadScript(`
let current = eget @counter_key
if not found then
eset @counter_key 1 ex to_int(@expires_ms)
return 1
end
let count = to_int(current)
if count >= to_int(@limit) then
return 0
end
eset @counter_key count + 1 ex to_int(@expires_ms)
return 1
`);
const result = await script.run({
parameters: [
{ key: "@counter_key", value: `rate-limit/login/203.0.113.10/${windowStartMs}` },
{ key: "@limit", value: "10" },
{ key: "@expires_ms", value: String(expiresMs) }
]
});
const firstValue = result.values[0]?.value;
const allowed = firstValue ? new TextDecoder().decode(firstValue) === "1" : false;
Sliding Expiration Counter
For a simpler throttle, keep one counter for each subject. Each accepted request sets the expiration to the full TTL in @ttl_ms.
let current = eget @counter_key
if not found then
eset @counter_key 1 ex to_int(@ttl_ms)
return 1
end
let count = to_int(current)
if count >= to_int(@limit) then
return 0
end
eset @counter_key count + 1 ex to_int(@ttl_ms)
return 1
When a caller sends requests continuously, this counter is stricter than a fixed window. The expiration of the key moves forward while the caller is active.
Operational Notes
- Use ephemeral durability for short-lived counters.
- Keep the script small. Rate limiting sits on a hot path.
- Use a bucketed key format if you need to inspect counters with
eget by bucket. - Use persistent durability if the limit must survive Kahuna node restarts and leader changes.
- For very high-cardinality traffic, choose a TTL that is short enough to avoid unbounded memory growth.