Handle News API Rate Limits in Node.js Without Losing Data

Kent Hudson

Kent Hudson

·

17 分钟 阅读

Handle News API Rate Limits in Node.js Without Losing Data

How to handle News API rate limits in Node.js without losing data

A rate-limit-safe Node.js API consumer detects 429 responses, reads Retry-After defensively (with a fallback when the header is absent), backs off with jittered exponential delays, persists in-flight requests in a Redis-backed queue so a process restart doesn't drop data, and routes permanent failures to a dead-letter queue instead of retrying forever. This article walks through the five-layer defense pattern that survives both transient throttling and permanent quota exhaustion in production.

Key takeaways

  • Half of rate-limit handlers assume Retry-After is in the response. It often isn't — for example, APITube's public docs as of 2026 don't enumerate rate-limit headers, so your code must read defensively and fall back to a default (e.g. 30 s).
  • In-memory queues drop articles on deploy or crash. Production needs durable storage — BullMQ + Redis is the standard Node.js pattern.
  • Don't retry forever. Bound maxAttempts to 5, route permanent failures to a dead-letter queue, and add a circuit breaker for sustained 429 streams.
  • Pick the pattern by load shape: one-shot scripts get axios-retry; single-process pollers get p-queue; multi-instance workers get BullMQ.

This article is for backend developers running production Node.js workloads against rate-limited APIs — particularly news APIs polled at high volume where dropping articles costs you data, not just latency.

The problem: 429 in production drops articles you can't get back

You're polling a news API every 30 seconds for fresh articles. Things work fine until a big-news day spikes your volume, you hit the 30-requests-per-30-minutes free-tier ceiling, and the API starts returning HTTP 429.

