StellaOps.Messaging.RateLimiting
Rate limiting for services behind a Router gateway: the limiter contract, the fixed-window rules and the limiter factory. Install Installing Stella Ops packagesRouter downloads and signaturesnet10.01.0.1-20261117T070237Zdotnet add package StellaOps.
Namespaces
| Namespace | Types |
|---|---|
StellaOps. | 8 |
namespace StellaOps.Messaging.RateLimiting
| Type | Kind | Description |
|---|---|---|
IRateLimiter | interface | Transport-agnostic rate limiter interface. |
IRateLimiterFactory | interface | Factory for creating rate limiter instances. |
RateLimitPolicy | record | Defines a rate limit policy: at most RateLimitPolicy.permits per key in each fixed, epoch-aligned window of length RateLimitPolicy.(see RateLimiterContract). |
RateLimitResult | struct | Result of a rate limit acquisition attempt. |
RateLimitStatus | struct | Current status of a rate limit key. |
RateLimitWindow | struct | One fixed rate limit window, in Unix milliseconds. |
RateLimitWindowState | struct | A key’s effective window and the permits counted in it. |
RateLimiterContract | class | The rules every IRateLimiterbackend (Valkey, PostgreSQL, in-memory) applies, so that one RateLimitPolicygives the same decisions on each of them. |
interface IRateLimiter
public interface IRateLimiter
Transport-agnostic rate limiter interface. Every backend applies the same fixed-window algorithm (windows aligned to the Unix epoch); check and increment are atomic, and a denied attempt does not consume a permit. Keys are case-sensitive. A key keeps one window per policy, so one limiter can apply several policies (for example per minute and per day) to the same key. The shared rules are defined by RateLimiterContract.
Members
| Member | Kind | Summary |
|---|---|---|
ProviderName | property | Gets the provider name for diagnostics (e.g., “valkey”, “postgres”, “inmemory”). |
GetStatusAsync( | method | Gets current usage for a key under policy without consuming a permit. |
ResetAsync( | method | Resets the rate limit counters for a key under every policy. |
TryAcquireAsync( | method | Attempts to acquire a permit from the rate limiter under policy. |
property ProviderName #
ProviderName #string ProviderName { get; }
Gets the provider name for diagnostics (e.g., “valkey”, “postgres”, “inmemory”).
method GetStatusAsync(string, RateLimitPolicy, CancellationToken) #
GetStatusAsync(string, RateLimitPolicy, CancellationToken) #ValueTask<RateLimitStatus> GetStatusAsync(string key, RateLimitPolicy policy, CancellationToken cancellationToken = default)
Gets current usage for a key under policy without consuming a permit.
Parameters
key: The rate limit key.policy: The rate limit policy.cancellationToken: Cancellation token.
Returns
The current rate limit status.
method ResetAsync(string, CancellationToken) #
ResetAsync(string, CancellationToken) #ValueTask<bool> ResetAsync(string key, CancellationToken cancellationToken = default)
Resets the rate limit counters for a key under every policy.
Parameters
key: The rate limit key.cancellationToken: Cancellation token.
Returns
True if the key had permits counted, under any policy, in a window that had not ended, and was reset.
method TryAcquireAsync(string, RateLimitPolicy, CancellationToken) #
TryAcquireAsync(string, RateLimitPolicy, CancellationToken) #ValueTask<RateLimitResult> TryAcquireAsync(string key, RateLimitPolicy policy, CancellationToken cancellationToken = default)
Attempts to acquire a permit from the rate limiter under policy. When the key’s current window for that policy is full the attempt is denied, nothing is counted, and RateLimitResult.is the time until that window ends. The key’s windows for other policies are not changed: a caller that applies two policies calls once per policy.
Parameters
key: The rate limit key (e.g., user ID, IP address, resource identifier): 1 toRateLimiterContract.characters, compared case-sensitively.MaxKeyLength policy: The rate limit policy defining max permits and window.cancellationToken: Cancellation token.
Returns
The result of the rate limit check.
interface IRateLimiterFactory
public interface IRateLimiterFactory
Factory for creating rate limiter instances.
Members
| Member | Kind | Summary |
|---|---|---|
ProviderName | property | Gets the provider name for this factory. |
Create( | method | Creates a rate limiter with the specified name. |
property ProviderName #
ProviderName #string ProviderName { get; }
Gets the provider name for this factory.
method Create(string) #
Create(string) #IRateLimiter Create(string name)
Creates a rate limiter with the specified name.
Parameters
name: The rate limiter name (used as key prefix, and in PostgreSQL as part of the table name): 1 toRateLimiterContract.characters fromMaxNameLength a-z,0-9and_, starting with a letter. Checked byRateLimiterContract..ValidateName( string)
Returns
A configured rate limiter instance.
Exceptions
ArgumentException: The name breaks the rule.
record RateLimitPolicy
public sealed record RateLimitPolicy
Defines a rate limit policy: at most RateLimitPolicy.permits per key in each fixed, epoch-aligned window of length RateLimitPolicy.(see RateLimiterContract).
Parameters
MaxPermits: Maximum number of permits allowed within one window; at least 1.Window: The window length: a whole number of milliseconds fromRateLimiterContract.(1 second) toMinWindow RateLimiterContract.(366 days).MaxWindow
Exceptions
Argument: A value is outside its range, at construction or in aOut Of Range Exception withexpression.
Members
| Member | Kind | Summary |
|---|---|---|
RateLimitPolicy( | constructor | Defines a rate limit policy: at most RateLimitPolicy.permits per key in each fixed, epoch-aligned window of length RateLimitPolicy.(see RateLimiterContract). |
MaxPermits | property | Maximum number of permits allowed within one window. |
Window | property | The window length. |
PerHour( | method | Creates a per-hour rate limit policy. |
PerMinute( | method | Creates a per-minute rate limit policy. |
PerSecond( | method | Creates a per-second rate limit policy. |
constructor RateLimitPolicy(int, TimeSpan) #
RateLimitPolicy(int, TimeSpan) #public RateLimitPolicy(int MaxPermits, TimeSpan Window)
Defines a rate limit policy: at most RateLimitPolicy.permits per key in each fixed, epoch-aligned window of length RateLimitPolicy.(see RateLimiterContract).
Parameters
MaxPermits: Maximum number of permits allowed within one window; at least 1.Window: The window length: a whole number of milliseconds fromRateLimiterContract.(1 second) toMinWindow RateLimiterContract.(366 days).MaxWindow
Exceptions
Argument: A value is outside its range, at construction or in aOut Of Range Exception withexpression.
property MaxPermits #
MaxPermits #public int MaxPermits { get; init; }
Maximum number of permits allowed within one window.
property Window #
Window #public TimeSpan Window { get; init; }
The window length.
method PerHour(int) #
PerHour(int) #public static RateLimitPolicy PerHour(int maxPermits)
Creates a per-hour rate limit policy.
method PerMinute(int) #
PerMinute(int) #public static RateLimitPolicy PerMinute(int maxPermits)
Creates a per-minute rate limit policy.
method PerSecond(int) #
PerSecond(int) #public static RateLimitPolicy PerSecond(int maxPermits)
Creates a per-second rate limit policy.
struct RateLimitResult
public readonly struct RateLimitResult
Result of a rate limit acquisition attempt.
Members
| Member | Kind | Summary |
|---|---|---|
CurrentCount | property | Gets the current count of permits used in the window. |
IsAllowed | property | Gets whether the permit was acquired (request allowed). |
RemainingPermits | property | Gets the number of remaining permits in the window. |
RetryAfter | property | Gets the suggested time to wait before retrying (when denied). |
Allowed( | method | Creates a result indicating the permit was acquired. |
Denied( | method | Creates a result indicating the request was denied. |
property CurrentCount #
CurrentCount #public int CurrentCount { get; init; }
Gets the current count of permits used in the window.
property IsAllowed #
IsAllowed #public bool IsAllowed { get; init; }
Gets whether the permit was acquired (request allowed).
property RemainingPermits #
RemainingPermits #public int RemainingPermits { get; init; }
Gets the number of remaining permits in the window.
property RetryAfter #
RetryAfter #public TimeSpan? RetryAfter { get; init; }
Gets the suggested time to wait before retrying (when denied).
method Allowed(int, int) #
Allowed(int, int) #public static RateLimitResult Allowed(int currentCount, int remainingPermits)
Creates a result indicating the permit was acquired.
method Denied(int, TimeSpan) #
Denied(int, TimeSpan) #public static RateLimitResult Denied(int currentCount, TimeSpan retryAfter)
Creates a result indicating the request was denied.
struct RateLimitStatus
public readonly struct RateLimitStatus
Current status of a rate limit key.
Members
| Member | Kind | Summary |
|---|---|---|
CurrentCount | property | Gets the current count of permits used in the window. |
Exists | property | Gets whether the key exists (has any usage). |
RemainingPermits | property | Gets the number of remaining permits in the window. |
WindowRemaining | property | Gets the time remaining until the window resets. |
Empty( | method | Creates a status for a key with no usage. |
WithUsage( | method | Creates a status for an existing key. |
property CurrentCount #
CurrentCount #public int CurrentCount { get; init; }
Gets the current count of permits used in the window.
property Exists #
Exists #public bool Exists { get; init; }
Gets whether the key exists (has any usage).
property RemainingPermits #
RemainingPermits #public int RemainingPermits { get; init; }
Gets the number of remaining permits in the window.
property WindowRemaining #
WindowRemaining #public TimeSpan WindowRemaining { get; init; }
Gets the time remaining until the window resets.
method Empty(int) #
Empty(int) #public static RateLimitStatus Empty(int maxPermits)
Creates a status for a key with no usage.
method WithUsage(int, int, TimeSpan) #
WithUsage(int, int, TimeSpan) #public static RateLimitStatus WithUsage(int currentCount, int remainingPermits, TimeSpan windowRemaining)
Creates a status for an existing key.
struct RateLimitWindow
public readonly struct RateLimitWindow : IEquatable<RateLimitWindow>
One fixed rate limit window, in Unix milliseconds.
Parameters
StartMs: Window start (inclusive).LengthMs: Window length.
Members
| Member | Kind | Summary |
|---|---|---|
RateLimitWindow( | constructor | One fixed rate limit window, in Unix milliseconds. |
EndMs | property | Window end (exclusive), in Unix milliseconds. |
LengthMs | property | Window length. |
StartMs | property | Window start (inclusive). |
RemainingAt( | method | Time from now until the window ends; zero once it has ended. |
constructor RateLimitWindow(long, long) #
RateLimitWindow(long, long) #public RateLimitWindow(long StartMs, long LengthMs)
One fixed rate limit window, in Unix milliseconds.
Parameters
StartMs: Window start (inclusive).LengthMs: Window length.
property EndMs #
EndMs #public long EndMs { get; }
Window end (exclusive), in Unix milliseconds.
property LengthMs #
LengthMs #public long LengthMs { get; init; }
Window length.
property StartMs #
StartMs #public long StartMs { get; init; }
Window start (inclusive).
method RemainingAt(DateTimeOffset) #
RemainingAt(DateTimeOffset) #public TimeSpan RemainingAt(DateTimeOffset now)
Time from now until the window ends; zero once it has ended.
struct RateLimitWindowState
public readonly struct RateLimitWindowState : IEquatable<RateLimitWindowState>
A key’s effective window and the permits counted in it.
Parameters
Window: The effective window.Count: Permits counted inWindow.
Members
| Member | Kind | Summary |
|---|---|---|
RateLimitWindowState( | constructor | A key’s effective window and the permits counted in it. |
Count | property | Permits counted in Window. |
Window | property | The effective window. |
constructor RateLimitWindowState(RateLimitWindow, int) #
RateLimitWindowState(RateLimitWindow, int) #public RateLimitWindowState(RateLimitWindow Window, int Count)
A key’s effective window and the permits counted in it.
Parameters
Window: The effective window.Count: Permits counted inWindow.
property Count #
Count #public int Count { get; init; }
Permits counted in Window.
property Window #
Window #public RateLimitWindow Window { get; init; }
The effective window.
class RateLimiterContract
public static class RateLimiterContract
The rules every IRateLimiterbackend (Valkey, PostgreSQL, in-memory) applies, so that one RateLimitPolicygives the same decisions on each of them.
Remarks
Algorithm: a fixed window aligned to the Unix epoch. For a window of W milliseconds, a call at Unix time t (milliseconds) belongs to the window that starts at floor(t / W) * W. A key may take at most RateLimitPolicy.permits in one window. Check and increment are one atomic step in every backend.
A denied attempt does not consume a permit: the count stays at the limit until the window ends.
A key’s stored window never moves backwards. A caller whose clock lags behind a window another caller has already opened is counted in that newer window, so clock skew between hosts cannot reopen permits.
A key keeps one window per policy. Its state under one policy (RateLimitPolicy.and RateLimitPolicy., named by RateLimiterContract.) is independent of its state under any other policy, so one limiter can apply a per-minute and a per-day policy to the same key. Equal policies share one window. IRateLimiter.clears the key under every policy.
Members
| Member | Kind | Summary |
|---|---|---|
MaxKeyLength | constant | Longest accepted rate limit key, in UTF-16 code units. |
MaxNameLength | constant | Longest accepted limiter name. |
MaxWindow | field | Longest accepted window. |
MinWindow | field | Shortest accepted window. |
CreateResult( | method | Builds the result of an acquisition attempt in the shape every backend returns. |
CreateStatus( | method | Builds the status of a key in the shape every backend returns. |
GetWindow( | method | Gets the epoch-aligned window that now falls in for policy. |
PolicyIdentity( | method | Names the state a key keeps for policy: <, for example 10/60000ms. |
ResolveStoredWindow( | method | Resolves stored key state against the caller’s current window. |
ValidateKey( | method | Validates a rate limit key: not null, not empty, at most RateLimiterContract.characters. |
ValidateName( | method | Validates a limiter name before any backend uses it in a key prefix or a table name. |
constant MaxKeyLength #
MaxKeyLength #public const int MaxKeyLength = 512
Longest accepted rate limit key, in UTF-16 code units. Keeps a PostgreSQL key within one index entry.
constant MaxNameLength #
MaxNameLength #public const int MaxNameLength = 40
Longest accepted limiter name. Keeps every derived PostgreSQL identifier within 63 bytes.
field MaxWindow #
MaxWindow #public static readonly TimeSpan MaxWindow
Longest accepted window.
field MinWindow #
MinWindow #public static readonly TimeSpan MinWindow
Shortest accepted window.
method CreateResult(bool, RateLimitWindowState, RateLimitPolicy, DateTimeOffset) #
CreateResult(bool, RateLimitWindowState, RateLimitPolicy, DateTimeOffset) #public static RateLimitResult CreateResult(bool allowed, RateLimitWindowState state, RateLimitPolicy policy, DateTimeOffset now)
Builds the result of an acquisition attempt in the shape every backend returns.
Parameters
allowed: Whether a permit was counted.state: The effective window and its count after the attempt.policy: The policy applied.now: The caller’s time.
method CreateStatus(RateLimitWindowState, RateLimitPolicy, DateTimeOffset) #
CreateStatus(RateLimitWindowState, RateLimitPolicy, DateTimeOffset) #public static RateLimitStatus CreateStatus(RateLimitWindowState state, RateLimitPolicy policy, DateTimeOffset now)
Builds the status of a key in the shape every backend returns.
Parameters
state: The effective window and its count.policy: The policy applied.now: The caller’s time.
method GetWindow(RateLimitPolicy, DateTimeOffset) #
GetWindow(RateLimitPolicy, DateTimeOffset) #public static RateLimitWindow GetWindow(RateLimitPolicy policy, DateTimeOffset now)
Gets the epoch-aligned window that now falls in for policy.
method PolicyIdentity(RateLimitPolicy) #
PolicyIdentity(RateLimitPolicy) #public static string PolicyIdentity(RateLimitPolicy policy)
Names the state a key keeps for policy: <, for example 10/60000ms. A key keeps one window per identity.
method ResolveStoredWindow(RateLimitWindow, long?, long?, int) #
ResolveStoredWindow(RateLimitWindow, long?, long?, int) #public static RateLimitWindowState ResolveStoredWindow(RateLimitWindow current, long? storedStartMs, long? storedLengthMs, int storedCount)
Resolves stored key state against the caller’s current window. The stored window is kept when it has the same length and does not start before the current one (the window never moves backwards); otherwise the current window applies with no permits counted.
Parameters
current: The caller’s window fromRateLimiterContract..GetWindow( RateLimitPolicy, DateTimeOffset) storedStartMs: The stored window start, or null when the key has no state.storedLengthMs: The stored window length, or null when the key has no state.storedCount: The stored permit count.
Returns
The effective window and the permits already counted in it.
method ValidateKey(string) #
ValidateKey(string) #public static void ValidateKey(string key)
Validates a rate limit key: not null, not empty, at most RateLimiterContract.characters.
Parameters
key: The rate limit key.
Exceptions
Argument: The key is null.Null Exception ArgumentException: The key is empty or too long.
method ValidateName(string) #
ValidateName(string) #public static string ValidateName(string name)
Validates a limiter name before any backend uses it in a key prefix or a table name. A name is 1 to RateLimiterContract.characters from a-z, 0-9 and _, starting with a letter.
Parameters
name: The limiter name.
Returns
The validated name, unchanged.
Exceptions
Argument: The name is null.Null Exception ArgumentException: The name breaks the rule.