← all notes

Why our Stripe webhooks ignore the event body

We bill for Tissue Cloud and Tissue Mast through Stripe. The code that talks to Stripe is a small Rust service called atp, and it runs on a server of its own, away from the rest of our fleet, because it holds the Stripe key. When something changes in Stripe, a webhook tells atp, and atp tells our management API which plan the account is on.

This week we pulled the webhook handling out of atp into a crate called stripe-poke and put it on crates.io. This post is about why it's built the way it is, which mostly comes down to one early decision and three bugs we wrote in the first month anyway.

When we started on atp in July we read Stripe's webhook docs pretty closely, and a few lines in there ended up deciding most of the design. Stripe doesn't guarantee that events arrive in the order they were created. The same event can be delivered more than once. And if your endpoint doesn't answer with a 2xx, Stripe keeps retrying, with backoff, for up to three days in live mode.

The usual way to write a handler is to take the subscription out of the event body and save it. With those rules, that can go backwards. Say a customer upgrades and then cancels a minute later. The upgrade delivery fails because we happen to be in the middle of a deploy, the cancellation goes through fine, and a while later Stripe retries the upgrade. If we apply that body, a customer who cancelled is back on Pro, and nothing ever logged an error.

So atp doesn't apply the subscription in the body. It takes the customer id out of the event, asks Stripe for that customer's subscriptions, works out the plan from whatever comes back, and sends the whole result to the management API. We started calling the events pokes, as in someone rang the doorbell and you go and see who's there. The retried upgrade still arrives and still runs the handler, but by then Stripe says the subscription is cancelled, so that's what we send.

We got more out of this than we expected. Duplicates stop mattering, because running the handler twice sends the same answer twice. The hourly job that catches webhooks we never received is the same function, run for every customer, so there's only one copy of the billing logic to get right. A forged event can't put anyone on a plan either, because the plan only ever comes from what Stripe answers. It costs an extra Stripe API call per event, which at our volume is nothing.

There is one thing atp still reads from a body. The first checkout event is where it learns which Stripe customer belongs to which account, and that pairing comes from the event. It can only fill in a pairing that isn't there yet. If the account or the customer is already paired with something else, atp refuses and logs it.

Taking the event body out of the picture turned out to be the easy part. We got the order of the steps around it wrong three times.

The first version of atp wrote down each event id as soon as it arrived, so a repeat delivery could be answered with a quick 200. A security review of the billing server in August pointed out what that does when something fails. If the Stripe fetch errors, atp answers 500 and Stripe redelivers, which is what you want. But the id is already written down, so the redelivery looks like a duplicate, gets a 200, and the event is gone. The hourly job would have fixed the account eventually, but until then it would have been wrong, with nothing in the logs to say so. We changed it on August 9, a week before we turned on live checkout. atp checks the id when the event arrives and records it only after the handler succeeds. That means two copies of one event arriving together can both run, which with a poke handler costs one extra Stripe call.

A review of all the money paths a few days later found the other two. The first was in the push to the management API. atp puts each push in a local SQLite queue before trying to send it, so a crash in between doesn't lose it. If that queue write itself failed, we logged it and carried on, and the webhook still answered 200. Stripe thought we had it and we didn't. That case answers 500 so Stripe tries again.

The second was a timestamp. Every push carries an as_of time, and the management API ignores a push older than the one it already has, since retries mean an old push can always turn up late. We were stamping it after the Stripe fetch came back. Picture two fetches for the same customer. One starts first and is slow. The other starts a second later, sees newer data and comes back quickly. Stamped at the end, the slow one carries the later time, and the stale answer wins. atp stamps it when the fetch starts.

None of that code knew anything about our plans or prices, and we'd rather other people didn't have to find the same bugs, so we moved it into its own crate. stripe-poke has the signature check, a receiver that checks the event id first and records it last, the queue for whatever you derive, and SQLite versions of the event log and the queue. atp keeps the Stripe calls and the plan rules, and it's moving onto the crate with its own test suite unchanged.

A webhook route using it looks roughly like this:

let rx = Receiver { secret: &webhook_secret, tolerance_secs: 300, ledger: &ledger };
let outcome = rx
    .receive(signature_header, &body, stripe_poke::unix_now(), |event| async move {
        let Some(customer) = event.customer_id() else {
            return Ok(Handled::Ignored);
        };
        let as_of = stripe_poke::unix_now();
        let plan = plan_for(fetch_subscriptions(customer).await?);
        let payload = serde_json::json!({ "plan": plan, "as_of": as_of }).to_string();
        outbox::enqueue_and_deliver(&queue, &sink, customer, &payload, as_of).await?;
        Ok(Handled::Processed)
    })
    .await;

outcome.status() is what you answer Stripe with: 400 for a bad signature, 200 for a success or a duplicate, and 500 when your handler failed or the event log couldn't be read. Stripe retries anything that isn't a 2xx, so the 500 is what gets you another delivery.

The queue holds one payload per account, and a newer one replaces the older, because each one is the full state and not a change. The fiddly part is the ack. If a newer payload is queued while an older one is being delivered, the older one succeeding can't be allowed to delete the newer row, so a row is only removed if it still holds the payload that was sent. Failed deliveries back off from 30 seconds, doubling up to 15 minutes.

There's no HTTP in it. You call it from your own route, write the Sink that talks to your service, and run the retry pass and the hourly sweep from a timer you already have. It doesn't talk to Stripe either, so the fetch is your code with whatever Stripe client you like. The SQLite stores block, which is fine for a local file but worth knowing on a busy async runtime, and you can implement Ledger and Outbox yourself for a different database. If all you need is the signature check and typed events, async-stripe-webhook is a better fit.

The code is at github.com/tissue-systems/stripe-poke, under MIT or Apache 2.0, and cargo add stripe-poke gets you version 0.1.