StellaOps.Messaging.RateLimiting

Rate limiting for services behind a Router gateway: the limiter contract, the fixed-window rules and the limiter factory.

library
Component
Router
Licence
BUSL-1.1 (Router licence)
Target framework
net10.0
Latest release
1.0.1-20261117T070237Z

Install

dotnet add package StellaOps.Messaging.RateLimiting --version 1.0.1-20261117T070237Z

Namespaces

NamespaceTypes
StellaOps.Messaging.RateLimiting8

namespace StellaOps.Messaging.RateLimiting

TypeKindDescription
IRateLimiterinterfaceTransport-agnostic rate limiter interface.
IRateLimiterFactoryinterfaceFactory for creating rate limiter instances.
RateLimitPolicyrecordDefines a rate limit policy: at most RateLimitPolicy.MaxPermitspermits per key in each fixed, epoch-aligned window of length RateLimitPolicy.Window(see RateLimiterContract).
RateLimitResultstructResult of a rate limit acquisition attempt.
RateLimitStatusstructCurrent status of a rate limit key.
RateLimitWindowstructOne fixed rate limit window, in Unix milliseconds.
RateLimitWindowStatestructA key’s effective window and the permits counted in it.
RateLimiterContractclassThe 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

MemberKindSummary
ProviderNamepropertyGets the provider name for diagnostics (e.g., “valkey”, “postgres”, “inmemory”).
GetStatusAsync(string, RateLimitPolicy, CancellationToken)methodGets current usage for a key under policy without consuming a permit.
ResetAsync(string, CancellationToken)methodResets the rate limit counters for a key under every policy.
TryAcquireAsync(string, RateLimitPolicy, CancellationToken)methodAttempts to acquire a permit from the rate limiter under policy.

property ProviderName #

string ProviderName { get; }

Gets the provider name for diagnostics (e.g., “valkey”, “postgres”, “inmemory”).

method 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) #

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) #

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.RetryAfteris 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 to RateLimiterContract.MaxKeyLengthcharacters, compared case-sensitively.
  • 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

MemberKindSummary
ProviderNamepropertyGets the provider name for this factory.
Create(string)methodCreates a rate limiter with the specified name.

property ProviderName #

string ProviderName { get; }

Gets the provider name for this factory.

method Create(string) #

IRateLimiter Create(string name)

Creates a rate limiter with the specified name.

Parameters

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.MaxPermitspermits per key in each fixed, epoch-aligned window of length RateLimitPolicy.Window(see RateLimiterContract).

Parameters

Exceptions

  • ArgumentOutOfRangeException: A value is outside its range, at construction or in a with expression.

Members

MemberKindSummary
RateLimitPolicy(int, TimeSpan)constructorDefines a rate limit policy: at most RateLimitPolicy.MaxPermitspermits per key in each fixed, epoch-aligned window of length RateLimitPolicy.Window(see RateLimiterContract).
MaxPermitspropertyMaximum number of permits allowed within one window.
WindowpropertyThe window length.
PerHour(int)methodCreates a per-hour rate limit policy.
PerMinute(int)methodCreates a per-minute rate limit policy.
PerSecond(int)methodCreates a per-second rate limit policy.

constructor RateLimitPolicy(int, TimeSpan) #

public RateLimitPolicy(int MaxPermits, TimeSpan Window)

Defines a rate limit policy: at most RateLimitPolicy.MaxPermitspermits per key in each fixed, epoch-aligned window of length RateLimitPolicy.Window(see RateLimiterContract).

Parameters

Exceptions

  • ArgumentOutOfRangeException: A value is outside its range, at construction or in a with expression.

property MaxPermits #

public int MaxPermits { get; init; }

Maximum number of permits allowed within one window.

property Window #

public TimeSpan Window { get; init; }

The window length.

method PerHour(int) #

public static RateLimitPolicy PerHour(int maxPermits)

Creates a per-hour rate limit policy.

method PerMinute(int) #

public static RateLimitPolicy PerMinute(int maxPermits)

Creates a per-minute rate limit policy.

method 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

MemberKindSummary
CurrentCountpropertyGets the current count of permits used in the window.
IsAllowedpropertyGets whether the permit was acquired (request allowed).
RemainingPermitspropertyGets the number of remaining permits in the window.
RetryAfterpropertyGets the suggested time to wait before retrying (when denied).
Allowed(int, int)methodCreates a result indicating the permit was acquired.
Denied(int, TimeSpan)methodCreates a result indicating the request was denied.

property CurrentCount #

public int CurrentCount { get; init; }

Gets the current count of permits used in the window.

property IsAllowed #

public bool IsAllowed { get; init; }

Gets whether the permit was acquired (request allowed).

property RemainingPermits #

public int RemainingPermits { get; init; }

Gets the number of remaining permits in the window.

property RetryAfter #

public TimeSpan? RetryAfter { get; init; }

