Rate Limiting
Learn how to add rate limiting to requests in your tRPC API
Understanding Rate Limiting
Rate limiting is a technique used to control the number of requests a user or client can make to an API within a specific time period. This helps prevent abuse, protect your server from overload, and ensure fair usage for all users.
This guide will walk you through setting up rate limiting in your tRPC API using the pre-configured Upstash Redis integration in this starter template.
Prerequisites
- An Upstash Redis account.
Setup
Obtain Upstash Redis Credentials
- Create an account on Upstash.
- Create a new Redis database in Upstash.
- Navigate to the database's "REST API" section.
- Copy the
UPSTASH_REDIS_REST_URL
andUPSTASH_REDIS_REST_TOKEN
values.
Configure Environment Variables
- Open your project's
.env
file. - Add the
UPSTASH_REDIS_REST_URL
andUPSTASH_REDIS_REST_TOKEN
environment variables, using the values you copied from Upstash:
Important: Do not commit your .env
file to your Git repository. This file contains sensitive credentials.
Apply Rate Limiting to a Procedure
The starter template includes a rateLimit
utility that you can use to apply rate limiting to your tRPC procedures.
Explanation:
- The
rateLimit
utility is pre-configured to use your Upstash Redis instance. - The
enforceUserIsAuthed
middleware checks if the user has exceeded the rate limit. - If the rate limit is exceeded, a
TOO_MANY_REQUESTS
error is thrown. - The
protectedProcedure
is pre-configured with this middleware.
Use the Rate Limited Procedure
Now you can use the protectedProcedure
in your tRPC routers to protect specific procedures.
Tips & Notes
- Customization: The rate limiting behavior (e.g., number of requests per time period) can be customized in the
utils/rateLimit.ts
file. - Error Handling: Provide informative error messages to users when they are rate limited.
- Varying Limits: Implement different rate limits for different procedures or user roles by creating multiple
rateLimit
instances with different configurations.
How is this guide?