Idempotency Keys in Distributed Payment APIs
Network timeouts can cause clients to retry requests, risking duplicate charges. An Idempotency Key (`Idempotency-Key` header) ensures an operation executes exactly once regardless of retries 💳.
# Server-side Idempotency Cache:
processed_orders = {}
def process_payment(idempotency_key: str, amount: int) -> dict:
if idempotency_key in processed_orders:
# Return exact cached response without re-charging customer! 💳
return processed_orders[idempotency_key], "CACHED"
charge_result = {"charge_id": "ch_9871", "amount": amount, "status": "paid"}
processed_orders[idempotency_key] = charge_result
return charge_result, "PROCESSED"
res1, status1 = process_payment("IDEM_KEY_123", 50)
res2, status2 = process_payment("IDEM_KEY_123", 50)
print(f"Call 1: {status1} | Call 2: {status2} 💳")
# 45. Idempotency Keys in Distributed Payment APIs Network timeouts can cause clients to retry requests, risking duplicate charges. An Idempotency Key (`Idempotency-Key` header) ensures an operation executes exactly once regardless of retries 💳. ```python # Server-side Idempotency Cache: processed_orders = {} def process_payment(idempotency_key: str, amount: int) -> dict: if idempotency_key in processed_orders: # Return exact cached response without re-charging customer! 💳 return processed_orders[idempotency_key], "CACHED" charge_result = {"charge_id": "ch_9871", "amount": amount, "status": "paid"} processed_orders[idempotency_key] = charge_result return charge_result, "PROCESSED" res1, status1 = process_payment("IDEM_KEY_123", 50) res2, status2 = process_payment("IDEM_KEY_123", 50) print(f"Call 1: {status1} | Call 2: {status2} 💳") ``` If an HTTP connection drops after the server completes a payment but before the client receives the response, the client retries with the same key and safely gets the existing receipt without being charged twice! 💳 --- ### Question Why are Idempotency Keys mandatory for high-reliability financial APIs like Stripe? 🧠- [ ] a. Prevents network retries or double-clicks from charging a user multiple times for the exact same transaction 💳 - [ ] b. Bypasses credit card limits - [ ] c. Reduces the payment amount by 5% - [ ] d. Converts USD into cryptocurrency --- ### Challenge Create cache `cache = {}`. Write `dedup(key, val)` returning cached value if key exists, else sets `cache[key] = val` and returns val. Call with `("k", 10)` twice. Print results. 🎯 <details> <summary>Solution</summary> ```python cache = {} def dedup(key, val): if key in cache: return cache[key] cache[key] = val return val print(dedup("k", 10)) print(dedup("k", 20)) ``` </details>