Gin project: a complete REST API · 5 MIN READ
Make POST safe to retry with Idempotency-Key: fingerprint, reserve, replay and expire
Add Idempotency-Key handling to POST /notes so retries replay the original response, conflicting reuse is rejected and in-flight duplicates wait.
A mobile client sends POST /notes, the connection drops before the 201 arrives, and the client retries. Without help the server creates a second note. HTTP defines PUT and DELETE as idempotent; POST is not, so the client supplies a unique key and the server promises that one key yields at most one effect and one stored response. This lesson adds that promise to the notes API.
gin · A MAP OF THE IDEA
- Read key and fingerprint
- Reserve key atomically
- Run and capture response
- Replay until expiry
Useful when
- Clients can retry ambiguous POSTs without creating duplicates.
- Changed payloads and concurrent duplicates are rejected explicitly.
- Replays return the identical status, headers and body.
Watch out
- A separate idempotency store leaves a crash window; prefer one transaction with the effect.
- Unscoped keys can replay one tenant's response to another.
Implementation & operation cost: One record per write request for the retention period, a lease for pending entries and an extra read and write on every POST.
Why a retry duplicates, and what the key promises
A timeout is ambiguous: the request may have failed before the handler ran, or succeeded with only the response lost. The client cannot tell, so a safe retry needs the server to remember. The client generates a random key, typically a UUID, for each logical operation and reuses it only when retrying that operation. The server keeps one record per caller and key with a fingerprint of the request, its state and, once finished, the response. Each arrival then has exactly one outcome: a new key runs the handler; a finished identical request is replayed; an identical request still running gets 409; the same key with a different request gets 422; a missing key gets 400. These choices follow the IETF HTTPAPI working group's Idempotency-Key header draft, which is still a draft, so document them in your API contract.
A middleware that reserves, captures and replays
Idempotent runs before the create handler. It reads and restores the body, fingerprints the request, and calls Begin, which checks and reserves the key in one critical section. On a fresh reservation it swaps c.Writer for a captureWriter that copies everything written, runs the handler with c.Next, and stores the status, Location and body. A deferred function releases the reservation when the handler ends in a 5xx or panics. The program holds one request open with channels so the in-progress case is deterministic.
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
)
// ---- the idempotency record store ----
type record struct {
fingerprint [32]byte
done bool
status int
location string
body []byte
expires time.Time
}
type outcome int
const (
started outcome = iota // key reserved; run the handler
replay // same request finished before; return the stored response
mismatch // same key, different request
inProgress // same request is still running
)
type IdempotencyStore struct {
mu sync.Mutex
records map[string]*record
now func() time.Time
ttl time.Duration
}
// Begin checks and reserves a key in one critical section.
func (s *IdempotencyStore) Begin(key string, fp [32]byte) (outcome, record) {
s.mu.Lock()
defer s.mu.Unlock()
if r, ok := s.records[key]; ok && s.now().Before(r.expires) {
switch {
case r.fingerprint != fp:
return mismatch, record{}
case !r.done:
return inProgress, record{}
default:
return replay, *r
}
}
s.records[key] = &record{fingerprint: fp, expires: s.now().Add(s.ttl)}
return started, record{}
}
func (s *IdempotencyStore) Finish(key string, status int, location string, body []byte) {
s.mu.Lock()
defer s.mu.Unlock()
if r, ok := s.records[key]; ok {
r.done, r.status, r.location, r.body = true, status, location, body
}
}
func (s *IdempotencyStore) Release(key string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.records, key)
}
// ---- the Gin middleware ----
type captureWriter struct {
gin.ResponseWriter
body bytes.Buffer
}
func (w *captureWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
func (w *captureWriter) WriteString(s string) (int, error) {
w.body.WriteString(s)
return w.ResponseWriter.WriteString(s)
}
func problem(c *gin.Context, status int, title string) {
c.Header("Content-Type", "application/problem+json")
c.AbortWithStatusJSON(status, gin.H{"title": title, "status": status})
}
func Idempotent(store *IdempotencyStore) gin.HandlerFunc {
return func(c *gin.Context) {
key := c.GetHeader("Idempotency-Key")
if key == "" || len(key) > 64 {
problem(c, http.StatusBadRequest, "Idempotency-Key header is required")
return
}
body, err := io.ReadAll(c.Request.Body) // already bounded by MaxBytesReader upstream
if err != nil {
problem(c, http.StatusBadRequest, "Unreadable body")
return
}
c.Request.Body = io.NopCloser(bytes.NewReader(body))
scope := c.GetString("principal") + "\x00" + key
fp := sha256.Sum256(append([]byte(c.Request.Method+" "+c.FullPath()+"\n"), body...))
switch result, rec := store.Begin(scope, fp); result {
case replay:
c.Header("Location", rec.location)
c.Header("Idempotent-Replayed", "true")
c.Data(rec.status, "application/json; charset=utf-8", rec.body)
c.Abort()
return
case mismatch:
problem(c, http.StatusUnprocessableEntity, "Idempotency-Key was used with a different request")
return
case inProgress:
c.Header("Retry-After", "1")
problem(c, http.StatusConflict, "A request with this Idempotency-Key is in progress")
return
}
finished := false
defer func() {
if !finished {
store.Release(scope) // 5xx or panic: let the client retry
}
}()
cw := &captureWriter{ResponseWriter: c.Writer}
c.Writer = cw
c.Next()
if status := cw.Status(); status < http.StatusInternalServerError {
store.Finish(scope, status, cw.Header().Get("Location"), bytes.Clone(cw.body.Bytes()))
finished = true
}
}
}
// ---- the resource ----
type Note struct {
ID string `json:"id"`
Title string `json:"title"`
}
type Notes struct {
mu sync.Mutex
items []Note
onCreate func(title string) // demo hook to hold a request open
}
func (n *Notes) Create(title string) Note {
if n.onCreate != nil {
n.onCreate(title)
}
n.mu.Lock()
defer n.mu.Unlock()
note := Note{ID: fmt.Sprintf("n%d", len(n.items)+1), Title: title}
n.items = append(n.items, note)
return note
}
func newRouter(store *IdempotencyStore, notes *Notes) *gin.Engine {
r := gin.New()
r.Use(func(c *gin.Context) { c.Set("principal", "u1") }) // stand-in for real authentication
r.POST("/notes", Idempotent(store), func(c *gin.Context) {
var in struct {
Title string `json:"title" binding:"required"`
}
if err := c.ShouldBindJSON(&in); err != nil {
problem(c, http.StatusBadRequest, "Malformed note")
return
}
note := notes.Create(in.Title)
c.Header("Location", "/notes/"+note.ID)
c.JSON(http.StatusCreated, note)
})
return r
}
func post(r http.Handler, key, body string) string {
req := httptest.NewRequest(http.MethodPost, "/notes", strings.NewReader(body))
if key != "" {
req.Header.Set("Idempotency-Key", key)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
line := fmt.Sprint(w.Code)
for _, h := range []string{"Location", "Idempotent-Replayed", "Retry-After"} {
if v := w.Header().Get(h); v != "" {
line += " " + h + "=" + v
}
}
if w.Code >= 400 {
line += " " + w.Body.String()
}
return line
}
func main() {
gin.SetMode(gin.TestMode)
clock := time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC)
store := &IdempotencyStore{records: map[string]*record{}, ttl: 24 * time.Hour,
now: func() time.Time { return clock }}
entered, release := make(chan struct{}), make(chan struct{})
notes := &Notes{onCreate: func(title string) {
if title == "Slow report" {
entered <- struct{}{}
<-release
}
}}
r := newRouter(store, notes)
fmt.Println("first k1: ", post(r, "k1", `{"title":"Groceries"}`))
fmt.Println("retry k1: ", post(r, "k1", `{"title":"Groceries"}`))
fmt.Println("reuse k1: ", post(r, "k1", `{"title":"Errands"}`))
fmt.Println("no key: ", post(r, "", `{"title":"Errands"}`))
first := make(chan string)
go func() { first <- post(r, "k2", `{"title":"Slow report"}`) }()
<-entered // the first k2 request now holds the reservation
fmt.Println("second k2: ", post(r, "k2", `{"title":"Slow report"}`))
close(release)
fmt.Println("first k2: ", <-first)
clock = clock.Add(25 * time.Hour) // past the 24h retention window
fmt.Println("late k1: ", post(r, "k1", `{"title":"Groceries"}`))
fmt.Println("notes created:", len(notes.items))
}The first k1 creates n1. The retry with the same body never reaches the handler: it gets the stored 201, the same Location and Idempotent-Replayed=true. Reusing k1 with a different title is 422, and a request without a key is 400. For k2, a goroutine starts the slow request, and main waits on entered until the handler is inside Create, so the reservation certainly exists; the second k2 then gets 409 with Retry-After. Closing release lets the first k2 finish with 201 for n2. Finally the fake clock moves 25 hours forward, past the 24-hour retention, and the old k1 creates n3: an expired key is a new request. Three notes exist, not five.
Fingerprints, scope and what gets stored
The fingerprint is SHA-256 over the method, the route pattern from c.FullPath and the raw body bytes. Byte equality is strict: a client that re-serializes the same JSON with different key order or spacing gets 422. Most APIs accept that and tell clients to resend the identical bytes; canonicalizing JSON before hashing is possible but easy to get subtly wrong. Scope every key by the authenticated principal. Without scope, two tenants that happen to choose the same key would see each other's responses, a data leak rather than a duplicate. Bound the key length and the body size before reading; the binding-limits lesson covers MaxBytesReader. Store whatever the client needs to treat a replay as the original, here status, Location and body. The Idempotent-Replayed header is a convention some APIs use, not a standard, but it makes replays visible in logs and client debugging.
In progress, expiry and the crash window
Begin must check and reserve atomically or two concurrent first attempts both run. The mutex does it here; in PostgreSQL use INSERT ... ON CONFLICT DO NOTHING and check the affected row count, and in Redis use SET with NX and an expiry. A pending record also needs a lease: if the process dies mid-request, nothing releases it, and every retry gets 409 until the record expires. Give pending records a short lock expiry separate from the retention TTL, and make the retention longer than any client's retry window. The deeper gap is that the note and the idempotency record live in different stores. A crash after the note is committed but before Finish loses the stored response, and a retry after the lease runs out creates a duplicate; releasing on a 5xx has the same hole if the effect committed before the error. The robust design writes the idempotency record in the same database transaction as the note, so the effect and the response commit together.
Test every outcome, including the concurrent one
Cover each branch through ServeHTTP: a fresh key, an identical replay that leaves exactly one note in the store, a changed body that returns 422, a missing key, an in-progress duplicate held open with channels as the program does, expiry driven by an injected clock and a 5xx that releases the key so the retry runs again. Add a test that fires many identical requests from goroutines and asserts that the handler ran once, and run the suite with -race. Assert the replayed body byte for byte, because the promise is the same response, not a similar one.
TAKE THIS WITH YOU
Reserve each principal-scoped key atomically with a request fingerprint, replay the stored response for identical retries, answer 422 for a changed payload and 409 while in progress, and retain records longer than clients retry.
Check your understanding
A client reuses Idempotency-Key k1 with a different JSON body after the first request succeeded. What should the server do?
Go to the source
Progress stays in this browser. No account needed.