Skip to content

About

Throttles arbitrary code to execute a maximum number of times per interval. Best for making throttled API requests.

Resources

Contributing

Stars

123 stars

Watchers

0 watching

Forks

Repository files navigation

throttled-queue

Throttles arbitrary code to execute a maximum number of times per interval. Best for making throttled API requests.

For example, popular APIs such as GitHub limit how many requests you can make in a period of time. Wrap all of your API calls in a throttle, and the throttle keeps your requests within the rate limit.

The throttle functions of utility libraries such as Lodash drop executions. throttled-queue keeps every execution. It puts each execution into a queue, and drains the queue at the rate limit you set.

Installation

npm install throttled-queue

Requirements

throttled-queue supports ES modules (import) and CommonJS (require). It runs in these environments:

  • Node.js 18 or later
  • Chrome and Edge 98 or later
  • Firefox 97 or later
  • Safari 15.4 or later
  • Cloudflare Workers

In Cloudflare Workers, create the queue inside your request handler, or inside a Durable Object. Cloudflare advises against global state shared across requests. A queue in global scope stops when the request that started its timer ends.

Using in the browser

You can import throttled-queue directly in the browser, without a bundler:

<script type="module">
    import { throttledQueue, seconds } from 'https://cdn.jsdelivr.net/npm/throttled-queue@4/+esm';

    const throttle = throttledQueue({
        maxPerInterval: 5,
        interval: seconds(1),
    });
</script>

Breaking changes in 4.x

  • Node.js 18 or later is required. See Requirements.

  • The second argument of throttle is now an options object. Pass execution state as its state property:

    // 3.x
    throttle(fn, { badStatuses });
    // 4.x
    throttle(fn, { state: { badStatuses } });
  • A queue pause no longer cancels functions that are running. See Retries and pauses.

  • When several functions pause the queue, the queue resumes at the latest requested time. In 3.x, each new pause replaced the previous one, so a short pause could end a long pause early.

  • A function that retries goes to the front of the queue. In 3.x, it went to the back.

  • The queue no longer adds an internal property to your state object.

  • The context signal now aborts only when you cancel the execution. See Cancelling executions.

Usage

  1. import the factory function:

    import { throttledQueue } from 'throttled-queue';

    CommonJS require is also supported:

    const { throttledQueue } = require('throttled-queue');
  2. Create a throttled queue. Specify the maximum number of executions per interval, and the duration of the interval in milliseconds:

    const throttle = throttledQueue({
        maxPerInterval: 5,
        interval: 1000,
    }); // at most 5 requests per second.

    You can also use the seconds, minutes, and hours helpers to calculate the interval duration:

    import { throttledQueue, seconds } from 'throttled-queue';
    const throttle = throttledQueue({
        maxPerInterval: 5,
        interval: seconds(1),
    }); // at most 5 requests per second.
  3. Call throttle to enqueue a function:

    throttle(() => {
        // perform some type of activity in here.
    });

    throttle returns a promise with the result of your function:

    const result = await throttle(() => {
        return Promise.resolve('hello!');
    });
    // result now equals "hello!"

How the queue works

  • The queue starts functions in the order that you enqueue them.
  • A function uses one of the interval's executions when it starts.
  • When the interval has no executions left, the remaining functions wait for the next interval.
  • A function that retries goes to the front of the queue. It still counts toward the rate limit. Functions that retry at the same time keep the order in which you enqueued them.

Each interval is a fixed window that starts when its first function starts. Some APIs count requests in a sliding window instead. At the end of one window and the start of the next, almost twice maxPerInterval functions can start within one interval. For an API with a sliding window, use evenlySpaced.

Examples

Basic

Enqueue many network calls. The queue runs at most 1 request per second.

import { throttledQueue, seconds } from 'throttled-queue';
const throttle = throttledQueue({
    maxPerInterval: 1,
    interval: seconds(1),
}); // at most make 1 request every second.

for (let x = 0; x < 100; x++) {
    throttle(() => {
        // make a network request.
        return fetch('https://api.github.com/search/users?q=shaunpersad');
    });
}

Reusable

Every function that you pass to the same throttle goes into the same queue, and shares the same rate limit.

import { throttledQueue, minutes } from 'throttled-queue';
const throttle = throttledQueue({
    maxPerInterval: 1,
    interval: minutes(1),
}); // at most make 1 request every minute.

