The Desi Architect
Notes / Docker Sandboxes / API Idempotency Key Engine & Distributed Locking
Docker Sandboxes · Tier 3: Reliability & Messaging · Lab 42

API Idempotency Key Engine & Distributed Locking

Build a payment endpoint that is safe to retry. Retry after a lost response, double click, change the body, crash after the money moved, crash before the work, empty Redis, and get a decline. Check each time that the customer is charged at most once and that the answer is the same.

Time40 minutes
StackPostgreSQL 16Ports 15447, 16391
MemoryAbout 70 MB
Before thisLab 07Lua in Redis
Verified runWindows, Mac, LinuxBash and PowerShell
  1. 1PrepareWhat you will learn
  2. 2PredictGuess before you run
  3. 3RunStep by step
  4. 4ObserveWhat you should see
  5. 5Break itChange one thing
  6. 6Clean upLeave nothing running
On this page
  1. 00 / What You Will Learn
  2. 01 / Why It Matters
  3. 02 / What We Are Building
  4. 03 / Words You Need
  5. 04 / Predict First
  6. 05 / Step by Step
  7. 06 / What You Should See
  8. 07 / Look Inside
  9. 08 / Break It, Fix It
  10. 09 / In Real Projects
  11. 10 / Interview Corner
  12. 11 / Clean Up

00 /What You Will Learn

By the end you will be able to
  • Explain idempotency and the idempotency key header.
  • Keep the key record and the charge in one transaction so a crash cannot split them.
  • Return 409 for a request still running, 422 for a reused key with a different body, and replay the stored answer otherwise.
  • Explain a lease, so a dead attempt does not block a payment forever.
  • Say why Redis can only be a cache here, and why declines are stored too.

Before you start

Finish Lab 05 (SQL Transactions and Isolation) and Lab 07 (Redis and Lua Scripting) first. You should know a transaction and SET key value NX. Docker Desktop and Python 3 are needed.