Gin project: a complete REST API · 5 MIN READ
Stop lost updates with versions, ETag and If-Match: 428 when missing, 412 when stale
Version the notes resource, expose the version as an ETag and require If-Match on writes so a stale client cannot overwrite a newer edit.
Two people open the same note. One adds a line; the other fixes the title from the copy loaded earlier, and that second save quietly erases the first edit. Each request was valid on its own. The bug is that the server never asked which version the client was editing. HTTP already has the vocabulary for that question: ETag, If-Match, 412 Precondition Failed and 428 Precondition Required.
gin · A MAP OF THE IDEA
- Version every write
- Return strong ETag
- Require If-Match
- Compare-and-swap in store
Useful when
- Concurrent edits are detected instead of silently overwritten.
- No locks are held while clients read or think.
- Uses standard HTTP headers and statuses that clients and proxies understand.
Watch out
- A check in the handler followed by an unconditional write still races.
- Weak ETags never satisfy If-Match, so writes need strong validators.
Implementation & operation cost: A version column, a conditional UPDATE and client code that handles 412 by re-reading and merging.
A lost update spans two requests
The store's mutex from the CRUD lesson makes each write atomic, but the dangerous gap is not inside a request. It is between one client's GET and its later PUT, while another client writes. A lock cannot cover that gap without holding it across user think time, and abandoned locks are worse than the original bug. Optimistic concurrency accepts that conflicts are rare and detects them at write time instead: every note carries a version, every successful write increments it, and a write names the version it was based on. If the stored version has moved, the write is refused and the client decides what to do. Nothing is locked while people read.
ETag out, If-Match in, compare-and-swap in the store
GET returns the version as a strong ETag such as "1". The guarded PUT requires If-Match, compares it with the current version and asks the store to replace the note only if the version is still the one it checked. The naive route with no checks runs first to reproduce the bug, then the guarded route replays the same two edits.
package main
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"github.com/gin-gonic/gin"
)
type Note struct {
ID string `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
Version int `json:"version"`
}
var (
ErrNotFound = errors.New("notes: not found")
ErrVersionMismatch = errors.New("notes: version mismatch")
)
type MemoryStore struct {
mu sync.Mutex
notes map[string]Note
}
// Replace is a compare-and-swap: it writes only if the stored version still
// equals expected (-1 means "skip the check", used by the naive route).
func (m *MemoryStore) Replace(id string, expected int, title, body string) (Note, error) {
m.mu.Lock()
defer m.mu.Unlock()
n, ok := m.notes[id]
if !ok {
return Note{}, ErrNotFound
}
if expected >= 0 && n.Version != expected {
return Note{}, ErrVersionMismatch
}
n.Title, n.Body, n.Version = title, body, n.Version+1
m.notes[id] = n
return n, nil
}
func (m *MemoryStore) Get(id string) (Note, error) {
m.mu.Lock()
defer m.mu.Unlock()
n, ok := m.notes[id]
if !ok {
return Note{}, ErrNotFound
}
return n, nil
}
func etag(version int) string { return `"` + strconv.Itoa(version) + `"` }
// matchVersion reads If-Match with strong comparison. Weak tags (W/"...") never match.
func matchVersion(header string, current int) bool {
for _, tag := range strings.Split(header, ",") {
tag = strings.TrimSpace(tag)
if tag == "*" || tag == etag(current) {
return true
}
}
return false
}
type noteBody struct {
Title string `json:"title" binding:"required"`
Body string `json:"body"`
}
func newRouter(st *MemoryStore) *gin.Engine {
r := gin.New()
r.GET("/notes/:id", func(c *gin.Context) {
n, err := st.Get(c.Param("id"))
if err != nil {
c.Status(http.StatusNotFound)
return
}
c.Header("ETag", etag(n.Version))
c.JSON(http.StatusOK, n)
})
// The naive route: last write wins.
r.PUT("/naive/notes/:id", func(c *gin.Context) {
var in noteBody
if c.ShouldBindJSON(&in) != nil {
c.Status(http.StatusBadRequest)
return
}
n, _ := st.Replace(c.Param("id"), -1, in.Title, in.Body)
c.JSON(http.StatusOK, n)
})
// The guarded route: the client must prove which version it edited.
r.PUT("/notes/:id", func(c *gin.Context) {
ifMatch := c.GetHeader("If-Match")
if ifMatch == "" {
c.JSON(http.StatusPreconditionRequired, gin.H{"title": "If-Match header is required"})
return
}
var in noteBody
if c.ShouldBindJSON(&in) != nil {
c.Status(http.StatusBadRequest)
return
}
cur, err := st.Get(c.Param("id"))
if err != nil {
c.Status(http.StatusNotFound)
return
}
if !matchVersion(ifMatch, cur.Version) {
c.JSON(http.StatusPreconditionFailed, gin.H{"title": "Note was changed by someone else"})
return
}
// The store re-checks atomically: another writer may have won since Get.
n, err := st.Replace(cur.ID, cur.Version, in.Title, in.Body)
if errors.Is(err, ErrVersionMismatch) {
c.JSON(http.StatusPreconditionFailed, gin.H{"title": "Note was changed by someone else"})
return
}
c.Header("ETag", etag(n.Version))
c.JSON(http.StatusOK, n)
})
return r
}
func do(r http.Handler, method, path, ifMatch, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
if ifMatch != "" {
req.Header.Set("If-Match", ifMatch)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func seed() *MemoryStore {
return &MemoryStore{notes: map[string]Note{
"n1": {ID: "n1", Title: "Trip", Body: "flights", Version: 1},
}}
}
func main() {
gin.SetMode(gin.TestMode)
// Lost update: both clients read version 1, both write, the second silently wins.
st := seed()
r := newRouter(st)
do(r, "PUT", "/naive/notes/n1", "", `{"title":"Trip","body":"flights, hotel"}`) // client A adds the hotel
do(r, "PUT", "/naive/notes/n1", "", `{"title":"Trip to Rome","body":"flights"}`) // client B renames from a stale copy
n, _ := st.Get("n1")
fmt.Printf("naive final: title=%q body=%q\n", n.Title, n.Body)
// The same race with ETag and If-Match.
st = seed()
r = newRouter(st)
tag := do(r, "GET", "/notes/n1", "", "").Header().Get("ETag")
fmt.Println("A and B read ETag", tag)
w := do(r, "PUT", "/notes/n1", tag, `{"title":"Trip","body":"flights, hotel"}`)
fmt.Println("A PUT If-Match", tag, "->", w.Code, "ETag", w.Header().Get("ETag"))
w = do(r, "PUT", "/notes/n1", tag, `{"title":"Trip to Rome","body":"flights"}`)
fmt.Println("B PUT If-Match", tag, "->", w.Code, w.Body.String())
w = do(r, "PUT", "/notes/n1", "", `{"title":"Trip to Rome","body":"flights"}`)
fmt.Println("B PUT without If-Match ->", w.Code, w.Body.String())
w = do(r, "PUT", "/notes/n1", `W/"2"`, `{"title":"Trip to Rome","body":"flights, hotel"}`)
fmt.Println(`B PUT If-Match W/"2" ->`, w.Code)
g := do(r, "GET", "/notes/n1", "", "")
fresh := g.Header().Get("ETag")
w = do(r, "PUT", "/notes/n1", fresh, `{"title":"Trip to Rome","body":"flights, hotel"}`)
fmt.Println("B re-reads", fresh, "and retries ->", w.Code, "ETag", w.Header().Get("ETag"))
fmt.Println("final:", w.Body.String())
}On the naive route both writes succeed and the final body is "flights": client A's hotel is gone and nobody was told. On the guarded route both clients read ETag "1". A writes with If-Match "1" and gets 200 with ETag "2". B writes from the stale copy with If-Match "1" and gets 412. Without If-Match B gets 428, so skipping the header is not a way around the check. W/"2" names the current version but is weak, and If-Match uses strong comparison, so it fails too. B re-reads, gets "2", reapplies the title change onto the current body and receives ETag "3"; the final note keeps both edits. Replace re-checks the version under its own lock because another writer can win between the handler's Get and the write.
The rules HTTP already defines
RFC 9110 defines an entity tag as a quoted string, optionally prefixed with W/ to mark it weak. If-Match is evaluated with strong comparison, so a weak tag can never satisfy it, and the asterisk matches any current representation, which is useful to say "update only if it exists". When the condition is false the server must not perform the method; the usual answer is 412, and RFC 9110 also permits a 2xx when the server can verify that the requested change is already reflected in the current state. RFC 6585 adds 428 for a server that requires conditional requests and receives one without a condition. Send the new ETag with every successful write so the client does not need an extra GET. PATCH needs exactly the same guard as PUT: a partial update made from stale assumptions is still a lost update. In the full service, 412 and 428 go through the problems middleware as two more problem types.
Make the check atomic where the data lives
The version check and the increment must be one operation in the store. A handler that reads the version, compares it and then issues an unconditional write has a race between the compare and the write. In SQL the condition goes into the UPDATE itself, and a statement that matched no rows tells you the condition failed. Do not use updated_at as the version: clock resolution and skew make two writes look simultaneous. Increment the version on every change that alters the representation, and if the representation includes data from elsewhere, such as an author name from another table, either include that in the version or derive the ETag from a hash of the representation.
const replaceNote = `
UPDATE notes
SET title = $1, body = $2, version = version + 1
WHERE id = $3 AND owner_id = $4 AND version = $5
RETURNING version`
func (s *Postgres) Replace(ctx context.Context, owner, id string, expected int, title, body string) (int, error) {
var v int
err := s.db.QueryRowContext(ctx, replaceNote, title, body, id, owner, expected).Scan(&v)
if !errors.Is(err, sql.ErrNoRows) {
return v, err // success, or a real database error
}
// No row matched: the note is gone, or another writer moved the version on.
var exists bool
if err := s.db.QueryRowContext(ctx,
`SELECT EXISTS (SELECT 1 FROM notes WHERE id = $1 AND owner_id = $2)`, id, owner).Scan(&exists); err != nil {
return 0, err
}
if !exists {
return 0, ErrNotFound
}
return 0, ErrVersionMismatch
}This fragment is the PostgreSQL adapter for the same Replace contract; run it against your own database. The WHERE clause checks ID, owner and version in the same statement that increments the version, so two writers holding version 5 cannot both succeed; the second matches zero rows. RETURNING gives the new version for the ETag. On sql.ErrNoRows a second query distinguishes a deleted note, which maps to 404, from a version that moved on, which maps to 412.
What clients and tests must do
On 412 a client re-reads, merges or shows the conflict to the person, and retries with the fresh ETag. Automatically resending the same body with the new ETag is just last-write-wins with extra steps. Conditional writes also interact with retries: if a PUT succeeded but the response was lost, the retry with the old If-Match gets 412 from this implementation, and the client should re-read and notice its change is already there. Test the contract through ServeHTTP: missing header is 428, a stale tag is 412, a weak tag is 412, a fresh tag is 200 with the next ETag, and two goroutines writing with the same tag produce exactly one 200.
TAKE THIS WITH YOU
Expose a version as a strong ETag, require If-Match on PUT and PATCH with 428 when it is absent, and let the store compare and increment the version atomically, answering 412 on mismatch.
Check your understanding
The notes API requires conditional writes. A client sends PUT /notes/n1 without an If-Match header. Which response is correct?
Go to the source
Progress stays in this browser. No account needed.