A payment gateway times out with a 504 error right after debiting a customer, leading to the webhook firing twice ten seconds later. If your payment flow relies on optimistic UI updates or a single `is_paid` boolean, you may end up with a ghost debit or a double-credited wallet.
When building payment integrations, I design with a focus on deterministic state machines and defensive reconciliation before implementing any business logic:
- Strict State Machines: Every transaction progresses through explicit states (INITIATED → PENDINGGATEWAY → SETTLED / FAILED). Once a record is SETTLED, it cannot regress, and any transaction stuck in PENDINGGATEWAY beyond a certain threshold triggers a verification check.
- Edge Tokenization: Raw card or bank credentials are exchanged at the client boundary, ensuring that sensitive information never touches internal microservices.
- Idempotent Webhooks + Signatures: Each incoming callback is validated using an HMAC signature and checked against a unique idempotency_key before acquiring a database row lock, allowing us to safely ignore duplicate retries.
- Reconciliation: Webhooks are best-effort and not guaranteed. To close the loop when callbacks are missed, a background cron job polls the gateway’s verify endpoint for stale PENDING_GATEWAY records.
Payment security isn’t merely a pre-launch checklist; it’s about how your state machine behaves when the network fails mid-flight. What’s the most challenging webhook or timeout edge case you’ve had to debug in production?
#Fintech #PaymentIntegrations #BackendEngineering #SystemDesign #AppSec
