Skip to content
docsv0.2.0

InMemoryRateLimiter

In-memory rate limiter using sliding window algorithm. Note: This implementation is per-process. For production with multiple workers, use RedisRateLimiter instead.

InMemoryRateLimiter::consume()

public function consume(string $key, int $cost = 1, int $windowSeconds = 60, int $maxTokens = 100): Milpa\ToolRuntime\RateLimiting\RateLimitResult

Attempt to consume tokens from this key's in-memory sliding-window bucket. Lazily resets the bucket once its window has elapsed, then denies the call when consuming would push usage past $maxTokens within the window; otherwise deducts $cost immediately. Buckets live in a process-local array, so limits are not shared across workers/processes.

Parameters

Parameters of consume()
NameTypeDescription
$keystring
$costint
$windowSecondsint
$maxTokensint

InMemoryRateLimiter::getUsage()

public function getUsage(string $key): int

Read current token usage for a key without consuming any; an expired window reads as zero.

Parameters

Parameters of getUsage()
NameTypeDescription
$keystring

InMemoryRateLimiter::reset()

public function reset(string $key): void

Discard the bucket for a key, immediately restoring its full quota.

Parameters

Parameters of reset()
NameTypeDescription
$keystring

InMemoryRateLimiter::cleanup()

public function cleanup(int $maxAge = 300): void

Cleanup expired buckets (call periodically to free memory).

Parameters

Parameters of cleanup()
NameTypeDescription
$maxAgeint