Your retry logic kicks in — except it retries immediately, which trips the limiter again. After a few rounds, your in-memory request queue has 200 backlogged calls. Then a deploy happens, the process restarts, and that queue evaporates. The articles published during those 30 seconds are gone unless you can replay the news feed (most APIs let you, but only if your code asked for the right published_at window — and yours probably didn't).

This is the data-loss path that generic "handle 429" articles skip. Backoff alone doesn't fix it. The fix is a five-layer defense, and each layer solves a different failure mode.

Why it happens: rate limit algorithms and naive retry storms

HTTP 429 Too Many Requests is the status code an API server returns when a client exceeds the configured rate limit. Defined in RFC 6585 and refined in RFC 9110 §15.5.29; the response should include a Retry-After header indicating when a retry is acceptable, though many APIs omit it in practice.

APIs rate-limit using one of three algorithms:

  • Fixed window (e.g. 30 req per minute, resetting at the top of each minute) — bursty around the boundary
  • Sliding window (rolling 60 s evaluated continuously) — smoother but less predictable
  • Token bucket (N tokens, refill rate R per second, burst capacity B) — allows controlled bursts

APITube's free-tier "30 requests per 30 minutes" is most likely a sliding-window or fixed-window implementation; the docs don't specify and headers aren't documented either.

The naive failure mode is the thundering herd: you (and every other client) hit a 429, immediately retry, the limiter sees a synchronized burst, refuses again, and so on. Without jitter on the retry delay, multiple clients (or even multiple worker threads in the same process) lock-step their retries forever. This is why "exponential backoff with jitter" is the entry-level fix, not a complete one.

Solutions: 5 layers of rate-limit defense

The minimum viable production stack:

  1. Respect Retry-After when present (with defensive parsing)
  2. Exponential backoff with jitter when the header is absent
  3. Queue with Redis persistence so backlog survives restart
  4. Bounded retries + dead-letter queue for permanent failures
  5. Circuit breaker for sustained failure streams

Layer 1 — Respect Retry-After (with defensive parsing)

Retry-After per RFC 9110 can be either an integer (seconds) or an HTTP-date. Your parser needs both — and a fallback for when the header is missing or unparseable.

function parseRetryAfter(headerValue, defaultSeconds = 30) {
  if (!headerValue) return defaultSeconds * 1000;

  // Try integer seconds
  const asInt = parseInt(headerValue, 10);
  if (!isNaN(asInt) && asInt >= 0) return asInt * 1000;

  // Try HTTP-date
  const asDate = Date.parse(headerValue);
  if (!isNaN(asDate)) {
    const ms = asDate - Date.now();
    return Math.max(ms, 0);
  }

  return defaultSeconds * 1000;
}

The 30-second default is a reasonable fallback — long enough to clear most fixed-window ceilings, short enough to not stall the pipeline.

Quotable: A 30-second Retry-After fallback clears most 30-req-per-30-min sliding-window limits (including APITube's free tier) without wasting throughput. Match it to your API's documented limit when known; never throw on missing headers.

Defensive header reading: Retry-After, X-RateLimit-Remaining, and X-RateLimit-Reset are not part of any HTTP standard's required behavior. Many news APIs (APITube as of 2026 docs included) don't publicly document which they expose. Always parse with a fallback; never throw on missing headers.

Layer 2 — Exponential backoff with jitter

When Retry-After is absent, fall back to exponential backoff with full jitter (the AWS-recommended variant that prevents synchronized retries):

Exponential backoff is a retry strategy that doubles the delay between attempts after each failure: delay = base × 2^attempt. It gives an overloaded server time to recover and prevents the immediate-retry storm that worsens rate limits.

delay = random(0, base * 2^attempt)

Where base is your minimum delay (e.g. 1000 ms) and attempt is the zero-indexed retry number.

function backoffWithJitter(attempt, base = 1000, cap = 30_000) {
  const exp = Math.min(base * 2 ** attempt, cap);
  return Math.floor(Math.random() * exp);
}

Jitter is randomization added to backoff delays to prevent multiple clients from synchronizing retries and creating a thundering herd. Full jitter — random(0, max_delay) — outperforms equal jitter on burst-recovery benchmarks (AWS Architecture Blog, "Exponential Backoff and Jitter").

Cap the delay at 30 seconds so a wedged client doesn't sleep for an hour after 11 retries. Full jitter (random between 0 and the exponential cap) outperforms equal jitter (cap/2 + random(0, cap/2)) on synchronized-burst scenarios.

Layer 3 — Queue with Redis persistence (BullMQ)

In-memory queues are why "handled rate limits" still lose data. Use BullMQ with Redis so the backlog survives a restart, deploy, or crash.

import { Queue, Worker } from 'bullmq';
import IORedis from 'ioredis';

const connection = new IORedis(process.env.REDIS_URL);
const queue = new Queue('news-fetch', { connection });

// Producer: enqueue a fetch job
await queue.add('fetch', { entity: 'tesla', since: '2026-05-02T08:00:00Z' }, {
  attempts: 5,
  backoff: { type: 'exponential', delay: 2000 },
  removeOnComplete: { count: 100 },
  removeOnFail: { count: 1000 },   // dead-letter retention
});

attempts: 5 is the bounded-retry layer (next section). backoff: { type: 'exponential', delay: 2000 } lets BullMQ handle the jittered delay between retries. removeOnFail: { count: 1000 } keeps the last 1,000 failed jobs around as the dead-letter queue.

Unlike in-memory queues, a Redis-backed BullMQ queue persists job state across process restarts, which means a deploy in the middle of a backlog reload doesn't drop the queued requests. Workers pick up where the previous instance left off.

Layer 4 — Bounded retries + dead-letter queue

Permanent 429s exist: monthly quota exhaustion, revoked API keys, or rotated credentials. Retrying these forever is worse than failing fast.

const worker = new Worker('news-fetch', async (job) => {
  const { entity, since } = job.data;
  try {
    const res = await axios.get('https://api.apitube.io/v1/news/everything', {
      params: { 'entity.id': entity, 'published_at.start': since },
      headers: { 'X-API-Key': process.env.APITUBE_KEY },
      timeout: 15_000,
    });
    return res.data;
  } catch (err) {
    if (err.response?.status === 429) {
      const wait = parseRetryAfter(err.response.headers['retry-after']);
      throw new Error(`429: retry after ${wait}ms`);   // BullMQ retries with backoff
    }
    throw err;
  }
}, { connection, concurrency: 2 });

worker.on('failed', (job, err) => {
  if (job.attemptsMade >= job.opts.attempts) {
    // Permanent failure → already in DLQ via removeOnFail retention
    console.error(`DLQ: ${job.name} ${job.id} after ${job.attemptsMade} attempts:`, err.message);
    // Optionally: alert ops, page on-call, etc.
  }
});

After attempts: 5 exhausts (with BullMQ's exponential backoff between attempts), the job lands in the failed-jobs set. worker.on('failed', ...) is your hook to alert, log, or batch-replay later. Infinite retry is worse than failing fast — a dead-letter queue with human review beats a retry loop that DDoSes a quota-exhausted endpoint.

Layer 5 — Circuit breaker for sustained failures

When 5 consecutive 429s fire within a minute, opening a circuit breaker for ~60 s is cheaper than letting every request hit the wall. The opossum library is the standard Node.js implementation:

import CircuitBreaker from 'opossum';

const breaker = new CircuitBreaker(fetchNews, {
  timeout: 15_000,
  errorThresholdPercentage: 50,   // open after 50% failures
  resetTimeout: 60_000,           // try again after 60s
});

breaker.on('open', () => console.warn('Circuit OPEN — pausing requests for 60s'));
breaker.on('halfOpen', () => console.info('Circuit half-open — testing'));

Backoff slows the next request; a circuit breaker stops all requests for a window. They solve different problems and you usually want both — backoff in the inner retry loop, circuit breaker around the whole fetch call.

Best practice: pick a pattern by use case

Don't over-engineer a one-shot script with Redis. Don't under-engineer a multi-instance worker pool with setTimeout. Match the pattern to the load shape:

Use casePatternStackPersistence
One-shot script (CLI, cron)axios-retry with Retry-Afteraxios + axios-retryNone needed
Single-process polling (one container)p-queue + axios-retryp-queue + axios-retryIn-memory (lossy on crash)
Multi-instance fan-out (3+ workers)BullMQ + Redis + circuit breakerbullmq + ioredis + opossumRedis (survives crashes)

Production news polling at any meaningful volume is the third row. Anything less than BullMQ + Redis means data loss is a question of when, not if.

Complete code (BullMQ + axios + APITube)

A full worker that respects Retry-After, queues with persistence, retries with bounded attempts, and routes failures to a DLQ:

import axios from 'axios';
import { Queue, Worker } from 'bullmq';
import IORedis from 'ioredis';

const connection = new IORedis(process.env.REDIS_URL, { maxRetriesPerRequest: null });
const queue = new Queue('news-fetch', { connection });

function parseRetryAfter(v, def = 30) {
  if (!v) return def * 1000;
  const i = parseInt(v, 10);
  if (!isNaN(i) && i >= 0) return i * 1000;
  const d = Date.parse(v);
  if (!isNaN(d)) return Math.max(d - Date.now(), 0);
  return def * 1000;
}

async function fetchNews({ entity, since }) {
  const r = await axios.get('https://api.apitube.io/v1/news/everything', {
    params: { 'entity.id': entity, 'published_at.start': since, 'per_page': 100 },
    headers: { 'X-API-Key': process.env.APITUBE_KEY },   // disclosure: I work on APITube
    timeout: 15_000,
    validateStatus: (s) => s < 500,   // let us handle 429 explicitly
  });
  if (r.status === 429) {
    const wait = parseRetryAfter(r.headers['retry-after']);
    const err = new Error(`429 from APITube; retry after ${wait}ms`);
    err.retryAfterMs = wait;
    throw err;
  }
  if (r.status >= 400) throw new Error(`HTTP ${r.status}`);
  return r.data.results;
}

const worker = new Worker('news-fetch', async (job) => {
  return fetchNews(job.data);
}, { connection, concurrency: 2 });

worker.on('failed', (job, err) => {
  if (job.attemptsMade >= job.opts.attempts) {
    console.error(`[DLQ] ${job.name}#${job.id} permanent failure:`, err.message);
  }
});

// Producer: schedule periodic fetches per competitor entity
const ENTITIES = ['tesla', 'rivian', 'openai'];
setInterval(() => {
  for (const entity of ENTITIES) {
    queue.add('fetch', { entity, since: 'now-5m' }, {
      attempts: 5,
      backoff: { type: 'exponential', delay: 2000 },
      removeOnComplete: { count: 100 },
      removeOnFail: { count: 1000 },
    });
  }
}, 5 * 60 * 1000);

That's a deployable polling pipeline in under 60 lines: persistent queue, defensive Retry-After parsing, bounded retries with exponential backoff, DLQ for permanent failures. Wrap fetchNews in opossum for the fifth layer.

News-specific tuning

News polling has unique characteristics that change the numbers:

  • Use an incremental cursor — set published_at.start to the last-seen timestamp on every poll, not a fixed 24-hour window. Cuts duplicate work and reduces rate-limit pressure.
  • Prioritize fresh, drop stale — when the queue depth exceeds (e.g.) 500, prefer the newest articles and let older ones drop or move to a low-priority lane. Editorial value of a 6-hour-old article is roughly zero.
  • Tune intervals to your urgency — alerts on Tier 1 sources can wait 30 seconds; intra-day digests can wait 5 minutes; weekly reports tolerate hours. Set the polling cadence per use case, not per "news API".

常见问题

What is HTTP 429?

HTTP 429 Too Many Requests is the status code an API returns when a client exceeds the documented or undocumented rate limit. Per RFC 6585, a 429 response should include a Retry-After header indicating when to retry — though in practice many APIs omit it. Treat 429 as a transient throttling signal that may also indicate permanent quota exhaustion.

How do you handle rate limits in Node.js?

Handle rate limits in Node.js by parsing Retry-After defensively (fall back to ~30 seconds when missing), backing off with jittered exponential delays, queueing pending requests in a Redis-backed BullMQ queue so they survive process restarts, bounding retries to ~5 attempts, and routing permanent failures to a dead-letter queue for manual review or batch replay.

What is exponential backoff?

Exponential backoff is a retry strategy that doubles the wait time between attempts — typically delay = base × 2^attempt — to give an overloaded server time to recover. Production implementations add jitter (randomness) to prevent multiple clients from synchronizing their retries and creating a thundering herd that re-overloads the server immediately.

Should you retry on 429?

Yes, but with bounded attempts and exponential backoff. Set maxAttempts to 5, respect Retry-After when present, and route still-failing jobs to a dead-letter queue for human review. Some 429s are permanent (monthly quota exhausted, revoked API key); retrying forever just wastes compute and worsens the limiter for everyone.

Try it

Need an API to test these patterns against? APITube returns 429 reliably on the free plan after 30 requests per 30 minutes — perfect for testing your retry/queue setup before production. Get a key at apitube.io and point the BullMQ worker above at /v1/news/everything.

资源

Related guides:

APITube - News API

相关文章

How to Cache News API Responses for Better Performance
Developer Guides

How to Cache News API Responses for Better Performance

Cache news API responses with content-aware TTLs (30s breaking, 5 min headlines, 1h archive), Redis SWR, and breaking-news bypass. Code included.

Stock News Alert System with Node.js: 2026 Tutorial
Developer Guides

Stock News Alert System with Node.js: 2026 Tutorial

Build a Node.js stock news alert system in one evening: poll APITube, dedupe, gate by sentiment, send Slack alerts. Full code + API comparison.

News API Pagination: Cursor, Offset & the 10k Cap
Developer Guides

News API Pagination: Cursor, Offset & the 10k Cap

Stop losing articles between pages. A consumer-side guide to news API pagination: date-window slicing, 429 retries, async streaming, and dedup.

Real-time news alerts with WebSockets (Socket.IO 2026)
Developer Guides

Real-time news alerts with WebSockets (Socket.IO 2026)

Build real-time news alerts with WebSockets in Node.js using Socket.IO 4.8 and APITube SSE. Room filters, reconnect, Redis adapter, full code.

我们使用 Cookie

点击“接受”即表示您同意在您的设备上使用 Cookie,以使网站正常运行并用于分析。