how do i make a payment-style post endpoint safe to retry?

api-designhttpidempotency4 replies · 3 views · started
  1. Im building an API where clients create orders with a POST 😂 Mobile clients on bad connections sometimes time out and retry, and weve ended up with duplicate orders a few times.

    customers notice duplicates immediaetly, and refunding them by hand is getting old.

    thinking

    4
  2. ahh classic two things to check. Also validate that a reused key comes with the same request body. If a client accidentally reuses a key for a different order, you should return an error rather than silently replaying teh old response. Store a hash of teh request payload with the key and compare. good luck man!

    11 0 helpful
  3. wait do you control the clients, sooo u can make them send a key, or is this a public API?

    1 0 helpful
  4. its a public api so i cant really force them to change how they send requests, but i'm hoping to implement an idempotency-key header. i want the clients to generate a unique uuid and send that with their order request so my backend can track it. i dont want to have to manually check every single request body cuz that would be a nightmare lol!!

    2 0 helpful
  5. honestly, if u dont want to manually hash every body, u gotta be careful. just checking the header isnt enough cuz a malicious client could send the same uuid with different item amounts or addresses... thats how u end up with successful duplicates that look different.

    in a setup like mine, i'd just store the idempotency key in a fast cache like redis with a TTL. when the request hits, check if the key eixsts. if it does, just return teh cached response. if it doesnt, process the order and save teh result. it keeps the db clean and stops the double-processing before it even hits your order logic. also, make sure your DB transaction wraps the 'check key' and 'create order' steps sooo u dont get race conditions if two identical requests hit at the exact same millisecond. 🙄

    2 0 helpful

Reply to this topic

Sign in or create an account to reply.