How to Build Race-Safe Idempotent POST Endpoints in Go Using Postgres
Duplicate writes in HTTP APIs occur when a client retries a timed-out request that the server already processed, a common problem on mobile networks and Kubernetes deployments. The standard solution is an idempotency key, where the client sends a unique identifier per operation and the server ensures it executes only once. A naive check-then-execute pattern fails under concurrency because two simultaneous requests can both pass the initial lookup before either stores a result. The correct approach uses a Postgres INSERT with ON CONFLICT DO NOTHING to atomically reserve the key before execution, making the database's unique index the race arbiter. A row count of 1 signals the request won the race and may proceed, while 0 means another request already holds the key and execution must be skipped.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in