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 .…