-- online Search!

APIs and Webhooks

by kirupa   | filed under Build Essentials

TL;DR

When our server needs something from another company's app, it sends a request in a shape that app has published and promised to answer. That list of requests is called an API. When the other app has news for us, it can call a URL on our server instead. That push is a webhook, and it can arrive twice.

  • A request carries a method, a URL, a JSON body, and a secret key. Anyone holding that key can act as us, so it stays on our server, never in browser code or in Git.
  • Send too many requests, and the provider answers 429 Too Many Requests, often with a Retry-After header. Wait that long, then try again.
  • Asking over and over (polling) is like walking to the mailbox. A webhook is a doorbell: a signed HTTP POST to our URL the moment something happens.
  • Webhooks are delivered at least once, so the same event can show up twice or out of order. Record each event ID, make the work safe to repeat, and answer with a 2xx fast.

This year, Crumb & Co. started taking holiday pie pre-orders on our website. A customer picks a pie, pays a $10 deposit, and gets an email that says Your pie is confirmed! On the second morning, one customer got that email twice, and Odette, who runs our kitchen, found two tickets for the same pecan pie. She baked both of them.

Nobody clicked anything twice, and nothing crashed. In this article, we'll look at how our website talks to the company that takes our payments, how that company tells us a payment went through, and how to make sure a message that shows up twice still bakes just one pie.

Onwards!

How Our Website Talks to the Payment Provider

Wren, our web developer, didn't build a payment system for the bakery. Card numbers and fraud checks are a whole job, so our website hands them to a payment provider.

Here is what happens when someone pre-orders a pie:

A customer's phone shows the Crumb & Co. pre-order page: Pecan pie, pickup Nov 24, $10 deposit, and a Pay $10 button. Step 1: the phone sends the pecan pie order to the Crumb & Co. server. Step 2: the Crumb & Co. server asks the payment provider to start a $10 payment. Step 3: the phone sends the card details straight to the payment provider. Step 4: the payment finishes at the provider, shown with a check mark and the word Paid. A handwritten note under the Crumb & Co. server asks: Did they pay yet?

In step 3, our customer types their card details into the provider's form, so the card number never touches our server. Step 4 happens entirely at the provider, and our server has no idea when. We'll come back to that.

First, let's zoom in on step 2, where our server sends the provider a request and gets back a response:

The Crumb & Co. server on the left and the payment provider on the right. An arrow carries a request from Crumb & Co. to the provider: POST /v1/payments (the method and URL), Authorization: Bearer sk_•••• (the secret key), and a JSON body with amount 1000 and order order_311. An arrow back carries the response: 200 OK (the status code) and a JSON body with id pay_8K2 and status pending.

POST is the method, and it asks the provider to create something. The URL says what to create, and the JSON body carries the details (the amount is 1000 because a lot of providers count money in cents). The response has a status code, where 200 means it worked, and an ID for our new payment.

Our provider publishes every request it will answer and the exact shape each one takes. That published list is called an API (short for application programming interface). Making HTTP/Web Requests in JavaScript shows the code side, and GraphQL: Going Beyond REST APIs compares this style of API with GraphQL.

The Secret Key and the Speed Limit

The Authorization line carries a secret key that the provider gave Wren when the bakery signed up. The key tells the provider which business is asking, and anyone holding it can charge cards and issue refunds as us. There is exactly one good place for our key to live:

Three places our secret key could live. On our server: the Crumb & Co. server sits next to a padlock with a key, with a check mark and the words Only our server sees it. In browser JavaScript: a browser window shows the line key = "sk_••••" with a pair of eyes looking at it, a red X, and the words Every visitor gets a copy. Committed to Git: a list of three commits, Add checkout, Add the key, and Remove the key, with the key still sitting in the middle commit, a red X, and the words Still in the history.

Every visitor gets a copy of our browser JavaScript, along with any key inside it. A key committed to Git stays in the history even after a later commit deletes it, which Git and Version Control explains. Stripe's API keys guide says to keep keys out of version control too.

Our provider also has a speed limit. If we send too many requests too quickly, it answers with 429 Too Many Requests, often along with a Retry-After header that says how long to wait:

Crumb & Co. sends POST /v1/payments three times in a row. The payment provider answers 200 OK, 200 OK, and then 429 Too Many Requests with Retry-After: 30. An hourglass shows Crumb & Co. waiting 30 seconds, and a fourth POST /v1/payments gets 200 OK.

Our server will wait the 30 seconds and try again. This time, it works. Without a Retry-After, we wait a little longer after each failure, because retrying right away just earns us another 429.

