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
{ value: number; ts: number } | null
required
The existing rate limit state, or
null if this is the first request.RateLimitConfig
required
The rate limit configuration. See RateLimitConfig.
number
default:"Date.now()"
The current time in milliseconds. Defaults to
Date.now().number
default:"0"
The number of tokens to consume. Defaults to 0 (just check, don’t consume).
Returns
An object containing the calculated rate limit state:number
required
The number of tokens remaining after consuming
count tokensnumber
required
The updated timestamp for this state
number | undefined
required
If the rate limit would be exceeded, this is the duration in milliseconds to wait before retrying.
undefined if the request is allowed.number | undefined
required
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
unknown
required
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.