Skip to main content

The Problem

Users sending messages too quickly can spam your application. You need to limit message frequency per user while allowing occasional bursts of legitimate activity.

Solution: Per-User Token Bucket

Use a per-user rate limit with a token bucket strategy. This allows steady messaging (10 per minute) while permitting short bursts when users haven’t been active.

Configuration

convex/rateLimits.ts
How it works:
  • Tokens refill at 10 per minute (one every ~6 seconds)
  • Maximum 3 tokens can accumulate
  • Each message consumes 1 token
  • If user hasn’t sent messages recently, they can send 3 quickly

Implementation

Backend Mutation

convex/messages.ts

Query to Check Rate Limit Status

convex/messages.ts

Client-Side Integration

With React Hook

First, set up the hook API:
convex/messages.ts
Then use it in your component:
src/MessageInput.tsx

Manual Error Handling

src/MessageInputSimple.tsx

Testing the Rate Limit

convex/test.ts

Common Variations

Capacity vs Rate: The capacity determines burst size, while rate controls sustained throughput. A capacity of 3 with rate of 10/minute means users can send 3 messages instantly, then must wait ~6 seconds between subsequent messages.
Use the React hook (useRateLimit) to show real-time feedback in your UI. This prevents users from hitting the rate limit and seeing errors.