Gets the suggested time to wait before retrying (when denied).

method Allowed(int, int) #

public static RateLimitResult Allowed(int currentCount, int remainingPermits)

Creates a result indicating the permit was acquired.

method 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

MemberKindSummary
CurrentCountpropertyGets the current count of permits used in the window.
ExistspropertyGets whether the key exists (has any usage).
RemainingPermitspropertyGets the number of remaining permits in the window.
WindowRemainingpropertyGets the time remaining until the window resets.
Empty(int)methodCreates a status for a key with no usage.
WithUsage(int, int, TimeSpan)methodCreates a status for an existing key.

property CurrentCount #

public int CurrentCount { get; init; }

Gets the current count of permits used in the window.

property Exists #

public bool Exists { get; init; }

Gets whether the key exists (has any usage).

property RemainingPermits #

public int RemainingPermits { get; init; }

Gets the number of remaining permits in the window.

property WindowRemaining #

public TimeSpan WindowRemaining { get; init; }

Gets the time remaining until the window resets.

method Empty(int) #

public static RateLimitStatus Empty(int maxPermits)

Creates a status for a key with no usage.

method 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

MemberKindSummary
RateLimitWindow(long, long)constructorOne fixed rate limit window, in Unix milliseconds.
EndMspropertyWindow end (exclusive), in Unix milliseconds.
LengthMspropertyWindow length.
StartMspropertyWindow start (inclusive).
RemainingAt(DateTimeOffset)methodTime from now until the window ends; zero once it has ended.

constructor 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 #

public long EndMs { get; }

Window end (exclusive), in Unix milliseconds.

property LengthMs #

public long LengthMs { get; init; }

Window length.

property StartMs #

public long StartMs { get; init; }

Window start (inclusive).

method 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 in Window.

Members

MemberKindSummary
RateLimitWindowState(RateLimitWindow, int)constructorA key’s effective window and the permits counted in it.
CountpropertyPermits counted in Window.
WindowpropertyThe effective window.

constructor 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 in Window.

property Count #

public int Count { get; init; }

Permits counted in Window.

property 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.MaxPermitspermits 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.MaxPermitsand RateLimitPolicy.Window, named by RateLimiterContract.PolicyIdentity(RateLimitPolicy)) 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.ResetAsync(string, CancellationToken)clears the key under every policy.

Members

MemberKindSummary
MaxKeyLengthconstantLongest accepted rate limit key, in UTF-16 code units.
MaxNameLengthconstantLongest accepted limiter name.
MaxWindowfieldLongest accepted window.
MinWindowfieldShortest accepted window.
CreateResult(bool, RateLimitWindowState, RateLimitPolicy, DateTimeOffset)methodBuilds the result of an acquisition attempt in the shape every backend returns.
CreateStatus(RateLimitWindowState, RateLimitPolicy, DateTimeOffset)methodBuilds the status of a key in the shape every backend returns.
GetWindow(RateLimitPolicy, DateTimeOffset)methodGets the epoch-aligned window that now falls in for policy.
PolicyIdentity(RateLimitPolicy)methodNames the state a key keeps for policy: <max permits>/<window in milliseconds>ms, for example 10/60000ms.
ResolveStoredWindow(RateLimitWindow, long?, long?, int)methodResolves stored key state against the caller’s current window.
ValidateKey(string)methodValidates a rate limit key: not null, not empty, at most RateLimiterContract.MaxKeyLengthcharacters.
ValidateName(string)methodValidates a limiter name before any backend uses it in a key prefix or a table name.

constant 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 #

public const int MaxNameLength = 40

Longest accepted limiter name. Keeps every derived PostgreSQL identifier within 63 bytes.

field MaxWindow #

public static readonly TimeSpan MaxWindow

Longest accepted window.

field MinWindow #

public static readonly TimeSpan MinWindow

Shortest accepted window.

method 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) #

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) #

public static RateLimitWindow GetWindow(RateLimitPolicy policy, DateTimeOffset now)

Gets the epoch-aligned window that now falls in for policy.

method PolicyIdentity(RateLimitPolicy) #

public static string PolicyIdentity(RateLimitPolicy policy)

Names the state a key keeps for policy: <max permits>/<window in milliseconds>ms, for example 10/60000ms. A key keeps one window per identity.

method 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

Returns

The effective window and the permits already counted in it.

method ValidateKey(string) #

public static void ValidateKey(string key)

Validates a rate limit key: not null, not empty, at most RateLimiterContract.MaxKeyLengthcharacters.

Parameters

  • key: The rate limit key.

Exceptions

  • ArgumentNullException: The key is null.
  • ArgumentException: The key is empty or too long.

method 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.MaxNameLengthcharacters from a-z, 0-9 and _, starting with a letter.

Parameters

  • name: The limiter name.

Returns

The validated name, unchanged.

Exceptions

  • ArgumentNullException: The name is null.
  • ArgumentException: The name breaks the rule.