Utility functions for working with rate limits.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/get-convex/rate-limiter/llms.txt
Use this file to discover all available pages before exploring further.
calculateRateLimit
Calculate rate limit values based on the current state and configuration. This function is exported so it can be used in both client and server code.Parameters
The existing rate limit state, or
null if this is the first request.The rate limit configuration. See RateLimitConfig.
The current time in milliseconds. Defaults to
Date.now().The number of tokens to consume. Defaults to 0 (just check, don’t consume).
Returns
An object containing the calculated rate limit state:The number of tokens remaining after consuming
count tokensThe updated timestamp for this state
If the rate limit would be exceeded, this is the duration in milliseconds to wait before retrying.
undefined if the request is allowed.For fixed window rate limits, the start time of the current window.
undefined for token bucket rate limits.Use Cases
Client-side prediction: Calculate expected rate limit state before making a requestAlgorithm Details
Token Bucket Algorithm
Token Bucket Algorithm
For token bucket rate limits:
- Calculate elapsed time since last update:
elapsed = now - state.ts - Calculate token generation rate:
rate = config.rate / config.period - Add generated tokens:
value = min(state.value + elapsed * rate, max) - count - Update timestamp to current time:
ts = now - If
value < 0, calculate retry time:retryAfter = -value / rate
Fixed Window Algorithm
Fixed Window Algorithm
For fixed window rate limits:
- Calculate elapsed windows:
elapsedWindows = floor((now - state.ts) / config.period) - Add tokens from new windows:
value = min(state.value + rate * elapsedWindows, max) - count - Update timestamp to start of current window:
ts = state.ts + elapsedWindows * config.period - If
value < 0, calculate windows needed and retry time
isRateLimitError
Type guard function to check if an error is a rate limit error.Parameters
The error to check
Returns
true if the error is a ConvexError with data.kind === "RateLimited", false otherwise.
When true, TypeScript will narrow the type to { data: RateLimitError }.
Use Cases
Error handling in mutations: Handle rate limit errors differently from other errorsThe
isRateLimitError function checks for errors thrown when using throws: true in rate limit operations. If you’re not using throws: true, check the ok field in the return value instead.