Skip to content

Stripe webhook receiver

POST /hooks/stripe on the public inference host (https://ai-api.myra.eu) is the inbound receiver for Stripe webhook events that drive self-serve sign-up provisioning and subscription lifecycle (payment success/ failure, plan changes, cancellation, disputes, refunds). It is not a customer- facing API — only Stripe's own webhook delivery infrastructure calls it — and is documented here because it is a genuine untrusted-input trust boundary (principle 11): every byte of the request body and every header is hostile until verified.

Trust boundary: signature verification

Stripe authenticates via a body signature, not a bearer token. The Stripe-Signature request header carries t=<unix-timestamp>,v1=<hex>[,v1=<hex>...] (multiple v1 values appear during a webhook-secret rotation window — any one matching is accepted). The expected signature is HMAC-SHA256(<the configured Stripe webhook secret>, "<t>.<raw body>"), compared constant-time against every v1 candidate.

Signature verification happens before any JSON parsing, and regardless of the self-serve kill-switch — the kill-switch stops new checkouts only; already-paid customers must never be refused service by a config flag.

Rejected input Response
Missing/empty Stripe-Signature header 400
Malformed header (no t=, no v1=) 400
Timestamp more than ±300s from server time 400
No v1 candidate matches the computed HMAC 400
Stripe webhook secret not configured (unset or whitespace-only) 400 (fails closed, never crashes) — reachable only when self-serve is off; with self-serve on a boot-time gate refuses to start on a missing/blank secret, so a self-serve gateway always has a usable one
Body exceeds 512 KiB (checked before the signature) 413
Any method other than POST 405 (with Allow: POST)
Request during the gateway's start-up window 503 (Stripe retries it)

An unsigned or otherwise unverifiable request is rejected here, at the signature check, and never consumes any rate-limit budget — the endpoint is not rate-limited on the caller's address (behind the edge every external request shares one origin peer address, so a per-address limit would be a single shared bucket that any unsigned flood could pin, starving genuine signed deliveries).

Once the signature verifies, the body is decoded and shape-checked. The decode is strict: a repeated key would otherwise silently keep only its last value, so the gateway never acts on a value a reader of the raw body did not see.

Rejected input Response
A key repeated in one object, at any depth (an escaped spelling such as "\u0061" counts) 400 duplicate key in event body
More than 262,144 structural elements (each {, [, , and each string, counted outside string contents) 413 event body too complex
Non-JSON body, an empty body, a body holding a raw NUL byte, a body that is not valid UTF-8, or a number that is not finite (NaN, Infinity, 1e400) 400 malformed event body
JSON body that isn't an object (a number, null, an array) 400 malformed event body
Missing id or type 400
Missing data or data.object, or either one an array instead of an object 400 missing event data / missing event data.object
A request body the gateway cannot read back 503 temporarily unavailable (before the signature check; Stripe retries)
More than 6000 verified events/minute across the endpoint 429 (a flat per-endpoint safety cap applied only after the signature verifies — so only genuine Stripe traffic can reach it; Stripe retries a 429 with backoff)

Every refusal above happens before the event is claimed, so nothing is written and a corrected resend of the same event id is processed normally. The 503 is logged only and the 429 is the rate limiter; neither raises an alert. A signed body refused for its content (the 400 and 413 rows) is not acknowledged: Stripe retries a non-2xx answer for up to three days, and a body Stripe itself signed should never repeat a key or be over-dense, so the gateway logs an error and raises one operator alert (stripe_webhook_body_refused, at most one per hour) instead of dropping the event. The error names the refusal, never the body. A genuine Stripe event is far below the limit: the largest measured events (a 100-line-item invoice) use about 3,400 of the 262,144 elements.

Endpoint subscription check

The gateway lists its Stripe webhook endpoints (GET /v1/webhook_endpoints, at most 20 pages) and alerts when an event it processes is not subscribed. The listing is decoded strictly and is rejected as unreadable, never treated as complete, when any of these holds:

  • a page is not an object with a data array and a boolean has_more, or has_more is true on an empty page;
  • the listing is not finished after 20 pages;
  • an element is not an object, or its id is not a we_ id;
  • an element's url is missing, empty or longer than 2048 characters, or its status is anything but enabled or disabled, or its livemode is not a boolean;
  • an element's enabled_events is not an array of strings, has more than 500 entries, or has an entry that is empty, longer than 128 characters or outside ^[a-z0-9_.*]+$.

The check selects only the current environment's exact URL and the pinned live/test mode: https://ai-api-int.myra.eu/hooks/stripe on int, https://ai-api-beta.myra.eu/hooks/stripe on beta, and https://ai-api.myra.eu/hooks/stripe on prod. Other hosts, other environments, URL suffixes (including trailing slash, query and fragment) and wrong-mode endpoints are ignored, never counted as healthy or as duplicates. Zero matching endpoints is no_endpoint; multiple exact matches are ambiguous. A configured Stripe environment with an unknown environment name is misconfigured, not guessed; completely absent Stripe key and pins still mean skipped.

The endpoint secret is never read. Listing errors expose a bounded status/type/code classification, not raw Stripe messages or proxy response bodies, in check logs and alerts. The check never writes Stripe configuration. Create a missing endpoint in the Stripe dashboard using the handler registry. The operator repair script adds every handled event (the list in src/hooks/stripe_events.tl) to an existing endpoint, the same list on every environment; it never removes an event. See the billing runbook for the outcomes.

Accepted event types

Only these twenty-three are processed (twelve billing events + five schedule events + six catalog events); anything else is acknowledged (200) and marked ignored — Stripe stops retrying an event the moment it gets any 2xx, so an unrecognized-but-harmless event type must never be met with a 500 (a 500-retry storm would get the endpoint auto-disabled by Stripe, silently killing provisioning for real customers).

  • checkout.session.completed — provisions a new tenant (pay-first: no tenant exists until this fires), or reactivates a cancelled tenant. A payment-mode session tagged metadata.kind=wallet_topup is a wallet top-up and is routed first: it credits the workspace's wallet with amount_subtotal (only when payment_status=paid). A money field that is not a non-negative integer, a currency the platform cannot convert, or a workspace that no longer exists is terminal: an unreconciled movement is recorded, ops is alerted once, and the event is acknowledged (200) — never a retry storm that can never succeed. A database fault is transient (500, redelivered). When the session's metadata names a budget request (budget_request_id, a top-up started from "Add budget" on the request), a credited session also marks that request approved (once — a redelivery or a request rejected meanwhile changes nothing; a malformed id is logged and ignored, the credit stands; a failed approval write answers 500 so Stripe redelivers). A subscription checkout (fresh sign-up, trial conversion, reactivation) reads the subscription's items once, before anything is written and records the EU-governed add-on it bills — see Subscription items. The workspace's card is also recorded here. When the session is a subscription checkout paid by the owner (signup, reactivation, or a conversion whose session carries metadata.purchaser=owner), the subscription's default_payment_method is stored as the workspace card for the automatic top-up — only when none is stored yet (an existing card is never replaced) and only when the value is a pm_… id. A conversion paid by a holder of Buy plans and add budget (no purchaser marker, or any value other than owner) records nothing: a holder's card never becomes the workspace card. A missing or malformed payment method is skipped and logged; the provisioning itself is never blocked by it.
  • checkout.session.expired — a Checkout Session this server opened has expired: its record is marked expired, and the workspace's (or signup's) open-session pointer is cleared only while it still names this session, so an expiry for an old session never clears a newer one. A session this server has no record of (a wallet top-up session, a foreign one) is ignored; a session without an id is ignored. A database error answers 500 so Stripe retries.
  • payment_intent.succeeded — our own off-session automatic top-up (metadata.kind=wallet_auto_topup) credits amount_received; the PaymentIntent behind a manual top-up (metadata.kind=wallet_topup) credits nothing (the session event does) and at most saves the card it was paid with as the workspace's card for the automatic top-up — only when the PaymentIntent echoes setup_future_usage exactly as "off_session", which the platform sets on the owner's top-up session alone. A top-up started by a holder of Buy plans and add budget sets nothing, so its card is never saved and the owner's saved card stays; an absent, null or any other setup_future_usage value saves nothing either (the event is acknowledged). During a rollback or a rolling deploy, a node running a release from before this rule saves the card from any top-up PaymentIntent, a holder's included. Any other PaymentIntent is ignored. Credits are idempotent per PaymentIntent (the ledger's unique key), so the two events Stripe fires for one payment credit once. payment_intent.payment_failed is deliberately not subscribed: the automatic top-up learns every decline synchronously from the charge itself.
  • invoice.paid — renewal/initial-payment confirmation; resets the usage allowance on a genuine new billing cycle (never on a portal tier-switch's proration invoice — that would let a customer farm free allowance resets by toggling tiers). Marks the subscription active and ends any dunning grace only on those same billing events (subscription_create / subscription_cycle); a proration invoice — paid or net-credit — changes nothing about status or grace (the subscription's own status event does). A no-op on a subscription that is already terminal (a late renewal invoice after a cancellation never resurrects the workspace). It does not clear a pending payment itself: the paid upgrade's customer.subscription.updated does (see below).
  • invoice.payment_failed — grace period + dunning email on a renewal failure; immediate deactivation (no grace) on a first-invoice failure. A no-op — no dunning email either — on a subscription that is already terminal. A proration invoice (billing_reason=subscription_update and every line a proration) is carved out: it changes no status, starts no grace and sends no email — the gateway only re-reads the invoice from Stripe and, when it is still open with a valid hosted-invoice link (an https://invoice.stripe.com URL in printable ASCII; anything else is rejected and logged), mirrors its id, link and expiry into the subscription's pending_invoice_* columns so the customer can pay it. The invoice is only mirrored while it is still the subscription's current invoice: the re-read subscription's latest_invoice must be this invoice. The expiry is Stripe's pending_update.expires_at. A subscription with no pending update did not get this invoice from the gateway's own pending plan change (its items are already applied; for example an ops change in the Stripe dashboard): invoice.payment_failed is then an ordinary failed payment (grace + dunning email like a renewal), never a pending payment. A malformed pending_update answers 500 with nothing written. A replacement invoice always replaces the stored link, even when it expires earlier. An open proration invoice that is no longer the latest (for example a renewal invoice followed), or a subscription without a latest_invoice, writes nothing and the stored link stays. A malformed latest_invoice or pending_update, or a malformed stored pending_invoice_id, writes nothing and is logged. A paid, void, foreign-subscription or already-lapsed invoice writes nothing, and a terminal subscription is never written. The write is a compare-and-set on the stored invoice id: if another writer changed the stored link between our read and our write, the event answers 500 so Stripe redelivers. A Stripe outage during either re-read also answers 500 so Stripe retries. Needs confirmation (MAP-4776). On the grace path (not the gateway's own plan change), the gateway re-reads the invoice and its PaymentIntent from Stripe: when the invoice is still open, belongs to this subscription, its one live PaymentIntent is requires_action (3-D Secure) and its hosted_invoice_url is a valid https://invoice.stripe.com link, the same write stores the invoice id and link (payment_action_invoice_id / payment_action_url) and the dunning e-mail is the "confirm your payment" variant with that link. Any other answer clears a stored link only if it names this invoice (before the dunning write): a later decline of the same invoice after a card change switches back to "update your payment method", while a delayed failure of another (older, since paid) invoice leaves a newer invoice's link in place. A Stripe outage during this re-read never delays the dunning: the event is processed, a link stored earlier (by invoice.payment_action_required, which Stripe does not redeliver) is kept, the e-mail takes the "update your payment method" wording and a warning is logged. A link that is not a valid Stripe-hosted link is never stored (logged as an error).
  • invoice.payment_action_required — the same proration-only mirror write (the customer must authenticate the charge) for the gateway's own pending plan change. MAP-4776: for any other invoice (a renewal, or a proration of a subscription with no pending update, e.g. a seat change billed immediately in the Stripe dashboard) it records whether the invoice only needs confirmation — the same Stripe re-read as above — and writes only payment_action_invoice_id / payment_action_url (never status, grace or an e-mail: the dunning stays invoice.payment_failed's). When the re-read no longer says requires_action (paid, void, declined), it clears a stored link only if it names this invoice, so an event that arrives late or is replayed after the invoice was paid never brings a link back and never removes a newer invoice's. Accepted residual: the Stripe re-read and the row write are not atomic. If the invoice is paid in the moment between them (the re-read still says requires_action, invoice.paid clears an empty row, then this write lands), a link to the now-paid invoice can be stored. It is only shown while subscription_status is 50, and the next grace clear (customer.subscription.updated active, a paid renewal) or the next invoice.payment_failed removes it; no compare-and-set is used. A Stripe outage answers 500 (Stripe retries). A subscription_update invoice that also carries a non-proration line (a charge for the subscription itself) is an ordinary failed payment (dunning/grace like a renewal), not a proration; one whose lines cannot be read changes nothing and is acknowledged (200), with a warning logged.
  • customer.subscription.updated — syncs status/period bounds from the live subscription, not from the event: Stripe does not order webhooks, so the event only names the subscription and the gateway re-reads it from Stripe (GET /v1/subscriptions/{id}) and mirrors that. A stale, older event therefore cannot regress the status, period, cancel flag, price, seat quantity or the tenant's plan. No row for the subscription yet: the usual retry/duplicate path, no Stripe call. A subscription that is already terminal is never touched by any customer.subscription.updated: it is acknowledged without a Stripe read or a write. A live subscription that has ended gets its terminal status written and nothing else (no price or seat mirror, no plan switch). A live read that fails or answers a different subscription id: 500 (Stripe retries); a subscription Stripe reports as not existing: logged as unexpected, 200, the mirror is not updated. A price change that arrives while the catalog cannot be read (the price's plan cannot be decided, as opposed to a price that is definitely bound to no plan) is not acknowledged: 500, so Stripe retries once the catalog is healthy; the price mirror is written last, so the retry still sees the change. A changed price that is definitely bound to no plan is acknowledged (200) after its subscription_tier_unresolved audit row is written; if that row cannot be written the delivery answers 500 before the price mirror, so Stripe's redelivery writes the row once. Each plan switch is applied once: a retry or a concurrent delivery that finds the tenant already on the new plan succeeds without a second e-mail. During a long catalog outage Stripe keeps retrying price-changing events and may eventually disable a persistently failing endpoint. Status/period-only events stay 200; a subscription with no mirrored price yet counts as price-changing, because nothing proves its price unchanged. A fixed cancellation date that is removed alerts ops (MAP-4723): when the stored subscription holds a fixed cancel_at set outside the app (cancel_at_period_end false) and the live subscription has no date and cancel_at_period_end is the boolean false (the owner clicked "Don't cancel" in the Stripe billing portal, or ops removed the date in the dashboard), one atomic write clears the date and the delivery that wins it raises the ops alert fixed_cancel_date_removed (a redelivery or a concurrent duplicate finds the date gone and does not alert again; a failing claim answers 500, so Stripe retries). The customer's own cancel-at-period-end undo does not alert. If the live flag is not the boolean false (missing, not a boolean, or true) while the date is null, the stored fixed date is kept, and the stored cancel_at_period_end flag too (logged), until a well-formed delivery arrives. A row with a scheduled plan switch gets plan_switch_dropped instead. A price that did not change never moves a tenant off a plan staff set (MAP-3777): when the mirrored price equals the live price and the tenant's stored plan is not a self-serve plan (an enterprise / manual plan, or an unreadable plan name), the plan switch is skipped, with a warning in the log; nothing is purged, no "tier-changed" e-mail is sent and no CRM sync runs. The price and seat mirror is still written. Only a changed price, or a self-serve tenant whose unchanged price now resolves to another plan (the recovery after ops bound a price), switches the plan. A failed write of the price / seat mirror or of the plan switch: 500 (the retry re-reads and converges; the "tier-changed" e-mail is sent only once the switch is applied). The read and the write are not atomic: if a newer change lands between them and a concurrent delivery writes it first, the older snapshot can win until the next customer.subscription.updated of that subscription — only that event repairs status, stripe_status, the period, cancel_at_period_end, price_id, stripe_quantity and the tenant's plan. The items heal does not write these fields (it repairs the seat cap, the add-on mirror, the schedule mirror and the pending-invoice mirror), and invoice.paid is not a repair. It detects a plan/interval switch by the subscription's price id, never by metadata (a portal-initiated price change never touches subscription metadata). Stripe's subscription status is the dunning authority: a status that maps to active also ends a grace window (the second way out of dunning, for a proration whose failed charge started it). The period and the cancel flag are written only when the live subscription carries a well-formed value (see below). The plan switch and the seat mirror read the seat item only — an EU-governed add-on item never drives the tier, and the item order does not matter. Every live delivery also marks the subscription's items for re-reading (see Subscription items). An event whose data.object.id is missing or is not a subscription id (a Stripe object id starting sub_, and not a sub_sched_ schedule id) is acknowledged (200) and ignored with a warning: no subscription or tenant data is written, no Stripe read is made, and the event is recorded as ignored.
  • customer.subscription.deleted — deactivates the tenant; starts the retention clock toward eventual data purge. An event whose data.object.id is missing or is not a subscription id (a Stripe object id starting sub_, and not a sub_sched_ schedule id) is acknowledged (200) and ignored with a warning: no subscription or tenant data is written, no Stripe read is made, and the event is recorded as ignored.

  • charge.dispute.created — locks the account (no self-service reactivation) and alerts ops for manual review. A dispute on a wallet charge (matched by the charge's payment_intent against the wallet ledger) also debits the wallet and flags it; the subscription lock still applies when one exists. A dispute of a plan-change (proration) charge locks the account like any other; a scheduled plan change is not touched.

  • charge.refunded — for a full refund of the current subscription's own charge (the charge's cumulative amount_refunded has reached what was captured — amount_captured, or amount when the charge carries no amount_captured; attributed through the charge's PaymentIntent and the invoice it paid): deactivates the account and cancels the subscription at Stripe immediately (no proration, no final invoice), so Stripe stops billing and the owner can come back through Reactivate (a fresh checkout). Once Stripe has confirmed the cancel, the workspace's Stripe status is recorded as canceled at once, so a reactivation is never mistaken for a second subscription; Stripe's own customer.subscription.deleted follows and sends the "subscription ended" e-mail (unless the customer has already reactivated — a deleted event for an older subscription the workspace has since replaced with a live one is ignored). A redelivered refund does not cancel twice: an already-ended subscription counts as done. A refund of an earlier subscription's charge (the customer has reactivated since) or of a charge that paid no subscription invoice (another product, a one-off payment, another product's subscription on the same Stripe customer) leaves the workspace untouched. If Stripe cannot be asked which subscription the charge paid for, the event answers 500 and Stripe redelivers it; the workspace is not blocked meanwhile and ops are alerted (stripe_refund_attribution_failed; a malformed PaymentIntent on the charge, or a malformed answer from Stripe, is rejected the same way and flagged permanent — never read as "not a subscription charge"). A refund whose charge has no PaymentIntent at all paid no subscription invoice and leaves the workspace untouched. A partial refund of a subscription charge (amount_refunded below what was captured) is money back only: the workspace and its subscription stay exactly as they were, and nothing is cancelled. When later partial refunds add up to the whole charge, that event is the full refund above. "Full" is measured against what was captured (amount_captured when the charge carries it, otherwise amount). If the current subscription's charge has an amount, amount_captured (when present) or amount_refunded that is not a whole, non-negative number of minor units, a charged or captured amount of 0, a captured amount above the charged one, or a refunded amount above the captured one, the refund is treated as neither: the event answers 500, nothing is written, and ops are alerted (stripe_refund_attribution_failed, flagged permanent). A charge that is not the current subscription's is ignored whatever its amounts. If the cancel call fails, the account stays blocked, ops are alerted (stripe_refund_cancel_failed, naming the workspace) and the event answers 500 so the cancel is retried. Two exceptions are money back only (200, nothing written, the subscription stays): a refund, full or partial, of a plan-change (proration) charge (its invoice's billing_reason is subscription_update and every line is a proration, over a complete line list (has_more false or absent, at least one line); an incomplete or empty list is an ordinary charge), and a full refund while the live Stripe subscription has a scheduled plan change that has not yet applied attached (cancelling would destroy it; the schedule is read live from Stripe, not from the mirror). A schedule of ours whose change has already landed (or that has ended) no longer blocks the cancel; a schedule that is not ours (for example one set in the Stripe dashboard) keeps the subscription, as before. A full refund kept this way alerts ops (stripe_refund_kept_subscription), who cancel by hand if the refund was meant to end the subscription. An absent billing_reason is treated as an ordinary subscription charge (a warning is logged); a present but malformed billing_reason, or a malformed schedule field, answers 500 with nothing written and an ops alert (stripe_refund_attribution_failed, flagged permanent); a failed schedule read answers 500 (retried) with the same alert. A subscription_update invoice whose lines cannot be read (so it cannot be told from a plan-change charge) is handled the same way (500, nothing written, a permanent stripe_refund_attribution_failed alert). A proration refund whose amounts cannot be read also alerts ops (stripe_refund_kept_subscription, the message says the amounts were unreadable and it may have been a full refund). A refund of a wallet charge instead debits the wallet by the refunded share of what was credited (cumulative across partial refunds) and leaves the subscription untouched. If the refund arrives before the top-up's own credit has been processed, the event is held (500, retried) rather than consumed. A charge that is neither a wallet charge nor known to be ours follows the subscription path.

Subscription schedule events

subscription_schedule.updated, .released, .canceled, .completed and .aborted keep the pending_change mirror on the subscription row (the six stripe_schedule_id and pending_* columns) equal to the schedule Stripe has attached. subscription_schedule.created is not subscribed: the gateway's own downgrade writes the mirror itself, and the product tag only arrives with the following updated.

  • The event is a trigger, never data. Its payload is used only to find the subscription row; the mirror is written from a live read of the subscription and its schedule at Stripe. Replays and reordered events therefore write the same thing, and a late released that arrives after a new schedule was attached mirrors the new schedule, it never clears it.
  • Result: the LIVE state at Stripe decides the outcome, not the event type. When Stripe reports no schedule of ours, the mirror is cleared; when it reports one with a change still ahead, the mirror is rewritten. The write is a compare-and-swap on the row as read. A miss (another writer, such as the gateway's own downgrade, changed the row in between) is re-converged in the same request: the row and the live state are read again and the write is retried, up to 3 attempts in total. A schedule the subscription named that reads back released, canceled or completed (it ended between the two reads) is re-converged the same way. If every attempt loses, the event answers 500 as a failed event (not as an ordering retry), so Stripe's redelivery is processed at once. ordering_retry stays only for a subscription row that is not in our table yet.
  • Inert schedule (200, processed). A schedule whose last phase has already applied (Stripe keeps it attached) leaves the mirror untouched; the items heal clears a landed schedule's mirror in the same transaction as the seat cap.
  • Foreign filter. A schedule carries its own metadata.product; the normal product filter applies, so a schedule of another product is ignored (200) with no Stripe call.
  • Accepted shape. data.object.id is a sub_sched_... string, and the subscription is data.object.subscription (string or expanded object), or released_subscription when subscription is null (Stripe sets that on release).
  • Mirror cleared (200, processed). An attached schedule that is not ours (foreign tag, end_behavior other than release, or an untagged schedule other than the event's own) is not ours to mirror, so the mirror is CLEARED by compare-and-swap. Because a foreign schedule with a phase still to apply also blocks every plan change of the customer, ops get one stripe_schedule_foreign alert per subscription and schedule, coalesced to once per 24 hours while it stays attached (a failing alert never changes the event's result). A foreign schedule that is already spent (inert) blocks nothing and raises no alert; the mirror is cleared either way.
  • Held (200, processed) plus alert. If the event's own schedule reads back untagged, or the subscription or identity does not match what the row says, the mirror is left untouched and ops gets one stripe_schedule_mirror_unreadable alert: a mirror we cannot re-derive is still the best we have.
  • Ignored (200). A foreign metadata.product on the payload, a missing or malformed schedule id, a malformed subscription id (a malformed value never falls through to the other field), both subscription ids absent, or a subscription not in our table that is a recorded duplicate or was replaced by a reactivation (the customer's row is on another, live subscription). Any other subscription not in our table is retried as an ordering race (500) until its provisioning lands.
  • Transient failure (500). Stripe unreachable, rate limited or 5xx, or a database fault.
  • Unreadable answer. If Stripe answers but the schedule is malformed or not a shape the gateway writes, the mirror is left untouched, ops gets one stripe_schedule_mirror_unreadable alert, and the event is acknowledged (200): a retry cannot heal a malformed answer. A malformed answer is never read as "no schedule".
  • Limit: untagged schedules. A schedule that was created but never tagged (the gateway's create succeeded and its tagging update failed) is dropped by the product filter and created is not subscribed, so no webhook sees it. The next downgrade replaces it, or the reconciliation (S8) does.

Catalog events

price.created, price.updated, price.deleted, product.created, product.updated, product.deleted keep the product catalog's Stripe mirror equal to what is configured in Stripe.

  • They bypass the metadata product filter above (an object that just lost its metadata.product=ai-gateway tag must still reach the mirror) and use a local relevance test instead, which makes no network call: the object's own tag, the tag in data.previous_attributes, the object id already being mirrored, or (for a price) its product being mirrored. An event that passes none is ignored (200) with zero Stripe calls.
  • A relevant event triggers one refetch of that object from Stripe (5 s timeout) in the client's pinned API version; the event body is never trusted beyond its validated id (^[A-Za-z0-9_-]{1,128}$). So delivery order, duplicates, and the endpoint's own API version do not matter.
  • Catalog events are always answered 200 (processed or ignored). A transient failure (Stripe unreachable, a database fault, a mirror lookup error, even an unexpected error in the handler) only marks the mirror dirty; the next full sync reconciles it. The webhook path never deletes a mirror row — only the full sync does, under its own safety rules. A burst of events for one object within 5 s refetches once and marks the mirror dirty for the rest.
  • Each environment's endpoint must subscribe to these six events in addition to the billing events. scripts/stripe/ensure_webhook_events.sh (see the billing runbook) subscribes every accepted event type the endpoint lacks; it reads them from the gateway's own list, so it cannot lag behind a new handler.
  • A missing subscription no longer waits for a person on every environment: where the platform setting stripe_webhook_self_repair_envs lists the environment (default int and beta), the hourly subscription check adds the missing handled events to the endpoint itself. It only ever adds events, never removes one, and every attempt is audited. See the billing runbook.

Which event writes which column

Stripe delivers a renewal's, a plan change's or a dunning cycle's events in parallel with no ordering guarantee. Each handler therefore writes only the columns its event owns — never a value it read from the row moments earlier (a parallel delivery whose write landed in between would otherwise be reverted: a scheduled cancellation silently un-flagged by the renewal invoice, a stale 7-day grace deadline left on a recovered workspace, a period roll reverted for the dunning duration). A column the event does not own is left untouched.

Event status Stripe status grace deadline period cancel-at-period-end dispute flag
invoice.paid (subscription_create / subscription_cycle) active — cleared the invoice line's service period (when readable) — —
invoice.paid (subscription_update) — — — only when the line period extends the stored one (an interval switch) — —
invoice.paid (any other reason) — — — — — —
invoice.payment_failed (subscription_update, every line a proration) and invoice.payment_action_required (same) — — — — — — (writes only pending_invoice_id / _url / _expires_at; the items heal clears them once Stripe shows no pending update and the mirrored invoice is no longer payable)
invoice.payment_failed grace / inactive past_due the new deadline / cleared — — — (MAP-4776: also sets or clears payment_action_* in the same write)
customer.subscription.updated mapped from Stripe's status Stripe's (when recognized) cleared when the status maps to active (active, trialing) and on a terminal status; otherwise — the item period (when valid) Stripe's flag (when a boolean; not on a terminal status) —
customer.subscription.deleted inactive canceled cleared — set —
charge.dispute.created inactive (locked) — cleared — — set
charge.refunded (a full refund of the current subscription's own, non-proration charge with no scheduled plan change only; a partial refund, a proration-charge refund or a refund while a schedule exists changes nothing) inactive canceled (only once Stripe has confirmed the cancel) cleared — — —

MAP-4776: the "needs confirmation" pair (payment_action_invoice_id / payment_action_url) only qualifies a grace: every write above that clears the grace deadline clears it too, and invoice.paid / invoice.voided (any reason) clear it when it names that invoice. The reactivation checkout clears it as well.

Every status-0 write by invoice.payment_failed, customer.subscription.deleted, charge.dispute.created and charge.refunded clears the grace deadline, so a cancellation, a dispute or a refund blocks inference without waiting out the grace window a failed payment had opened; customer.subscription.updated clears it only on a terminal status (an incomplete / paused / unknown status maps the workspace inactive but leaves a running grace as it is).

Every subscription write (and a tier switch) flushes the cached gateway configuration of every gateway of the workspace — including the internal / external pair of a workspace that started as a free trial — so the new status applies on the next request served by the gateway node that processed the webhook. Other gateway nodes pick it up when their cached configuration expires (the gateway-config cache lifetime, config_cache_ttl, 30 seconds by default).

Accepted shapes and what is rejected (the body is signature-verified first; each field is then read on its own): cancel_at_period_end is written only when it is a JSON boolean — absent, null, "true" or 1 leave the stored flag as it is (writing 0 would silently un-schedule a cancellation) and log a warning; status is written only when it is a string Stripe's vocabulary recognizes — an unknown string maps the workspace inactive (fail closed) but the raw string is not stored, and a non-string leaves both status columns as they are; a period is written only when both bounds are finite positive timestamps with the end after the start and both before the year 10000 — anything else (one bound, an inverted or zero-length pair, "1e400") leaves the stored period as it is; billing_reason on an invoice must be a string — a non-string invoice changes nothing. None of these answer an error: Stripe would retry a 4xx/5xx for days, and a malformed-but-signed body is never worth a retry storm.

Subscription items (the EU-governed add-on)

A self-serve subscription bills one or two items: the seat line and, when the customer bought it with the trial conversion, the EU-governed add-on line (quantity = seats). Stripe does not order items, so no handler reads an item by position. Stripe's items are the truth; the subscription row keeps a mirror of the add-on (its slug and price), and the add-on's grant is derived from that mirror while the subscription serves (see Tenant entitlements).

Item shape (untrusted input). An item without a well-formed price id is dropped and the list counts as incomplete, as does a list Stripe reports as truncated (has_more anything other than absent or false) or a broken shape (items.data not a list). An item's quantity is read as one of three states: a positive integer; a literal 0 (the add-on counts as absent, and a quantity mismatch is paged); or unreadable (absent, null, negative, not an integer) — an unreadable add-on quantity never revokes a paid grant: the add-on stays granted, the row stays marked for re-reading, and it is paged.

checkout.session.completed. The items are classified once, before any write. The checkout session's own record is the first authority (it names the seat price and, for a conversion with the add-on, the add-on price); items it does not name go through the catalog. Exactly one complete item is the seat, with no catalog dependency.

  • A purchase with the add-on waits — the event answers failed, so Stripe retries, and one coalesced billing_subscription_items_unread page is sent — when the item list is incomplete, an item the record does not name cannot be classified yet (for example the catalog is unreadable), the add-on was replaced by an item that is not ours, or the subscription bills several add-on or several plan items. Nothing is written in that case.
  • A purchase without the add-on provisions as before; an extra item it does not name never blocks it (it is classified later).
  • Completion writes the add-on mirror (or clears it when the subscription has none) as unconfirmed and marks the items for re-reading in the same statement; the grant is live immediately, and the workspace's gateway configuration is flushed when an add-on was recorded. The record's offered add-on is compared with the billed one too: a difference pages billing_checkout_mismatch (the workspace is provisioned from what Stripe charges), unless the audit log holds a billing.change_applied / billing.change_payment_pending row for the subscription written since the session was created: then a self-serve plan change moved the subscription on purpose and nothing pages (an INFO log names the action). No row, an unreadable lookup or a malformed answer all page. The checkout_mismatch audit row is written before the completion: if it cannot be written, the delivery answers 500 and the checkout is not completed yet: the workspace exists on its plan, but the purchased seats, the price mirror and the checkout record are not written. Stripe redelivers, and the redelivery writes the row once and then completes. Every failed attempt pages again (no coalescing); the page says provisioning is not completed. An add-on quantity different from the seats pages billing_addon_quantity_mismatch (it still grants); an item that is not ours pages billing_subscription_unknown_item (it grants nothing).
  • A redelivery of a conversion whose session record is already completed for this workspace skips the item read, the seat guard, the duplicate check and the completion, and takes the plan from the record — so a drifted or two-item subscription can never turn it into a failure — but still runs the deferred-voucher redemption a first delivery may have left pending.

customer.subscription.updated never writes the add-on mirror. On every live (non-terminal) delivery it marks the items for re-reading — in the same update as the status, or on its own when every field of the body was malformed (a failed mark answers failed, retried). It never marks a terminal status, nor a row the guarded update did not match. Two items that both classify as plans page subscription_multi_plan_items (regardless of a price change) and switch nothing.

The items heal. A background step on every node (worker 0, beside the catalog sync's 60-second tick, in its own error isolation) is the only writer that confirms the add-on mirror. Each tick it pages billing_subscription_items_unread when a marked row has waited longer than one hour (evaluated even when the catalog is unreadable), stops while the catalog is unreadable, and otherwise re-reads up to five marked subscriptions plus one unmarked one (least recently checked first — this catches a lost mark and visits every older subscription once) within 20 seconds. A complete read writes the mirror and clears the mark, guarded by a version number that every mark bumps: an event landing in between makes the heal lose, and the next tick reads again. When the add-on changed, the workspace's gateway configuration is flushed. A shape fault (incomplete list, several add-ons, the add-on replaced by an unknown item, no or several plan items, an unreadable quantity) never revokes the add-on — the row stays marked and is paged. A strict Stripe 404 on the verified, pinned account is final: the mark is cleared, the mirror is left unchanged, and billing_subscription_items_missing is paged; a 404 that cannot be verified as the pinned account's keeps the row marked (a wrong-account key can never clear rows). Ended subscriptions, deleted workspaces and rows without a Stripe id are never selected.

customer.subscription.updated applies seats and the add-on. The event itself only marks the subscription row dirty; the items heal (the stripe_catalog_sync tick on worker 0) then re-reads the subscription from Stripe and, in one transaction, (1) confirms the add-on mirror, (2) converges the tenant's plan-row seat cap to Stripe's live seat quantity - self-serve plans only, an enterprise / manual cap is never touched - and (3) clears a landed schedule mirror (the downgrade took effect). A self-serve tenant without a plan row keeps that mirror: no cap was written, so the scheduled seat count stays its only seat bound until a plan row exists. Once Stripe shows no pending_update the heal re-reads the mirrored invoice and clears the stale pending_invoice_* mirror unless that invoice is still open inside its payment window (then the customer can still pay and the mirror is kept); an unpaid or lapsed upgrade therefore never raises the cap. The same pending-invoice check also runs at the end of a processed customer.subscription.updated (MAP-3888), right after the price mirror is written, so a paid upgrade clears the pending payment as soon as that event is handled (the webhook runs the whole check, so a lapsed, void, uncollectible or gone invoice is also cleared there, with the same audit and page as on the tick); this is best effort, and a failed or skipped check leaves the mirror for the tick. When that check clears the mirror because the invoice is paid (MAP-4412), the same delivery then runs the items heal's own visit of that subscription (a fresh Stripe read and the one transaction above), right after the clear; the 60 s tick is the backstop. A not-paid clear (void, uncollectible, lapsed, gone) or a kept mirror never runs it. If that visit does not confirm (Stripe unreachable, a concurrent heal or event won, the catalog is unhealthy) the event is still acknowledged and the tick applies the cap. Otherwise the delay is bounded by the heal cadence: a 60 s tick handles 5 dirty rows, and a row that stays dirty for more than an hour pages billing_subscription_items_unread. A rejected quantity (zero, above the platform seat maximum, not an integer) leaves the cap alone and pages invalid_billing_subscription_seats; a tenant without a plan row pages billing_seats_no_plan_row. An admin override of a Stripe-billed tenant's cap is reverted on the next heal.

Early void and expiry of a pending payment (MAP-3777). invoice.voided (resolved to the subscription like the other invoice events) and customer.subscription.pending_update_expired (the subscription is named by data.id) do nothing but mark the subscription row dirty; the items heal above is the only code that clears the pending_invoice_* mirror (invoice.payment_action_required / invoice.payment_failed write it): on its tick, and through its pending-invoice check, which customer.subscription.updated (MAP-3888) runs at its end. Stripe sends no customer.subscription.updated for either, so without them the mirror would stay until the backstop. A subscription this gateway does not know is ignored (200), and so is an invoice.voided whose invoice carries no customer; a subscription that ended (terminal) is still processed (the row is marked, the heal decides); a body without a usable subscription id is processed with nothing written; a failed mark answers 500 so Stripe retries.

Reconciliation. For a self-serve plan the heal tells operators when it had to correct the mirror, and pages billing_reconcile_drift (one audit row; Stripe stays the authority). A seat or add-on correction pages when no recorded customer plan change explains it; a customer's plan change whose answer was lost (the write is still recorded, unsettled) also explains it once Stripe shows that change applied. A schedule correction pages when no customer plan change was in flight. A pending-payment correction (field pending_payment) pages when the mirrored invoice was voided before its expiry, marked uncollectible, or no longer exists (a strict 404 on the verified account); a paid invoice, Stripe's own expiry void and an open invoice past its window are cleared without a page. A manual plan's add-on correction is only logged. While a customer plan change is in flight the items are not confirmed: a dirty row stays dirty, a backstop row stays clean. A Stripe answer of the wrong shape is never treated as absent: it pages billing_reconcile_stripe_malformed. For a wrong-shape subscription or incomplete items nothing is changed and the row is retried. For a malformed pending_update the pending-invoice mirror is kept and the subscription items are still confirmed. The mirrored invoice is read fail-closed too: an unknown or absent status, a missing or foreign subscription, a void whose status_transitions.voided_at is absent, or a status_transitions that is not an object or carries a stamp that is not a positive whole unix timestamp in seconds keeps the mirror and pages billing_reconcile_stripe_malformed (kind pending_invoice). An absent or null stamp is "not stamped", never malformed. A wrong-shape schedule answer during the heal's reconcile instead raises the hold alert stripe_schedule_mirror_unreadable and leaves the schedule mirror untouched.

Duplicate subscriptions. When a second paid subscription slips through, the webhook records the PaymentIntent that actually paid its invoice (from the invoice's payments: exactly one paid → that one; otherwise exactly one that is not canceled; with no payments list, the invoice's single legacy PaymentIntent; else none) — a canceled earlier attempt is no longer recorded in its place, so the refund of the real payment is recognised as the duplicate's.

Product filtering (shared Stripe account)

This endpoint receives every event on the Stripe account, including events for an unrelated product sharing the same account. Checkout, subscription and subscription-schedule events positively match metadata.product == "ai-gateway" before acting. Charge events (dispute/refund) and invoice events (invoice.paid / invoice.payment_failed / invoice.payment_action_required) carry no reliable product tag on the object itself — a real invoice's metadata is empty and the tag lives only on its line items — so these are matched instead by looking up the object's customer id against our own subscription table. An event that doesn't match is ignored (200), never 500 — same reasoning as the unrecognized-event-type case above. A customer that is not (yet) in our table is treated as foreign and ignored; a genuine database error during the lookup returns 500 so Stripe retries.

Idempotency

Every event is durably recorded (stripe_event_id, unique) before processing, so a Stripe redelivery of an already-fully-processed event is a fast no-op (200), and a redelivery that arrives while the first delivery is still being processed gets 500 (never 200 — a 200 would make Stripe consider the event delivered and stop retrying, permanently losing it if the in-flight attempt then fails).

Wallet credits, refunds and disputes

A wallet credit (a Stripe wallet top-up or automatic top-up charge), refund or dispute reversal is stored together with its audit entry in one transaction. If the audit entry cannot be written, the credit is rolled back and the endpoint answers 5xx, so Stripe redelivers the event; the redelivery is idempotent (one credit per payment and kind). A payment that cannot be matched to a workspace is recorded as unreconciled only after that record is durably committed; an operator alert (wallet_audit_refused) is raised when the audit entry itself is refused.

What this endpoint never returns

There is no response body contract to integrate against — Stripe only inspects the HTTP status code. Responses are plain text, not JSON.