Backend Case Studies

Topic B12

Idempotency and retries

Making retries safe: the same result however many times a request is sent.

9 min · intermediate

Watch: the reply gets lost on the network and the app tries again. Without a key, the user is charged twice; with one, still once.

payment providerappAPIcharges: 0
  • moving now
  • being checked
  • finished / the result
Step 1 of 5

The user presses Pay $15. The app sends POST /payments.

Networks can lose a reply at any time. Retries can't be avoided, so the server must be safe receiving the same request twice.

Why retries can't be avoided

When a request times out, the client can't tell where it failed: before the server got it, while the server was working, or on the way back. All three look the same from the client's side. The only safe choice is to try again, and that's only safe if the server can recognise the same request.

What's idempotent already

  • GET, PUT ("set name = Ana") and DELETE are naturally idempotent: running them twice leaves the same state.
  • POST ("create an order", "charge a card", "send a message") isn't. Running it twice makes two.
  • Adding ("balance += 50") isn't idempotent; setting ("balance = 150") is.
Code, for programmersAn idempotency key on the server
-- CREATE TABLE idempotency (key text PRIMARY KEY, response jsonb, created_at timestamptz);

app.post("/payments", async (req, res) => {
  const key = req.get("Idempotency-Key");
  if (!key) return res.status(400).json({ error: "Idempotency-Key required" });

  const saved = await db.idempotency.findUnique({ where: { key } });
  if (saved) return res.json(saved.response);          // seen before: replay the answer

  const result = await db.$transaction(async (tx) => {
    await tx.idempotency.create({ data: { key } });      // unique key: a second racer fails here
    const charge = await payments.charge(req.body);
    await tx.idempotency.update({ where: { key }, data: { response: charge } });
    return charge;
  });
  res.json(result);
});

Notice the key is stored under a unique constraint, not just checked with a SELECT. Two retries arriving at once could both pass the check; the database constraint makes sure only one succeeds (see the race condition topic).

Quiz

  1. A payment request times out. What does the client know?

  2. Which operation is idempotent?

  3. Why store the key under a unique constraint instead of checking first?

0 of 3 answered.