MSD-101 ยท Deep dives: hard problems, solved
Payments without double charges
โฑ 14 min ๐ฎ Hands-on โ Azure โ Completed
โก The 30-second answer
A payment must happen exactly once in a world where networks drop and queues deliver at least once. Put the charge on a queue, keep one ledger record per trip (a unique key), send an idempotency key to the payment provider, trust only signed webhooks, and retry with backoff and a limit into a dead-letter queue.
- At-least-once delivery
- Idempotency at every hop
- Signed webhooks
- Retries that do not storm
Try it
Play with the design before you read about it. Everything runs on this page.
No Azure subscription needed. Read the requirement, see the architecture, build it in a mock portal, send a booking through it, then break it.
โ Simulate on Azure: Payments without double charges
Priya's trip ends. Her saved card must be charged RM 32 exactly once, even if the payment provider is slow, a message is delivered twice, or someone sends a fake 'paid' message.
It must
- Charge the saved card when a trip completes
- Mark the trip PAID only when the provider confirms
- Send the rider a receipt
- Never store card numbers on our servers
With these numbers
- Double charges
- 0
- Paid within
- p95 < 30 s
- Card data
- Tokens only
- Audit
- Every attempt logged
Each box is one Azure service. Tap a box (or Tab to it) to see its job and why it is there.
Create each resource. The defaults are a good design; change a setting and read why it matters. Some choices decide what breaks later.
Home โบ Create a resource โบ Azure Service Bus
Create Service Bus namespace and queue
โ Duplicate detection needs Standard or Premium.
โ Drops a message with the same MessageId (the tripId) inside the time window.
โ After 10 failed tries the message moves to the dead-letter queue for a human.
Deployment in progressโฆ
Microsoft.ServiceBus ยท resource group rg-payments
Home โบ Create a resource โบ Azure Container Apps
Create Container App: payment-service
โ The provider returns the first result for a repeated key instead of charging again.
โ Fast endless retries turn a slow provider into an outage.
Deployment in progressโฆ
Microsoft.ContainerApps ยท resource group rg-payments
Home โบ Create a resource โบ Azure Cosmos DB
Create Cosmos DB container: payments
โ The database itself refuses a second payment record for the same trip.
Deployment in progressโฆ
Microsoft.CosmosDB ยท resource group rg-payments
Home โบ Create a resource โบ Azure API Management
Add webhook API in API Management
โ Only messages signed by the provider are accepted.
Deployment in progressโฆ
Microsoft.APIManagement ยท resource group rg-payments
Everything is deployed. Your architecture is lit up below. Go to Run to send a request through it.
Request: Trip ends: charge RM 32 to the saved card
โ ๏ธ Use the payment provider's test mode only. Never use real cards in a learning lab.
- Create a Service Bus Standard namespace with a queue and duplicate detection on.
- Create a Cosmos DB container with a unique key on /tripId.
- Build a small payment worker that sends an Idempotency-Key to the provider's test API.
- Expose the webhook through API Management and verify the signature.
- Delete the resource group when done.
* Illustrative prices to compare designs, not a quote.
What breaks, and the fix
| Failure | User sees | Why | Fix |
|---|---|---|---|
| โณ Provider times out, service retries | Charged twice | A retry looked like a new charge | Idempotency-Key on every provider call |
| ๐จ Queue delivers the command twice | Charged twice | Queues deliver at least once | Duplicate detection + unique key on tripId |
| ๐ญ Attacker sends a fake 'paid' webhook | Free rides for fraudsters | Webhooks were trusted blindly | Verify the provider's signature at the gateway |
| ๐ฉ๏ธ Provider down for 3 minutes | Late or failed payments | Fast, endless retries | Backoff with jitter, max tries, dead-letter queue |
๐ Education-only simulation. Nothing is created in Azure and no subscription is needed.
Stream vs command
Live data can lose a point. Commands must happen exactly once. Give them different roads.
GPS points ride the WebSocket every 4 s. One lost? The next one replaces it.
Idempotency key
Send the same ID on every retry. The server returns the first result instead of doing it again.
Book with key k7. The trip is savedโฆ but the reply is lost in the lift.
Outbox + backoff
Save the command on the phone first, then send it. Wait longer after every failure.
The tap is saved to the local outbox. Even if the app dies now, it is not lost.
Geo index + expiry
Keep only the latest position per driver in memory, and let it expire after 30 s.
Every ping overwrites the driverโs last position and resets a 30 s timer.
Pub/sub fan-out
Publish one event to a group. Everyone in the group gets it, however many they are.
The trip service publishes once: โcar movedโ.
Push to wake, then re-sync
A push only says โsomething changedโ. The app then asks the server for the truth.
The app is in the background, so its socket is closed. The server sends a push.
- The problemA support ticket: โYou charged me RM 64 for a RM 32 ride.โ The logs show one trip, two charge calls, 900 ms apart. The first call worked; its reply was lost.
- The design ideaEvery hop may repeat. Make every repeat harmless.
- In real lifePayment providers document idempotency keys because double charges are the number one payment support ticket. Teams that add them at every hop rarely see the problem again.
Start with a question
A support ticket: โYou charged me RM 64 for a RM 32 ride.โ The logs show one trip, two charge calls, 900 ms apart. The first call worked; its reply was lost.
Every hop between the app and the bank can repeat. The design must make repeats harmless.
Explain it like I'm 10
When you pay at a shop and the machine freezes, the cashier checks the receipt number before swiping again. The receipt number is the idempotency key.
The technical explanation
Queue the work. When a trip completes, the trip service puts a charge command on Azure Service Bus with MessageId = tripId. Turn on duplicate detection (Standard or Premium) so a repeated message in the window is dropped.
One record per trip. The payment service inserts a PENDING record in Cosmos DB with a unique key on /tripId. A second insert for the same trip fails, so two workers cannot both charge.
Idempotent provider call. Send an Idempotency-Key (for example the tripId) with the charge. If the reply is lost and you retry, the provider returns the first result. Read the provider key from Key Vault with a managed identity.
Confirm safely. Mark PAID only when the providerโs signed webhook arrives; API Management verifies the signature. Retry failures with exponential backoff and jitter; after the max delivery count the message goes to the dead-letter queue for a human.
| Repeat source | Guard |
|---|---|
| App retries the trip end | Idempotency-Key on the API |
| Queue delivers twice | Duplicate detection + unique key |
| Worker retries the charge | Idempotency-Key to the provider |
| Webhook arrives twice | Ledger state check (already PAID) |
| Fake webhook | Signature verified at the gateway |
Real-world scenario
Payment providers document idempotency keys because double charges are the number one payment support ticket. Teams that add them at every hop rarely see the problem again.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
Next: Fares and surge pricing โQuestions people ask
How do payment systems avoid double charging?
Idempotency keys on every call, one ledger record per order (a unique key), duplicate detection on the queue, and confirmation only from signed provider webhooks.
What is a good idempotency key for a payment?
A business id such as the trip id, reused on every retry of the same charge. A new random id for each attempt protects nothing, because the provider sees every retry as a new payment.
Does Azure Service Bus deliver each message exactly once?
No. Service Bus delivers at least once, so a message can arrive twice. Turn on duplicate detection (Standard or Premium tier) and keep a unique key per trip in the ledger, so a repeat cannot charge again.
Should a mobile app call the payment provider directly?
Only for card entry with the providerโs own SDK, which returns a token. Charging happens on your server with the token and an idempotency key.
Interview questions
How this topic comes up in system design interviews. Answer out loud first, then open the model answer.
intermediate Design the charge flow after a ride.
TripCompleted โ Service Bus (MessageId = tripId, dedup on) โ payment service inserts PENDING (unique /tripId) โ charge with Idempotency-Key โ signed webhook via API Management โ PAID โ receipt push; backoff, max tries, dead-letter queue.
advanced How do you reconcile with the provider each night?
Pull the providerโs settlement report, compare with the ledger by tripId, flag missing, extra or mismatched amounts into a review queue, and never auto-refund without a rule or a human.
Quick revision
Remember
- At-least-once delivery
- Idempotency at every hop
- Signed webhooks
- Retries that do not storm
- Use a business id (tripId) as the idempotency key, not a random id per attempt. A new random id on each retry protects nothing.
One line to remember
โEvery hop may repeat. Make every repeat harmless.โ
Official documentation
- Service Bus duplicate detection (Microsoft Learn)
- Cosmos DB unique keys (Microsoft Learn)
- Service Bus dead-letter queues (Microsoft Learn)