Design a payment system: ledgers, webhooks, and idempotency
Payment
Guided ModeStep 2 β Introducing a Dedicated Payment Service
Request Flow
Separate payment logic from the API
We extract all payment-specific logic into a dedicated Payment Service. The API becomes a thin gateway that validates the request and forwards it. The Payment Service owns state transitions: PENDING β AUTHORISED β CAPTURED β SETTLED.
Payment Gateway as an external dependency
The Payment Service calls an external Payment Gateway (Stripe/Adyen/Braintree). This call is the slowest and most failure-prone in the entire system β network latency of 80β300ms plus the gateway's own processing time.
Save intent before calling gateway
The Payment Service saves a PENDING charge record to the database before calling the gateway. This means we always know a charge was attempted, even if the gateway call crashes.
Why We Need This
Separating payment logic into its own service enables independent scaling, isolated audit logs, and cleaner ownership. The Payment Service is typically the most heavily tested service in the entire organisation β it must be bulletproof.
Key Insight
Always write PENDING to your database before making the external gateway call. If the service crashes after writing, a recovery job can check the gateway for the outcome. If it crashes before writing, no money moved.
Step 2 of 7