Are We Paid Yet?

Let's go back to step 4. The moment the payment finishes is our cue to email the customer and print a ticket for Odette's kitchen. How will our server find out?

Wren's first idea was to keep asking, every 5 minutes:

Two lanes over time, Crumb & Co. on top and the payment provider below. At 9:00, 9:05, 9:10, and 9:15, Crumb & Co. sends a request asking Paid yet?. The provider answers No, No, No, and then Yes!. The payment actually finished at 9:12, marked with a green check. A bracket from 9:12 to 9:15 is labeled 3 minutes late!

Three of our four questions came back empty. The payment finished at 9:12, and we didn't hear about it until 9:15. Asking over and over like this is called polling, and it's a lot like walking out to the mailbox every few minutes. If you've seen Shrek 2, you know how this goes:

A gag. The Crumb & Co. server, on the left, says Paid yet? three times, each speech bubble bigger than the last, and then How about now?. The payment provider, on the right, looks weary and says: For the last time, NO.

Donkey asks "Are we there yet?" the whole way to Far Far Away. (He does get there eventually.) Polling more often would get us our news sooner, but every question is another request against the provider's speed limit.

What if our provider told us instead? Wren gives our provider a URL on our server, and the moment a payment finishes, our provider sends a request to it:

The same two lanes over time. Crumb & Co. asks nothing. At 9:12, the payment finishes at the provider (a green check), and the provider immediately sends payment.succeeded up to Crumb & Co., where a doorbell rings. Crumb & Co. answers 200 OK. A handwritten note points at the doorbell: Ding dong!

Look at how the arrows flipped. Our server asked nothing and heard about the payment at 9:12, the minute it happened. We traded the trip to the mailbox for a doorbell. When an app calls a URL we gave it to tell us that something happened, that call is a webhook.

What Shows Up at Our Door

A webhook is an ordinary HTTP request, just going the other way. Here is the one our provider sends for our pecan pie:

A webhook delivery from the payment provider. POST /webhooks/payments is the URL we registered. Webhook-Signature: 5f1c…e09a is the proof it came from the provider. The JSON body has id evt_1042 (the event ID), type payment.succeeded (what happened), and data with payment pay_8K2 (which payment).

Every event has its own ID and a type that says what happened. Our webhook URL has to be public, so anybody could send it a fake payment.succeeded.

The signature line is how we will tell real from fake:

Two deliveries arrive at Crumb & Co. For each one, we compare the signature it came with to the signature we compute from its body and our shared secret. From our provider: it came with 5f1c…e09a, we compute 5f1c…e09a, and they match, so we process it. From a stranger: it came with 0b7d…13f6, we compute 9e42…c8a1, and they don't match, so we reject it with a 400.

Our provider and our server share a second secret. Before sending, the provider mixes the body with that secret to make a short fingerprint called an HMAC (RFC 2104 has the math). Our server does the same math on what arrived. A stranger without the secret can't make a match, so we reject their request with a 400. Stripe sends this fingerprint in a Stripe-Signature header, and GitHub uses X-Hub-Signature-256.

Our provider also wants a quick answer. GitHub expects a 2xx within 10 seconds, and Stripe's docs say to send one before any complex logic.

Emails and kitchen tickets can be slow, so we split our work in two:

Two bands. The top band, While the provider waits, has three steps joined by arrows: Check the signature, Write down the event, and Answer 200 OK. An arrow goes from Write down the event down to the bottom band, After we answer, where a background worker leads to Email the customer and then Print a kitchen ticket.

Everything in the green band happens while the provider waits, and it takes a moment. A background worker does the slower yellow band afterward, so a slow email service never keeps the provider waiting. Async Processing with Queues goes deeper on this pattern.

Why the Same Event Shows Up Twice

Let's say our server is restarting when evt_1042 arrives. Our provider gets an error, so it tries again later:

Two lanes over time. The provider sends evt_1042 three times. The first time, Crumb & Co. is restarting and answers 500. After a wait, the second try reaches a slow Crumb & Co. and times out with no answer. After a longer wait, the third try gets 200 OK. Under the lanes, the first gap is labeled wait and the second, twice as long, is labeled wait longer.

Each wait is longer than the one before, which gives our server time to recover. Stripe will keep retrying for up to three days in live mode. GitHub doesn't retry on its own, so we'd have to redeliver a missed delivery ourselves within 3 days.

The tricky case is when our server did its job and our provider never found out:

