Rate limiting is important for any production app, but it’s not as complicated as it seems. In this post, we’ll show you how to easily set up API rate limiting using Upstash and Redis.
In this example, I'll show you how I added rate limiting to my production app, Mylinx. Which handles
Sign Up for a Free Upstash Account
Upstash is a managed service for Redis and Kafka with a serverless setup, offering a generous free tier. We'll use Upstash to implement rate limiting, as their rate limit package makes it easy to set up with any API.
Set Up Your Upstash Database
Copy the URL and Token to your .env
Adding Rate Limiting to Our API Endpoint
First, install the necessary packages:
npm install @upstash/redis @upstash/ratelimit request-ip
Next, choose the endpoint you want to protect and import the required modules:
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import requestIp from "request-ip";
Set Up Rate Limiter
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL as string,
token: process.env.UPSTASH_REDIS_REST_TOKEN as string,
});
const rateLimiter = new Ratelimit({
redis: redis,
limiter: Ratelimit.slidingWindow(60, "1m"), // s: seconds m: minutes h: hours and d: days
});
Add Rate Limiting to API Handler
import { NextApiRequest, NextApiResponse } from 'next';
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import requestIp from "request-ip";
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL as string,
token: process.env.UPSTASH_REDIS_REST_TOKEN as string,
});
const rateLimiter = new Ratelimit({
redis: redis,
limiter: Ratelimit.slidingWindow(10, "1h"),
});
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
const clientIp = requestIp.getClientIp(req) || 'default-identifier';
const { success } = await rateLimiter.limit(`${clientIp}-my-api-endpoint`);
if (!success) {
return res.status(429).json({ message: 'Rate limit exceeded, please try again later.' });
}
// Your API LOGIC HERE
return res.status(200).json({ message: 'Request successful!' });
} else {
return res.status(405).json({ message: 'Method not allowed.' });
}
}
This example provides a simple setup for rate limiting, allowing you to easily integrate it into your API endpoint.
Congratulations! You’ve successfully added rate limiting by IP to one of your endpoints.
I can't express enough how Upstash and its free tier have saved my app from collapse. With the free tier barely touched, Mylinx handles over 175K hits a month.
Top comments (0)