Menu

How to stop double charges in Go with idempotency keys
📰

How to stop double charges in Go with idempotency keys

DEV Community: go·Bismarck Ndou·3 days ago
#zJIDnUyG
#devtogo#devto#dev#request#store
Long article (781 words) — no AI summary yet.
Reading 0:00
15s threshold

A client sends POST /payments . Your server charges the card, but the response is lost to a timeout. The client retries, and the customer is charged twice.

Retrying is the right thing for a client to do. The bug is that the server can't tell a retry from a new request.

The standard fix is an idempotency key . The client sends the same Idempotency-Key header on every retry of one operation. The server runs the operation once and replays the stored response for every retry. Stripe popularized this, and there is an IETF draft for the header.

I couldn't find a Go library I liked, so I built one: go-idempotency .

Using it

store := memory . New ( ) defer store . Close ( )

mw := idempotency . New ( store )

mux := http . NewServeMux ( ) mux . HandleFunc ( "POST /payments" , createPayment )

http . ListenAndServe ( ":8080" , mw .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.