Most API and webhook integration bugs are not caused by the API you are calling. They come from the parts around it: a webhook processed twice, a retry storm after a timeout, a payload that changed shape, or a rate limit nobody planned for. This developer guide lists the patterns that keep integrations reliable and points you to a focused Node.js tutorial for each one.
Quick answer: This guide covers the seven habits of a reliable integration: verify signatures, acknowledge fast, handle duplicates, validate payloads, retry with backoff, respect rate limits and keep failed events for replay. If you are new to webhooks, start with signature verification and local testing, then add a queue for retries.
- Decide whether the job needs webhooks, polling or both.
- Get a public URL for local testing and verify every signature.
- Validate the payload, return a 2xx fast and do the work in a background job.
- Retry failed outgoing calls with exponential backoff and jitter.
- Queue outgoing calls so you stay under the provider’s rate limit.
In this guide
Webhooks or Polling: Pick the Right Direction
An API call is you asking a service for data. A webhook is the service calling you when something happens. They suit different jobs:
- Webhooks fit events you need to react to quickly: a payment succeeded, a form was submitted, a contact was updated. You do not waste requests asking “anything new?”
- Polling fits services with no webhooks, or cases where you need a complete, ordered picture and cannot risk a missed delivery. If you poll from a spreadsheet, see how to fetch paginated API data in Google Apps Script.
- Both together is the most dependable setup: handle webhooks in real time, and run a scheduled reconciliation job that fetches recent records to catch anything that was dropped.
The Reliability Checklist for a Webhook Endpoint
Work through these in order. Each item links to the tutorial that builds it.
- Verify the signature. Anyone can send a POST to a public URL. Compute an HMAC over the raw request body with your shared secret and compare it to the signature header in constant time. Tutorial: verify webhook signatures with HMAC in Node.js.
- Acknowledge fast, work later. Most providers time out after a few seconds and then retry. Return a 2xx as soon as the request is verified and stored, then do the slow work in a background job. If one event must reach several services, see how to route webhooks to multiple endpoints.
- Make handlers idempotent. Idempotent means processing the same event twice has the same effect as processing it once. Retries make duplicates normal, so store the event ID and skip anything you have already processed. When two copies arrive at the same moment, a Redis distributed lock stops both from running at once.
- Validate the payload. Check the shape of incoming data against a schema before your code trusts it. Tutorial: validate webhook payloads with Zod in Express.
- Retry outgoing calls with backoff. When your own call fails, wait longer between each attempt and add random jitter so many clients do not retry at the same instant. Tutorial: build a webhook retry system with exponential backoff.
- Respect rate limits. On a 429 response, read the
Retry-Afterheader and queue the work instead of hammering the API. Tutorial: handle external API rate limits with BullMQ and Redis. - Log enough to replay. Keep the raw payload and headers for failed events so you can re-run them after a fix. A Redis Streams event processor keeps events until a worker confirms them.
Example: Verifying a Webhook Signature in Express
The detail that trips most people up is the body parser. The signature is calculated over the exact bytes that were sent, so you must read the raw body on that route rather than the parsed JSON object.
The example below is the receiving route of a Node.js Express app. It uses import syntax, so save it in a .mjs file or set "type": "module" in package.json, and set WEBHOOK_SECRET in your environment.
import crypto from 'node:crypto';
import express from 'express';
const app = express();
// express.raw keeps the body as a Buffer so the HMAC matches what the sender signed.
app.post('/webhooks/provider', express.raw({ type: 'application/json' }), (req, res) => {
// The header name and encoding differ per provider - check their docs.
const signature = req.get('X-Signature') ?? '';
const expected = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
const valid =
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
if (!valid) {
return res.status(401).send('Invalid signature');
}
const event = JSON.parse(req.body.toString('utf8'));
// Acknowledge first, then hand the event to a queue or background worker.
res.sendStatus(202);
handleEventLater(event);
});timingSafeEqual throws if the two buffers have different lengths, which is why the length check comes first. handleEventLater stands for whatever you use to process work outside the request: a job queue, a database table that a worker reads, or a message stream.
Testing Webhooks on Your Own Machine
A provider cannot reach localhost, so you need a public URL that forwards to your development server. A tunnel gives you that without deploying; the tutorial on how to test webhooks locally with Cloudflare Tunnels sets one up for free.
Keep one saved sample payload per event type in your repository as well. Then you can replay it with curl and write tests without waiting for the real service to fire. To watch deliveries arrive live while you build, stream webhooks to your browser with SSE.
Tutorials in This Guide
Each tutorial below covers one of the patterns above with complete code.
- Build a Webhook Retry System with Exponential Backoff in Node.jsBuild a webhook retry system in Node.js with BullMQ and Redis: exponential backoff with jitter, a capped delay, a dead-letter list and event IDs to dedupe.
- How to Build an OTP Verification System with Redis and Node.jsOTP verification with Redis and Node.js: codes that expire on their own, a resend cooldown, a 3-attempt limit and constant-time checks, tested with curl.
- How to Handle External API Rate Limits with BullMQ and RedisStop 429 errors: throttle outgoing API calls in Node.js with a BullMQ rate limiter on Redis, and pause the queue for Retry-After when a 429 still arrives.
- How to Route Webhooks to Multiple Endpoints in Node.jsRoute one webhook to multiple endpoints in Node.js: reply 202 at once, forward in parallel with Promise.allSettled and isolate each failing target.
- Redis Caching Tutorial: Speed Up Node.js API ResponsesAdd Redis caching to a Node.js Express API with a reusable middleware, a TTL on every key, invalidation on updates and curl tests that confirm cache hits.
- Redis Distributed Lock in Node.js: Prevent Race ConditionsBuild a Redis distributed lock in Node.js with ioredis: SET NX PX to acquire, a Lua script to release safely, and a test that proves it stops a race.
- Redis Pub/Sub Event Broker in Node.js: Step-by-Step GuideBuild a Redis Pub/Sub event broker in Node.js with ioredis: separate publisher and subscriber connections, reconnect handling and pattern subscriptions.
- Redis Sliding Window Rate Limiter in Node.jsBuild a Redis sliding window rate limiter for Express in Node.js with sorted sets and an atomic Lua script, then test the 429 responses with a curl loop.
- Redis Streams Node.js: Build a Real-Time Event ProcessorBuild a Redis Streams event processor in Node.js: XADD events, read them with a consumer group, XACK on success and reclaim messages from crashed workers.
- Stream Webhooks to Your Browser in Real-Time with SSE and Node.jsStream webhooks to your browser in real time with Server-Sent Events and Node.js: an Express SSE endpoint, a live dashboard page and curl tests.
- Test Webhooks Locally with Cloudflare TunnelsTest webhooks locally with a free Cloudflare Tunnel: a public URL for localhost in one command, then a permanent hostname on your domain, tested with curl.
- Validate Webhook Payloads with Zod in ExpressValidate webhook payloads with Zod 4 in Express: define a schema, add a middleware that returns a clear 400, test with curl and check signatures first.
- Verify Webhook Signatures with HMAC in Node.jsVerify webhook signatures with HMAC in Node.js: keep the raw body, recompute HMAC-SHA256, compare with timingSafeEqual and block replays with a timestamp.
Frequently Asked Questions
What is the difference between an API and a webhook?
An API call is a request you send; a webhook is a request the service sends to you. With an API you ask for data when you want it. With a webhook the provider POSTs an event to your URL as soon as something happens, so you react without polling.
Why does my webhook endpoint receive the same event twice?
Because providers retry when they do not get a fast 2xx response, and some deliver at least once by design. A slow handler, a timeout or a network error all cause repeats. Store each event ID, skip IDs you have already processed, and return 2xx before doing slow work.
How do I test webhooks without deploying?
Run a tunnel that gives your local server a public HTTPS URL, and paste that URL into the provider’s dashboard. Cloudflare Tunnel and similar tools forward each request to your machine, so you can set breakpoints and read logs. Saved sample payloads replayed with curl cover the rest.
Where to Go Next
Start with the HMAC signature tutorial if your endpoint is already public, because an unverified endpoint accepts anyone’s data. If your integration starts from a spreadsheet instead of a server, see the Google Apps Script automation guide. If you want to run the workers, queues and automation tools yourself, continue with the self-hosted tools guide.

