AlgoViz

Idempotency

medium 26 min

An idempotent operation has the same effect whether it runs once or many times.

See it run

How a request can be sent many times and still take effect once, even when answers get lost and servers crash.

Operations

The double charge

A payment without a key: the answer is lost, the customer tries again, and the card is charged twice.

Step 1 of 4

Pay $99.99

Our systemPOST /paymentsclaim, savechargeClientPayment APIKey storeunique keyCard network

Charged

$99.99

The customer clicks once. The request reaches the API and the card is charged.

Step 1: Pay $99.99

def create_payment(body):    return card.charge(body)     # every call charges
Effect
$199.98
Extra work
None
With a key
$99.99

A timeout does not mean it failed. It means you do not know. That sentence is the whole reason for this topic.

In the real world

The same idempotency doing real jobs. Pick one and step through it.

The old payment simulator as a story: one new key, then retries with the same key, then a new purchase.

Step 1 of 3

First click, key 8f14

KeyStatusCharged
Click 18f14201 new$99.99
Click 2
Click 3
Purchase 2

New key: processed, 201. Total charged $99.99, duplicates blocked 0.

Step 1: First click, key 8f14

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A new key for every attempt

    critical

    The server sees a new intention each time, so retries charge again. The key belongs to the click, not to the HTTP call.

    Wrong
    def attempt():    post(body, key=uuid4())
    Right
    key = uuid4()            # onceretry(lambda: post(body, key=key))
  • Read, then write

    critical

    Two requests can both read nothing and both go on. Only a unique insert decides a winner.

    Wrong
    if not db.find(key):    db.insert(key); charge()
    Right
    if db.insert_if_absent(key):   # UNIQUE    charge()
  • A key that is unique for everyone

    major

    If keys are not scoped to the user, one user's key can return another user's stored answer.

    Wrong
    UNIQUE (key)
    Right
    UNIQUE (user_id, endpoint, key)
  • Marking any error as final

    major

    A timeout to the card network is not a failure: the charge may exist. Keep the key open and look it up before trying again.

    Wrong
    except Exception:    db.set(key, "failed")
    Right
    except Timeout:    leave_processing(key)      # recovery asks first

Interview tips

  • How to explain it

    • Doing it twice leaves the same state as doing it once.
    • Retries are normal, so every write must survive them.
    • GET, PUT and DELETE are idempotent by definition. POST needs a key.
  • Memory trick: SAKE

    • S: same result, however many calls.
    • A: atomic store of the key before the work.
    • K: key from the client.
    • E: expiry after the retry window.
  • Reach for a key when

    • Payments and refunds.
    • Orders and bookings.
    • Transfers between accounts.
    • Any POST a client may retry.
  • Simpler choices first

    • A natural key: one checkout per cart.
    • A unique constraint on the business row.
    • A PUT to an id the client chose.
    • A set instead of an add.