hardSystem Design

How do you make a payment system reliable against retries?

993 views
01

Understand the problem

Explain idempotent payments.

paymentsidempotency
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Idempotent charge with status
Run Playground
charges = {}   # idempotency_key -> record (Redis/DB in production)

def charge(key, amount, provider):
    rec = charges.get(key)
    if rec and rec["status"] == "succeeded":
        print("retry of", key, "-> no second charge")
        return rec                                  # safe to retry
    charges[key] = {"status": "pending", "amount": amount}   # record intent FIRST
    ref = provider(key, amount)                     # provider call is also keyed
    charges[key] = {"status": "succeeded", "amount": amount, "ref": ref}
    return charges[key]

def fake_provider(key, amount):
    print("  charging", amount, "for", key)
    return "txn_" + key

print(charge("k1", 4999, fake_provider))
print(charge("k1", 4999, fake_provider))   # retry -> deduped, no double charge
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.