Repository navigation
Ofetch with rate limit #80
Answered
by
ismaildasci
joaopedrodcf
asked this question in
Q&A
|
Hey everyone, What is the optimal way of creating a ofetch instance that does 10 requests max per second to prevent hitting the rate limit of a specific API? Any specific npm package that is useful for this ? Or you guys normally do a custom implementation ? Thanks 👍 |
Answered by
ismaildasci
Jan 17, 2026
Replies: 1 comment 1 reply
|
For ofetch with rate limiting, heres a clean approach using p-limit or bottleneck: Option 1: Using p-limit (simple) import { ofetch } from "ofetch";
import pLimit from "p-limit";
const limit = pLimit(10); // max 10 concurrent
const rateLimitedFetch = (url, options) => limit(() => ofetch(url, options));Option 2: Using bottleneck (more control) import { ofetch } from "ofetch";
import Bottleneck from "bottleneck";
const limiter = new Bottleneck({
maxConcurrent: 10,
minTime: 100 // 100ms between requests = 10/sec
});
const rateLimitedFetch = limiter.wrap((url, opts) => ofetch(url, opts));Option 3: Custom interceptor let lastRequest = 0;
const minInterval = 100; // 10 req/sec
const api = ofetch.create({
async onRequest({ request }) {
const now = Date.now();
const wait = minInterval - (now - lastRequest);
if (wait > 0) await new Promise(r => setTimeout(r, wait));
lastRequest = Date.now();
}
});Bottleneck is the most robust for production since it handles queuing, retries, and can persist state to Redis for distributed apps. |
1 reply
Answer selected by
joaopedrodcf
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For ofetch with rate limiting, heres a clean approach using p-limit or bottleneck:
Option 1: Using p-limit (simple)
Option 2: Using bottleneck (more control)
Option 3: Custom interceptor