for (let x = 0; x < 50; x++) {
    throttle(() => {
        // make a network request.
        return fetch('https://api.github.com/search/users?q=shaunpersad');
    });
}
for (let y = 0; y < 50; y++) {
    throttle(() => {
        // make another type of network request.
        return fetch('https://api.github.com/search/repositories?q=throttled-queue+user:shaunpersad');
    });
}

Bursts

You can perform multiple executions within the given interval:

import { throttledQueue, seconds } from 'throttled-queue';
const throttle = throttledQueue({
    maxPerInterval: 10,
    interval: seconds(1),
}); // at most make 10 requests every second.

for (let x = 0; x < 100; x++) {
    throttle(() => {
        // This will fire at most 10 a second, as rapidly as possible.
        return fetch('https://api.github.com/search/users?q=shaunpersad');
    });
}

Evenly spaced

You can space out your executions. Set the evenlySpaced option to true:

import { throttledQueue, seconds } from 'throttled-queue';
const throttle = throttledQueue({
    maxPerInterval: 10,
    interval: seconds(1),
    evenlySpaced: true,
});

for (let x = 0; x < 100; x++) {
    throttle(() => {
        // This will fire at most 10 requests a second, spacing them out instead of in a burst.
        return fetch('https://api.github.com/search/users?q=shaunpersad');
    });
}

Promises

You can wait for the results of your functions:

import { throttledQueue, seconds } from 'throttled-queue';
const throttle = throttledQueue({
    maxPerInterval: 10,
    interval: seconds(1),
});

const usernames = ['shaunpersad', 'forward-motion'];
const profiles = await Promise.all(
    usernames.map((username) => throttle(() => {
        return fetch(`https://api.github.com/search/users?q=${username}`);
    })),
);

const justMe = await throttle(() => fetch('https://api.github.com/search/users?q=shaunpersad'));

Retries and pauses

You can retry a single execution, or pause the whole queue for a period of time. Both are useful when you react to status codes from an API. To retry or pause, throw a RetryError:

import { throttledQueue, seconds, RetryError } from 'throttled-queue';
const throttle = throttledQueue({
    maxPerInterval: 10,
    interval: seconds(1),
});
const result = await throttle(async () => {
    const response = await fetch('https://api.github.com/search/users?q=shaunpersad');
    if (response.status === 429) {
        // pause the queue until retryAfter.
        // if we can't tell when to retry, the queue waits for the given interval of 1 second.
        throw new RetryError({
            retryAfter: parseRetryAfter(response.headers.get('retry-after')),
            pauseQueue: true,
        });
    }
    // for all other bad statuses, we just want to retry this specific API call
    if (!response.ok) {
        throw new RetryError();
    }
    // if the response succeeded, return the result
    return response.json();
});

// The Retry-After header holds a number of seconds or an HTTP date.
function parseRetryAfter(header) {
    if (!header) {
        return null;
    }
    const delaySeconds = Number(header);
    // An invalid date gives NaN, and the queue then uses its default wait.
    return Number.isNaN(delaySeconds) ? Date.parse(header) - Date.now() : seconds(delaySeconds);
}

Pauses

When a function throws a RetryError with pauseQueue: true:

  • No function starts until the pause ends. This includes queued functions, retries, and new calls.
  • The function that paused the queue retries first when the pause ends.
  • The queue pauses even when the function that paused it has no retries left. That function's promise rejects with the RetryError.
  • Functions that are already running continue to run. The queue does not cancel them. If one of them also throws a RetryError, the queue retries it after the pause.
  • If the queue is already paused, the pause ends at the later of the two end times. A short pause never ends a long pause early.

The queue does not cancel running functions, because a cancelled request can still take effect on the server. For example, the server can complete a POST request that the client cancelled. A retry would then send the request a second time.

RetryError options

You can pass these options when you construct a RetryError. All of them are optional.

  • retryAfter: The time to wait before the retry, in milliseconds. If you do not set it, or set it to null or NaN, the queue uses the interval from the throttledQueue options. If interval is also not set, the queue uses DEFAULT_WAIT, which is 500 milliseconds.
  • pauseQueue: If true, the queue pauses for the retryAfter time. See Pauses.
  • message: An error message to attach to the error object.

Maximum retries

By default, each execution can retry at most 30 times (DEFAULT_RETRY_LIMIT) in each category. You can change these limits in the throttledQueue options:

  • maxRetries applies to a RetryError with pauseQueue set to false, or not set.
  • maxRetriesWithPauses applies to a RetryError with pauseQueue: true.

