Sharing a Request Budget
A history importer starts fetching candles while another worker polls prices. Each worker stays below its own request limit, but both use the same outbound IP address. The exchange counts their combined traffic and starts rejecting requests.
Adding a delay inside each loop doesn't coordinate them. Neither does creating a fresh limiter for every SDK client. The budget has to cover the requests the exchange counts together, including calls from other processes and API keys.
A second problem appears when requests have different costs. Ten small ticker reads and ten deep order-book snapshots may be ten HTTP calls each, but consume very different amounts of quota. A scheduler needs the cost of the actual endpoint and parameters before it starts the request.
Counting Request Weight
Binance Spot's market-data documentation lists these weights, checked on 1 November 2026:
| Request | Parameters | Weight |
|---|---|---|
| Price ticker | One symbol | 2 |
| Order-book snapshot | limit=100 | 5 |
| Order-book snapshot | limit=1000 | 50 |
| Candles | Up to 1,000 bars | 2 |
Twenty 100-level snapshots consume 100 weight. Changing the depth to 1,000 levels makes the same twenty calls consume 1,000. A limiter that charges one unit per HTTP call cannot see that change.
The API product matters too. These are Spot endpoints under /api/v3; a Futures endpoint has its own table. Spot candle requests currently have a fixed weight of 2, so a weight formula copied from a Futures candle endpoint would be wrong here.
The window matters as much as the cost. A budget of 1,200 units per minute doesn't necessarily permit 1,200 units in one second. That example may also have a shorter burst limit. Every applicable window must allow the request, and the scheduler reserves its cost before sending it. Waiting for the response to count it leaves concurrent requests spending the same apparent capacity.
IP and Account Limits
Binance Spot request weight is counted per IP, while its unfilled-order count is account-scoped. Bybit V5 has a separate HTTP IP limit and rolling per-second API limits by UID and endpoint. One counter can't represent all of those restrictions.
For example, two workers behind the same NAT address share an IP budget even if they run on different machines. Two keys for the same account may also share an account budget. Giving each worker a copy of the full allowance doubles the traffic the exchange receives.
A single process can share one scheduler among its callers. Multiple processes need a common coordinator or explicit portions of the budget. If the counters live in Redis, checking capacity and reserving it must be atomic. Reading a counter and incrementing it in a later call recreates the same race across workers. A coordinator outage also needs a defined response; silently giving every worker a fresh full budget defeats the limit.
Queuing Requests in Node.js
A backfill job is a useful place to start because its requests can wait. The example below accepts functions that start requests, charges each call a weight, and waits until enough earlier weight has left a rolling window. It runs one task at a time and rejects additional work when the pending count reaches its limit.
This example uses a sliding window. A token bucket refills continuously and permits bursts according to its capacity; that isn't automatically equivalent to an exchange's fixed or rolling window. The implementation has to match the documented rule, or impose a more conservative local budget.
Save this as request-queue.mjs and run node request-queue.mjs. It uses a fictional budget of five units per second and logs mock requests. It doesn't connect to an exchange.
request-queue.mjs
import { setTimeout as sleep } from 'node:timers/promises';
import { performance } from 'node:perf_hooks';
export function createReadQueue({ budget, windowMs, maxPending = 100 }) {
for (const value of [budget, windowMs, maxPending]) {
if (!Number.isSafeInteger(value) || value < 1) {
throw new Error('Queue limits must be positive safe integers');
}
}
let recent = [];
let pending = 0;
let tail = Promise.resolve();
return function schedule(cost, task) {
if (!Number.isSafeInteger(cost) || cost < 1 || cost > budget) {
return Promise.reject(new Error('Invalid request cost'));
}
if (typeof task !== 'function') {
return Promise.reject(new Error('Pass a function that starts the request'));
}
if (pending >= maxPending) {
return Promise.reject(new Error('Request queue is full'));
}
pending += 1;
const result = tail.then(async () => {
while (true) {
const now = performance.now();
recent = recent.filter((entry) => now - entry.at < windowMs);
const used = recent.reduce((sum, entry) => sum + entry.cost, 0);
if (used + cost <= budget) {
recent.push({ at: now, cost });
return task();
}
const waitMs = recent[0].at + windowMs - now;
await sleep(Math.max(1, Math.ceil(waitMs)));
}
});
tail = result.catch(() => {});
return result.finally(() => { pending -= 1; });
};
}
const schedule = createReadQueue({ budget: 5, windowMs: 1_000 });
const started = performance.now();
await Promise.all([2, 2, 2, 1].map((cost, index) =>
schedule(cost, () => {
const elapsed = Math.round(performance.now() - started);
console.log(`Request ${index + 1}: cost ${cost}, started at ${elapsed} ms`);
}),
));
The first two requests spend four units and start immediately. The third needs two units, so it waits about a second. The fourth then fits in the new window. Timer scheduling can make the delay longer; the loop checks capacity again after waking.
The function argument is important. An SDK call passed as schedule(2, client.getKlines(...)) would start before the queue can delay it. The call belongs inside a function: schedule(2, () => client.getKlines(...)).
This queue keeps the reserved cost even when a task fails, since the request may have reached the exchange. A rejected task doesn't break the promise chain, so later tasks can still run. It doesn't retry requests, apply server cooldowns, or coordinate other processes. It models one local budget; an actual exchange request may need several reservations.
Each request also needs a network timeout. A stalled promise would otherwise block this serial queue indefinitely. A timeout makes a read available for retry, but doesn't prove that an order-placement request failed at the exchange.
Keeping Queued Work Useful
A delayed history page is usually still useful. A price poll queued five seconds ago may already be obsolete. Coalescing pending polls for the same symbol avoids fetching several copies of a value that will immediately replace each other.
A trading command needs a deadline and another check when it leaves the queue. An order can become unnecessary while waiting. Cancellation requests can take priority over background reads, but priority only changes which request gets available capacity next. It can't bypass an exhausted account or IP limit.
The small FIFO queue above is intended for reads. A command scheduler needs those expiry and priority rules, plus capacity reserved for urgent operations where the exchange's limits allow it. Adding more queue space doesn't solve a sustained excess of incoming work over available capacity.
Reading Exchange Feedback
The Binance and Bybit SDKs expose rate-limit information from responses. Reading it doesn't throttle later calls; the scheduler still controls when each SDK method runs.
Binance and Bybit Headers
The binance REST client retains the limit headers it last received. This public read needs no credentials:
Binance limit observations
import { MainClient } from 'binance';
const client = new MainClient();
await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' });
console.log(client.getRateLimitStates());
Those values are observations, not a reservation for the next request. Other workers may have sent traffic since the response was generated. Responses can also finish out of order, so a smaller used-weight value arriving later doesn't necessarily mean the exchange reset its counter.
Bybit's parser is enabled with parseAPIRateLimits. This authenticated read exposes the limit information for the position endpoint:
Bybit endpoint limits
import { RestClientV5 } from 'bybit-api';
const client = new RestClientV5({
key: process.env.BYBIT_API_KEY,
secret: process.env.BYBIT_API_SECRET,
parseAPIRateLimits: true,
});
const response = await client.getPositionInfo({
category: 'linear',
symbol: 'BTCUSDT',
});
console.log(response.rateLimitApi);
// { remainingRequests, maxRequests, resetAtTimestamp }
Bybit defines these headers per endpoint. Remaining capacity on a position read doesn't describe capacity for order creation. Its reset timestamp has another qualification: after a limit breach it indicates the reset time; otherwise it represents the current time. Treating every successful response as a new refill deadline can make a limiter release requests too early.
These snippets are diagnostic reads. In an application, they pass through the relevant scheduler like other requests. Missing headers leave the configured budget in force; they don't establish unlimited capacity.
Handling Rate-Limit Responses
A throttled response can mean another process consumed the shared budget, the local cost table is wrong, or the exchange is applying a different restriction. The response's HTTP status, exchange error code, and limit scope determine which queue to pause.
| Response | Handling |
|---|---|
Binance 429 | Stop affected requests and observe Retry-After. |
Binance 418 | Hold traffic from the banned IP until the ban expires. |
Bybit retCode: 10006 | Apply the API-limit cooldown to the affected UID and endpoint. |
Bybit 403 with access too frequent | Follow the documented IP-ban procedure, including its wait. |
Binance documents escalation to an IP ban when clients keep sending after rate-limit failures. Bybit's IP-limit procedure specifies at least ten minutes after its access too frequent response. Other 403 responses can have different causes, so the status alone isn't enough to choose a retry policy.
Waiting Before a Retry
A retry delay applies to every caller sharing the blocked budget. Putting one failed request to sleep while the rest of the queue continues sending doesn't respect that cooldown.
The HTTP Retry-After header can contain seconds or an HTTP date. This helper accepts seconds or the standard GMT date form and returns milliseconds. A missing or unrecognised value returns null rather than authorising an immediate retry.
Reading Retry-After
export function retryAfterMs(value, now = Date.now()) {
if (typeof value !== 'string' || value.trim() === '') return null;
const text = value.trim();
if (/^\d+$/.test(text)) {
const milliseconds = Number(text) * 1_000;
return Number.isSafeInteger(milliseconds) ? milliseconds : null;
}
// HTTP dates include a weekday and an explicit GMT timezone.
if (!/^[A-Za-z]{3}, .+ GMT$/.test(text)) return null;
const deadline = Date.parse(text);
if (!Number.isFinite(deadline) || new Date(deadline).toUTCString() !== text) {
return null;
}
return Math.max(0, deadline - now);
}
console.log(retryAfterMs('3')); // 3000
console.log(retryAfterMs(undefined)); // null
An exchange JSON field named retryAfter may use a different unit. For example, Binance's WebSocket API limit responses use a retry timestamp. That value mustn't be passed to a parser for an HTTP seconds header. Absolute deadlines also depend on an accurate clock.
When no usable deadline is available, a bounded exponential delay with jitter can space out read retries. If the server supplied a minimum wait, jitter is added after that wait, not subtracted from it. Attempts remain limited by a retry count and an overall deadline, and each retry passes through the queue again.
A lost order response needs different handling. The exchange may have accepted the order before the connection failed. Automatically submitting another order can create a duplicate, even if both attempts obey the rate limit. The unknown-outcome example covers checking the original request before deciding what to do next.
A batch can also contain both accepted and rejected operations. Retrying the whole batch without checking its individual results can repeat work that already succeeded.
Reducing REST Traffic
A market-data stream can replace repeated REST reads for quotes, trades, or order-book changes. Healthy private-stream updates can maintain the relevant account cache without a REST confirmation after every event. Initial snapshots and recovery still need the reads required by that particular feed.
WebSocket commands are a separate case. Binance's WebSocket API still consumes request weight and counts it per IP. Bybit explicitly shares the account limit between HTTP and WebSocket batch orders. Changing transports doesn't automatically create another quota.
Connections and subscriptions also have their own limits. After a disconnect, reopening many clients and starting all their backfills at once can produce a request burst. Spreading reconnect attempts and sending recovery reads through the shared scheduler keeps that work within the same budgets. WebSocket Reconnects and Backfill covers the recovery sequence.
A queue library can replace the small scheduler here once priorities, cancellation, or multiple workers are needed. Its configuration still has to describe the exchange's scopes, costs, and windows. Queue age, rejected work, observed usage, and cooldowns make it easier to see whether the problem is request volume or an incorrect limit model.
A small local check can queue mixed-cost mock reads, fail one request, and confirm that later reads still run within the budget. Retry handling can be checked with a fake Retry-After value.
Related articles
Continue from here