Order and Payment State Machines
Represent order and payment lifecycles explicitly instead of using loosely related booleans. An order might move from PENDING to CONFIRMED, CANCELLED, or FULFILLED; a payment may be CREATED, AUTHORIZED, CAPTURED, FAILED, or REFUNDED. Valid transitions should be enforced and audited.
Do not equate an HTTP success from a payment provider with final settlement unless the provider's contract says so. Webhooks may arrive late, out of order, or more than once. Verify signatures, persist provider event IDs, and process events idempotently. Periodic reconciliation compares internal state with provider records to detect missed callbacks or uncertain outcomes.
Separate order state from payment state because they have related but distinct lifecycles. Define what happens when payment succeeds after an order was cancelled, or when inventory expires before capture completes.
- Model allowed state transitions explicitly.
- Treat provider webhooks as duplicate and potentially out-of-order events.
- Use reconciliation to resolve uncertain external outcomes.
What prevents two concurrent purchases from both consuming the final unit of stock?