If an execution exceeds its limit, the promise rejects with the RetryError.

Dynamic queues

With RetryError, you can create a queue that is unbounded. An unbounded queue has no rate limit at the start, and runs functions as fast as possible. The queue pauses when your API returns an error:

import { throttledQueue, RetryError } from 'throttled-queue';
const throttle = throttledQueue(); // passing no options creates an "unbounded" queue, executing as fast as possible
const result = await throttle(async () => {
    const response = await fetch('https://api.github.com/search/users?q=shaunpersad');
    if (response.status === 429) {
        throw new RetryError({
            retryAfter: parseRetryAfter(response.headers.get('retry-after')), // see Retries and pauses
            pauseQueue: true,
        }); // pause the queue until retryAfter
    }
    // for all other bad statuses, we just want to retry this specific API call
    if (!response.ok) {
        throw new RetryError();
    }
    // if the response succeeded, return the result
    return response.json();
});

Execution state

Pass any object as the state option. The function gets the object in its context, and the object stays the same across all retries of that execution:

const badStatuses = [];
const result = await throttle(
    async ({ state }) => {
        const response = await fetch('https://api.github.com/search/users?q=shaunpersad');
        if (!response.ok) {
            state.badStatuses.push(response.status);
            throw new RetryError();
        }
        return response.json();
    },
    { state: { badStatuses } },
);
console.log(badStatuses); // this array now contains a log of all bad statuses received.

You can use the state object to keep any data you need between retries, for example to calculate an exponential backoff.

Cancelling executions

You can cancel an execution with an AbortSignal. Pass it as the signal option:

import { throttledQueue, seconds } from 'throttled-queue';
const throttle = throttledQueue({
    maxPerInterval: 1,
    interval: seconds(1),
});

try {
    const response = await throttle(
        ({ signal }) => fetch('https://api.github.com/search/users?q=shaunpersad', { signal }),
        { signal: AbortSignal.timeout(seconds(5)) },
    );
} catch (err) {
    if (err.name === 'TimeoutError') {
        // the execution waited or ran for longer than 5 seconds
    }
}

If the signal aborts before the execution finishes, the promise rejects with the signal's reason. The timeout includes the time in the queue, the run time, and every retry.

AbortSignal.timeout needs Chrome and Edge 124, Firefox 100, or Safari 16 and later.

Use the signal in your function

The function gets a signal in its context. Pass this signal to fetch, or to any other API that accepts an AbortSignal. The context signal aborts when one of these signals aborts:

The context signal always exists, even if you do not pass a signal. Use the context signal instead of your own signal, because only the context signal covers both cases.

Cancelling a batch

Pass the same signal to each execution in the batch:

const controller = new AbortController();

const usernames = ['shaunpersad', 'forward-motion'];
const profiles = Promise.all(
    usernames.map((username) => throttle(
        ({ signal }) => fetch(`https://api.github.com/search/users?q=${username}`, { signal }),
        { signal: controller.signal },
    )),
);

// cancel all executions in the batch
// other executions in the same queue continue
controller.abort();

Combining signals

To cancel an execution when any of several signals aborts, combine them with AbortSignal.any:

await throttle(
    ({ signal }) => fetch('https://api.github.com/search/users?q=shaunpersad', { signal }),
    { signal: AbortSignal.any([controller.signal, AbortSignal.timeout(seconds(5))]) },
);

AbortSignal.any needs Node.js 18.17, Chrome and Edge 116, Firefox 124, or Safari 17.4 and later.

When a signal aborts

When the signal aborts Result
Before you call throttle The promise rejects immediately. The function never enters the queue.
While the function waits in the queue The queue removes the function. The promise rejects immediately.
While the function runs The promise rejects immediately. The queue discards the result of the function.
While the function waits to retry The promise rejects immediately. The queue does not retry the function.
While the queue is paused The promise rejects immediately.
After the promise settles Nothing happens.

A function that waits in the queue has not used an execution, so a cancelled function does not use one. A function that already started keeps its execution, because the API already received the request.

The queue cannot stop a function that is already running. If your function ignores its signal, the function continues to run after the promise rejects.

Retries and signals

  • A signal limits the whole execution: the time in the queue, every attempt, and every wait between attempts.
  • After an execution is cancelled, the queue ignores everything that its function does. This includes a RetryError, so a cancelled execution never retries and never pauses the queue.
  • If an execution pauses the queue and is then cancelled, the pause continues. The rate limit still applies to the other executions.