Two lanes over time. The provider sends evt_1042. Crumb & Co. sends the confirmation email and prints a kitchen ticket, then answers 200 OK, but the answer is lost on the way back, marked with a red X. The provider sends evt_1042 again, and Crumb & Co. sends a second email and prints a second ticket before its 200 OK gets through. A handwritten note points at the second email and ticket: Again?!

From our side, the first delivery worked. From the provider's side, it failed, because our 200 never made it back. Our provider can't tell the difference, so it sends evt_1042 again, and we send a second email and print a second ticket:

A gag. Odette, who runs the Crumb & Co. kitchen, stands next to two identical pecan pies. Above each pie hangs the same kitchen ticket: order_311, Pecan pie, Nov 24. On the right, the customer's phone shows two identical emails that say Your pie is confirmed!. A handwritten note points at the pies: Twins!

Our provider promises that every event will reach us at least once, and it never promised exactly once. This is called at-least-once delivery, and Stripe's docs say plainly that an endpoint might receive the same event more than once.

Events can also show up out of order. If our customer pays at 9:02 and cancels at 9:05, a retry of the payment event can land after the refund:

Two columns. What happened: at 9:02, evt_1042 payment.succeeded, and at 9:05, evt_1043 payment.refunded. What arrived: at 9:05, evt_1043 payment.refunded, and at 9:07, evt_1042 payment.succeeded, marked as a retry. Arrows cross from each event to where it landed. A handwritten note points at the late evt_1042: Arrives last!

If we trust the order things arrive in, order_311 ends up paid, and Odette bakes a pie for someone who canceled. Stripe doesn't guarantee order, so our handler should check where order_311 stands right now, see the refund, and leave it alone.

Making the Second Delivery Harmless

We can't stop the duplicates, and we wouldn't want to, because retries keep us from missing payments. What we can do is make a second delivery change nothing.

First, we write down every event ID we handle, and we tell the database that an ID can only appear once (a unique constraint).

Here is what happens to the second evt_1042:

An incoming delivery of evt_1042 arrives again and heads for our webhook_events table, whose event_id column is unique. The table already has rows for evt_1040, evt_1041, and evt_1042, so the evt_1042 row is highlighted and a handwritten note says Seen it!. An arrow leads from the incoming delivery down to the result: skip it, answer 200 OK.

The database turns the duplicate away, so our handler skips the work and still answers 200 to stop the retries. Data Modeling and Databases has more on keys and the rules a database can enforce.

Second, we make the work itself safe to repeat. Our worker will move order_311 from pending to paid, and print a ticket only if that move happened. A second run finds the order already paid. Nothing prints. A refunded order can't move to paid either, which takes care of the late event from earlier.

Getting the same result whether something runs once or twice is called idempotency, and it matters for our own requests too. If the connection drops while we're starting a payment, did the payment get created?

Stripe's Idempotency-Key header will make the retry safe:

Two tries of the same request. First try: Crumb & Co. sends POST /v1/payments with Idempotency-Key: 9f2c…41ab. The provider creates pay_8K2, but its answer is lost on the way back, marked with a red X. Retry: Crumb & Co. sends the same request with the same key. The provider has seen this key, so it sends back pay_8K2 again instead of making a new payment. A handwritten note points at the provider's second answer: Charged once!

The retry uses the same key, so Stripe sends back pay_8K2 instead of charging our customer another $10. Timeouts, Retries, and Circuit Breakers has more on retrying safely.

The Handler in Code

What we just did was teach our handler to check signatures, answer fast, skip repeats, and look at an order's current state.

Here is a sketch of it for a Node.js server using Express:

import express from "express";
import crypto from "node:crypto";
import { db, sendConfirmationEmail, printKitchenTicket } from "./bakery.js";

const app = express();
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET; // from the server's settings, never from Git

