Posted by

Handling HubSpot API Rate Limits in Node.js: Retries, Backoff and Batching

Sooner or later every HubSpot integration hits the same wall: a sync job that worked perfectly in testing starts returning 429 Too Many Requests in production. The fix is rarely "make fewer calls" alone. It is a combination of understanding the limits, reading the signals HubSpot gives you, and retrying politely. This guide walks through all three in Node.js.

1. Know the limits

HubSpot enforces a burst limit (requests per 10 seconds) and a daily limit. According to HubSpot's API usage guidelines, the table below applies to privately distributed apps (legacy private apps, and apps on the latest developer platform versions with distribution set to private):

Account tierPer 10 secondsPer day
Free / Starter100 per app250,000 per account
Professional190 per app625,000 per account
Enterprise190 per app1,000,000 per account
With the API Limit Increase add-on250 per app1,000,000 more per account, on top of the base subscription

For public apps using OAuth, HubSpot states that each account that installs your app is limited to 110 requests every 10 seconds, and that this excludes the CRM Search API. The CRM Search API has its own, much tighter limit: five requests per second per account, with at most 200 records per page and 10,000 total results per query. When you exceed a limit, HubSpot returns a 429 for subsequent calls. These numbers change over time, so confirm them on the official page linked in the sources before you size a job.

2. Read the rate-limit headers

HubSpot reports your current position in response headers, so you do not need to guess:

  • X-HubSpot-RateLimit-Max: the number of requests allowed in the window
  • X-HubSpot-RateLimit-Remaining: the requests still permitted in the window
  • X-HubSpot-RateLimit-Interval-Milliseconds: the length of that window
  • X-HubSpot-RateLimit-Daily and X-HubSpot-RateLimit-Daily-Remaining: the daily allowance and what is left

Two caveats from the documentation: the daily-remaining header is not included in responses to OAuth-authorized requests, and Search API responses do not include any of these headers. Code that reads them must tolerate missing values.

A 429 response body also tells you which limit you hit. For a daily limit it looks like {"status":"error","message":"You have reached your daily limit.","errorType":"RATE_LIMIT","policyName":"DAILY"}; the policyName tells you whether it was the daily or the per-second limit.

About Retry-After: the REST API reference does not promise a Retry-After header on every 429, so treat it as optional: use it when present and fall back to your own backoff. When it is present, the HTTP standard (see MDN) allows two formats: a non-negative number of seconds, or an HTTP date. Handle both.

3. A retrying fetch wrapper

The wrapper below retries a bounded number of times, honors Retry-After in both formats, caps every wait, and otherwise uses exponential backoff with jitter. It requires Node.js 18 or newer, which includes fetch. It makes four safety choices:

  • Daily limit is not retried. Waiting a few seconds will not reset a daily quota, so a 429 with policyName: "DAILY" is returned to the caller.
  • 5xx is retried only for idempotent methods (GET, HEAD, OPTIONS, PUT, DELETE). A POST that failed with a 5xx may already have been processed, and retrying could create a duplicate. A 429 means the request was rejected for rate limiting, so it is retried for any method.
  • The body must be a string. A stream can only be read once, so it cannot be re-sent on the next attempt.
  • Waits are capped. If Retry-After asks for more than 30 seconds, the wrapper throws instead of silently sleeping for hours; your job runner can decide what to do.
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const MAX_DELAY_MS = 30_000;
const IDEMPOTENT = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);

// Retry-After is either whole seconds ("120") or an HTTP date. Returns milliseconds or null.
function retryAfterMs(value) {
  if (!value) return null;
  const v = value.trim();
  if (/^\d+$/.test(v)) return Number(v) * 1000;
  const date = Date.parse(v);
  return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
}

async function isDailyLimit(res) {
  const body = await res.clone().json().catch(() => null);
  return body?.policyName === 'DAILY';
}

