Design consistent errors and idempotency
Design consistent errors and idempotency
Clients need a stable machine-readable error code, not just free-form text. Use a documented HTTP status and a small public response shape. Keep internal errors in protected logs, not in the response. For operations that might be retried after a lost response, explicitly design deduplication rather than assuming a POST can safely run twice.
package main
import ( "encoding/json" "fmt" "net/http/httptest")
type Problem struct { Code string `json:"code"` Message string `json:"message"`}
func main() { w := httptest.NewRecorder() w.Header().Set("Content-Type", "application/json") w.WriteHeader(409) if e := json.NewEncoder(w).Encode(Problem{"stock_conflict", "Not enough stock"}); e != nil { panic(e) } fmt.Println(w.Code) fmt.Print(w.Body.String())}Code is part of the API contract; clients can branch on it without comparing translated message text. This is a custom JSON error envelope, not a claim of RFC Problem Details compliance. Use 400 for malformed requests, 409 for conflicting current state and 500 for unexpected failures. Do not send database errors or stack traces to the caller.
Expected output:
409{"code":"stock_conflict","message":"Not enough stock"}Deduplicate a repeated creation
package main
import ( "fmt" "sync")
type Entry struct { Body string ID int}type Store struct { mu sync.Mutex entries map[string]Entry next int}
func (s *Store) create(key, body string) (int, int) { s.mu.Lock() defer s.mu.Unlock() if key == "" { return 0, 400 } if old, ok := s.entries[key]; ok { if old.Body != body { return 0, 409 } return old.ID, 201 } if s.entries == nil { s.entries = map[string]Entry{} } s.next++ s.entries[key] = Entry{body, s.next} return s.next, 201}func main() { s := Store{} for _, body := range []string{"book", "book", "pen"} { id, status := s.create("demo-key", body) fmt.Println(id, status) } fmt.Println(s.next)}Under a single mutex the lookup, creation and stored result form one operation. Reusing the key with a different body is rejected. This single-principal, single-operation example compares exact synthetic strings. Production needs keys scoped to authenticated identity and operation, bounded size and retention, a defined request fingerprint, durable atomic persistence, and a policy for in-flight requests and failures. A header alone does not provide idempotency.
Expected output:
1 2011 2010 4091Try it locally
Create two orders with different keys and identical bodies, then retry the first key. Print each ID/status pair and the total number of created orders.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
REST API 05: Design consistent errors and idempotency
Check the lesson objective before moving on.
A key is reused with a different payload. What does this API do?
What protects deduplication across processes?