Rebuild: Payment State Machine with Compensating Transactions
What exists
x402 (HTTP 402 pay-per-request) payments are handled inline — charge then process. If the processor crashes after charging but before confirming, the payer has no recovery path.
What I'd build instead
A formal payment state machine with compensating transactions:
States: Pending → Authorized → Captured → Completed
↘ Failed → Refunded (compensation)
- Every payment gets a UUID idempotency key (stored in Upstash Redis)
- Two-phase:
authorize holds funds, capture settles only after successful processing
- On failure in any post-authorization step: automatic refund via compensating transaction
- Payment event log for audit trail (who paid what, when, and the outcome)
Why this matters
- Zero lost funds: no scenario where money leaves wallet without service rendered
- Idempotency: retrying a failed request doesn't double-charge
- Audit trail: you can prove every payment outcome
- Users trust the system when they see "Authorized — will only charge on completion"
Migration path
- Extract payment logic into a standalone service with a state machine
- Generate idempotency keys before any HTTP 402 interaction
- Store payment state in Redis with TTL
- Add a refund endpoint triggered by compensating events
- Add idempotency check on all payment webhooks
Rebuild: Payment State Machine with Compensating Transactions
What exists
x402 (HTTP 402 pay-per-request) payments are handled inline — charge then process. If the processor crashes after charging but before confirming, the payer has no recovery path.
What I'd build instead
A formal payment state machine with compensating transactions:
authorizeholds funds,capturesettles only after successful processingWhy this matters
Migration path