Quick start
Your first rate limiter in a few lines.
Quick start
Create a limiter and run a job through it:
import { RateLimiter } from 'rate-queue';
const limiter = new RateLimiter({
maxConcurrent: 2, // only 2 jobs at a time
minTime: 500, // 500ms between starting each job
});
const result = await limiter.schedule(() => fetch('https://api.example.com/data'));
schedule returns a Promise that resolves when the job finishes. While it runs, other jobs you schedule wait in a queue and start when a slot is free and the rate limit allows.
Multiple jobs:
const [a, b, c] = await Promise.all([
limiter.schedule(() => fetch('/api/1')),
limiter.schedule(() => fetch('/api/2')),
limiter.schedule(() => fetch('/api/3')),
]);
Only 2 run at once; the third starts after one of the first two completes and 500ms has passed.
Sample: API function + schedule
Define an async function that calls your API, then run it through the limiter:
async function fetchUser(id) {
const res = await fetch(`https://api.example.com/users/${id}`);
if (!res.ok) throw new Error(res.statusText);
return res.json();
}
// Run it through the limiter — same return value
const user = await limiter.schedule(() => fetchUser(1));
With axios, you can destructure the response: const { data } = await limiter.schedule(async () => axios.request(config));
Running multiple Node instances (production)? Use the Redis-backed limiter so every instance shares the same limit.
Next: Concurrency & rate limits.