To limit each attempt instead of the whole execution, create a timeout inside your function:

await throttle(async ({ signal }) => {
    const attemptSignal = AbortSignal.any([signal, AbortSignal.timeout(seconds(5))]);
    try {
        return await fetch('https://api.github.com/search/users?q=shaunpersad', { signal: attemptSignal });
    } catch (err) {
        if (err.name === 'TimeoutError') {
            throw new RetryError(); // this attempt took longer than 5 seconds, so try again
        }
        throw err;
    }
});

Cancelling the queue

To cancel every execution in a queue, pass a signal in the throttledQueue options:

import { throttledQueue, hours } from 'throttled-queue';

const quota = new AbortController();
const throttle = throttledQueue({
    maxPerInterval: 1000,
    interval: hours(24),
    signal: quota.signal,
});

async function search(query) {
    try {
        return await throttle(async ({ signal }) => {
            const response = await fetch(`https://api.example.com/search?q=${query}`, { signal });
            if (response.status === 429) {
                const reason = new Error('Daily quota reached.');
                quota.abort(reason);
                throw reason;
            }
            return response.json();
        });
    } catch (err) {
        return searchWithAnotherApi(query);
    }
}

When the queue's signal aborts:

  • Every function that waits in the queue rejects with the signal's reason.
  • Every function that runs gets an aborted context signal, and its promise rejects.
  • Every new call rejects immediately.

An aborted signal cannot be reset, so the queue stays cancelled. To start again, create a new queue.

An execution is cancelled when its own signal or the queue's signal aborts. The promise rejects with the reason of the signal that aborted first.

Waiting for the queue to finish

throttle.onIdle() returns a promise. The promise resolves when no functions wait in the queue and every promise from the queue has settled. Functions that wait for a pause or a retry count as waiting. If the queue is already idle, the promise resolves immediately.

import { throttledQueue, seconds } from 'throttled-queue';
const throttle = throttledQueue({
    maxPerInterval: 10,
    interval: seconds(1),
});

for (const url of urls) {
    throttle(() => fetch(url));
}

await throttle.onIdle();
console.log('All requests are complete.');

onIdle() resolves in the same tick as the last promise. A promise handler can still enqueue a function after that, for example throttle(a).then(() => throttle(b)). onIdle() does not wait for such a function. Call onIdle() again to wait for it.

throttle.size is the number of functions that wait in the queue. This number includes functions that wait for a pause or a retry. It does not include functions that run.

console.log(`${throttle.size} requests wait in the queue.`);

Testing with fake timers

The queue measures time with performance.now(). If your tests use fake timers, fake performance as well as setTimeout and clearTimeout. In Vitest:

vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] });

API reference

throttledQueue(options?)

Creates a queue and returns its throttle function. All options are optional.

Option Default Description
maxPerInterval Infinity The maximum number of executions per interval.
interval 0 The duration of the interval, in milliseconds.
evenlySpaced false If true, the queue spaces executions evenly across the interval.
maxRetries 30 The maximum number of retries for each execution, without pauses.
maxRetriesWithPauses 30 The maximum number of retries for each execution, with pauses.
signal none An AbortSignal that cancels the whole queue.

throttle(fn, options?)

Enqueues fn, and returns a promise with the result of fn. All options are optional.

Option Description
signal An AbortSignal that cancels this execution.
state An object that fn gets in its context. It stays the same across retries.

fn gets a context object with these properties:

Property Description
signal An AbortSignal that aborts when this execution is cancelled.
state The state option, or an empty object.
intervalStart The time that the current interval started, in milliseconds since the epoch.

throttle.size

The number of functions that wait in the queue.

throttle.onIdle()

Returns a promise that resolves when the queue is idle.

RetryError

Throw a RetryError from fn to retry the execution, or to pause the queue. See RetryError options.

RetryError.isRetryError(err)

Returns true if err is a RetryError. Use this check instead of instanceof. An app can load the ES module and CommonJS copies of throttled-queue at the same time, and instanceof fails across the two copies.

seconds(n), minutes(n), hours(n)

Convert a duration to milliseconds. Each helper accepts a number or a numeric string.

About

Throttles arbitrary code to execute a maximum number of times per interval. Best for making throttled API requests.

Resources

Contributing

Stars

123 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages