Skip to main content
Utility functions for working with rate limits.

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 tokens
number
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 request
Testing: Test rate limit logic without database access
Custom rate limiting logic: Build custom rate limiting on top of the calculation

Algorithm Details

For token bucket rate limits:
  1. Calculate elapsed time since last update: elapsed = now - state.ts
  2. Calculate token generation rate: rate = config.rate / config.period
  3. Add generated tokens: value = min(state.value + elapsed * rate, max) - count
  4. Update timestamp to current time: ts = now
  5. If value < 0, calculate retry time: retryAfter = -value / rate
For fixed window rate limits:
  1. Calculate elapsed windows: elapsedWindows = floor((now - state.ts) / config.period)
  2. Add tokens from new windows: value = min(state.value + rate * elapsedWindows, max) - count
  3. Update timestamp to start of current window: ts = state.ts + elapsedWindows * config.period
  4. 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 errors
Client-side error handling: Show user-friendly messages for rate limit errors
Logging and monitoring: Track rate limit events separately
Automatic retry logic: Implement exponential backoff for rate-limited requests
The 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.