function isValidSignature(body, signature) {
  const expected = crypto.createHmac("sha256", WEBHOOK_SECRET).update(body).digest("hex");
  const a = Buffer.from(expected);
  const b = Buffer.from(signature || "");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

app.post("/webhooks/payments", express.raw({ type: "application/json" }), async (req, res) => {
  // 1. Is this really from our payment provider?
  const body = req.body.toString("utf8");
  if (!isValidSignature(body, req.get("Webhook-Signature"))) {
    return res.status(400).send("Bad signature");
  }
  const event = JSON.parse(body);

  // 2. Write the event down. event_id is UNIQUE, so a repeat adds no row.
  const saved = await db.query(
    "INSERT INTO webhook_events (event_id, type, body) VALUES ($1, $2, $3) " +
    "ON CONFLICT (event_id) DO NOTHING",
    [event.id, event.type, body]
  );
  if (saved.rowCount === 0) console.log(`Already have ${event.id}, skipping`);

  // 3. Answer right away. A background worker picks up new rows in webhook_events.
  res.sendStatus(200);
});

// The background worker runs this for each new payment.succeeded row.
async function handlePaymentSucceeded(event) {
  const paid = await db.query(
    "UPDATE orders SET status = 'paid' WHERE payment_id = $1 AND status = 'pending' RETURNING *",
    [event.data.payment]
  );
  if (paid.rowCount === 0) return; // already paid, or refunded: nothing to do
  await sendConfirmationEmail(paid.rows[0]);
  await printKitchenTicket(paid.rows[0]);
}

app.listen(4242);

We read the raw body with express.raw, because the signature was made from the exact bytes the provider sent. For a repeat, the insert adds no row and rowCount is 0. The UPDATE only matches a pending order, so the email and ticket go out once.

Note: Use the Provider's Library

Real providers also sign a timestamp, so nobody can replay an old delivery later. In a real Stripe handler, we'd let stripe.webhooks.constructEvent check both instead of our isValidSignature.

When an AI Agent Writes the Handler

Wren built Biscuit with a coding agent, so our first handler came from an agent too. It emailed the customer, printed the ticket, and passed Wren's test. It also lasted exactly until the second morning of pre-orders...

Agents are good at the path where everything goes right, because that's the path we describe. Wren's prompt now asks for the rest out loud:

  • Verify the signature with the provider's library and the raw body.
  • Answer with a 2xx right away, and send emails and tickets from a background worker.
  • Record each event ID with a unique constraint, and skip repeats.
  • Check the order's current state, since events can arrive out of order.
  • Add a test that sends the same event twice and expects one email.

That last one matters most. An agent will happily tell us its handler is safe to repeat, and a duplicate event is how we find out.

Try It This Week

Let's receive one real webhook and make it arrive twice. This uses Stripe's test mode, and the commands match Stripe's CLI docs at the time of writing (a GitHub repository webhook and its Redeliver button work too):

  1. Install the Stripe CLI, run stripe login, and start a handler like our sketch on port 4242, with stripe.webhooks.constructEvent doing the signature check.
  2. Run stripe listen --events payment_intent.succeeded --forward-to localhost:4242/webhooks/payments, and give your handler the whsec_ secret it prints.
  3. In a second terminal, run stripe trigger payment_intent.succeeded, and copy the event ID (it starts with evt_) from the stripe listen output.
  4. Run stripe events resend with that event ID to send the same event again.
  5. Check your logs, emails, or database. The work should happen once. If it happened twice, ask your agent for the event ID check from this article and try again.

Frequently Asked Questions

What Is the Difference Between an API and a Webhook?

An API is the published list of requests another app agrees to answer, and our app calls it when we want something. A webhook goes the other way: the other app sends an HTTP request to a URL we gave it when something happens on its side. Asking an API over and over is like checking the mailbox, and a webhook is like a doorbell.

Can a Webhook Be Delivered More Than Once?

Yes. Most providers, including Stripe, deliver webhooks at least once, so an error, a timeout, or a lost 200 response can lead to the same event arriving again. Events can also arrive out of order, so record each event ID you’ve handled, skip repeats, and check an order’s current state before acting.

How Do You Verify a Webhook Signature?

The provider makes an HMAC from the raw request body and a secret that only you and the provider know, then sends it in a header such as Stripe-Signature or X-Hub-Signature-256. Your server computes the same HMAC from the body it received and compares the two with a constant-time check. If they don’t match, reject the request, and use the provider’s library when there is one, because it also checks a timestamp.

What Does Idempotent Mean for APIs and Webhooks?

An idempotent operation has the same result whether it runs once or several times. For webhooks, that means a repeated event does no extra work, like moving an order from pending to paid only once. For our own requests, an idempotency key such as Stripe’s Idempotency-Key header lets us retry without creating a second charge.

Conclusion

Ok! It is time to wrap things up. Our website talks to its payment provider through an API, using a secret key that never leaves our server. When the provider has news, it rings our doorbell with a webhook. That doorbell can ring twice or out of order, so we check the signature, write down each event ID, and look at where an order stands before anything goes in the oven.

One honest limitation is that webhooks don't completely replace asking. If our server is down longer than the provider keeps retrying, we'll miss events, so a nightly job that asks the API what we missed is still worth having.

As for the bonus pecan pie, Rosa says it was the best mistake our kitchen made all season.

Before you go, here are a few things you can do:

  1. Ask a question

    Stuck on something, or curious about a detail we skipped? Ask on the forums, and we’ll help you out.

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright © KIRUPA 2026 //--