There is an HTTP handler in Go 1.24 (standard library only) that accepts POST /payments with the Idempotency-Key header and a JSON body {"order_id":"...","amount":123}. The feature requirement is: for the first successful request for a given key, an external payment API must be called, and a repeated request with the same key must return the same status and body without a new charge. The external API is called synchronously via http.Client and in the test environment may respond slowly or with an error. The system must also terminate request processing correctly when the request context is canceled and must not hold network resources after reading the external API response.
In the PR below, the idempotency cache and external API integration were changed. After the change, complaints appeared: with concurrent repeats for the same key, an extra charge sometimes occurs, and under load the process gradually runs into network resource limits after a series of successful external API calls.
A review of the diff is needed to find the defects.
Assumptions and environment:
GOOS=linux, GOARCH=amd64.memoryStore accesses may happen concurrently from different goroutines in the same process.POST {gatewayURL}/charge with the same JSON, 200 OK and JSON {"confirmation":"..."} on success, any other status is an error.httptest.Server as the gateway, create one Server, and then send several concurrent POST /payments requests with the same Idempotency-Key.200 and JSON {"confirmation":"..."}; if the gateway returned non-200, the handler responds 502 Bad Gateway; if the key is missing — 400.Go 1.24, standard library. Runs in one process, concurrent requests are served in parallel by HTTP server goroutines. A normal net/http transport with keep-alive is assumed, so correctly releasing the resp.Body of outgoing requests is mandatory for connection reuse and for avoiding descriptor/connection leaks.
Use line comments to explain the problem, its impact, the fix and how to test it.