async function hubspotFetch(path, options = {}, maxRetries = 5) {
  const method = (options.method ?? 'GET').toUpperCase();
  if (options.body != null && typeof options.body !== 'string') {
    throw new TypeError('Use a string body so the request can be safely re-sent.');
  }
  const url = `https://api.hubapi.com${path}`;

  for (let attempt = 0; ; attempt++) {
    const res = await fetch(url, {
      ...options,
      headers: {
        Authorization: `Bearer ${process.env.HUBSPOT_TOKEN}`,
        'Content-Type': 'application/json',
        ...options.headers,
      },
    });

    let retryable = false;
    if (res.status === 429) {
      retryable = !(await isDailyLimit(res)); // waiting seconds will not reset a daily limit
    } else if (res.status >= 500) {
      retryable = IDEMPOTENT.has(method); // a retried POST could create a duplicate
    }
    if (!retryable) return res;

    const fromHeader = retryAfterMs(res.headers.get('retry-after'));
    if (attempt >= maxRetries || (fromHeader !== null && fromHeader > MAX_DELAY_MS)) {
      const err = new Error(`HubSpot request failed (${res.status}) after ${attempt} retries`);
      err.status = res.status;
      err.retryAfterMs = fromHeader;
      throw err;
    }

    await res.arrayBuffer().catch(() => {}); // release the connection before waiting

    const ceiling = Math.min(MAX_DELAY_MS, 500 * 2 ** attempt);
    const delay = fromHeader !== null
      ? fromHeader + Math.random() * 250
      : ceiling / 2 + Math.random() * (ceiling / 2); // "equal jitter": never zero
    await sleep(delay);
  }
}

Jitter matters. If ten workers all fail at the same moment and all wait exactly one second, they will all collide again. Randomizing the delay spreads them out. The wrapper does not retry network errors (when fetch itself throws); add that only for idempotent requests if your environment needs it.

4. Slow down before you are told to

Retrying is a safety net, not a strategy. You can also watch the headers and pause proactively when the window is nearly empty. Because Search responses carry no rate-limit headers, the code treats missing headers as "no information" and does not pause:

async function politeFetch(path, options) {
  const res = await hubspotFetch(path, options);
  const num = (name) => {
    const v = res.headers.get(name);
    return v === null ? NaN : Number(v);
  };
  const remaining = num('x-hubspot-ratelimit-remaining');
  const windowMs = num('x-hubspot-ratelimit-interval-milliseconds');

  if (remaining < 5 && windowMs > 0) {
    await sleep(windowMs / 2);
  }
  return res;
}

This only throttles one call chain. If several workers share one app, they share one budget, so coordinate them with a shared queue or a concurrency limit.

5. Make fewer, bigger requests

HubSpot's usage guidelines recommend batch APIs, caching data you would otherwise request on every page load, and using webhooks instead of polling. Batch endpoints are usually the biggest win. For example, the CRM batch read endpoint fetches many contacts in one call:

const res = await hubspotFetch('/crm/v3/objects/contacts/batch/read', {
  method: 'POST',
  body: JSON.stringify({
    properties: ['email', 'firstname'],
    inputs: ids.map((id) => ({ id })),
  }),
});
const { results } = await res.json();

Check the endpoint's reference page for its maximum batch size and chunk your input accordingly. Replacing many single-record calls with a few batch calls means far fewer requests against your limits.

6. Remember that HubSpot retries too

If you build workflow webhook actions or custom code actions, HubSpot's error-handling documentation says: "Workflows will automatically retry after receiving a 429 response, and will respect the Retry-After header if present. Note that the Retry-After value is in milliseconds."

This is the opposite unit from the standard header. Standard HTTP (and MDN) defines Retry-After in seconds, but for workflow retries HubSpot reads your value as milliseconds. If your own endpoint answers a workflow with Retry-After: 5, HubSpot will read it as 5 ms, not 5 seconds; send 5000 if you want five seconds. Do not reuse this endpoint behavior with other clients that expect seconds. Separately, HubSpot documents that failed custom code actions caused by rate limiting or 5xx errors are retried for up to three days, starting one minute after the failure.

Checklist

  • Know your tier's burst and daily limits, and the Search API limit of five requests per second per account.
  • Log the X-HubSpot-RateLimit-* headers while developing, and expect them to be missing on Search and (daily) on OAuth.
  • Retry only 429 and, for idempotent methods, 5xx, with a cap, jitter and a maximum number of attempts.
  • Do not retry a daily-limit 429.
  • Prefer batch endpoints, caching and webhooks over tight polling loops.
  • Limit concurrency in your job runner so parallel workers share one budget.

Sources