Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 16150

Upstash's Rate Limiter takes 5s to complete API call

$
0
0

i'm trying to set up the upstash rate limiter on a GET route on my own NextJS API following web dev cody video : https://www.youtube.com/watch?v=9xqlkAPnoTY (which is basically the demo code on upstash's rate limiter repo).

This is my code without the limiter, takes around 50ms to complete :

import Albums from "@models/albums";import { connectToDB } from "@utils/database";import { NextResponse } from 'next/server'export const GET = async () => {    try {        await connectToDB()        const albums = await Albums.find({})        return NextResponse.json(            albums,            { status: 200 }        )    } catch (error) {        console.log(error)        return NextResponse.json("Failed to fetch all ablums",            { status: 500 }        )    }} 

And here is the code with upstash rate limiter added, which takes around 5s to complete :

import Albums from "@models/albums";import { connectToDB } from "@utils/database";import { Ratelimit } from "@upstash/ratelimit";import { Redis } from "@upstash/redis";import { NextResponse } from 'next/server'const ratelimit = new Ratelimit({    redis: Redis.fromEnv(),    limiter: Ratelimit.slidingWindow(1, "10 s")})export const GET = async (request) => {    try {        const ip = request.headers.get("x-forwarded-for") ?? "";        const { success, reset } = await ratelimit.limit(ip);        if (!success) {            const now = Date.now();            const retryAfter = Math.floor((reset - now) / 1000);            return new NextResponse("Too Many Requests", {                status: 429,                headers: {                    ["retry-after"]: `${retryAfter}`,                },            });        }        await connectToDB()        const albums = await Albums.find({})        return NextResponse.json(            albums,            { status: 200 }        )    } catch (error) {        console.log(error)        return NextResponse.json("Failed to fetch all ablums",            { status: 500 }        )    }} 

Does anybody have an idea why it suddenly takes so long to complete API calls with the rate limiter set up ?


Viewing all articles
Browse latest Browse all 16150

Latest Images

Trending Articles



Latest Images