Implement idempotency and deduplication
Implement idempotency and deduplication
An idempotency key identifies one logical operation. Repeating the same key and payload should return the stored result without applying the effect again. A different payload under the same key is a conflict. Scope keys by caller and operation, and persist the result with the effect atomically when possible.
package main
import ( "errors" "fmt" "sync")
type Entry struct{ Amount, Result int }type Store struct { mu sync.Mutex total int seen map[string]Entry}
func (s *Store) apply(key string, amount int) (int, error) { s.mu.Lock() defer s.mu.Unlock() if key == "" || amount < 1 || amount > 100 { return 0, errors.New("invalid") } if e, ok := s.seen[key]; ok { if e.Amount != amount { return 0, errors.New("conflict") } return e.Result, nil } s.total += amount s.seen[key] = Entry{amount, s.total} return s.total, nil}func main() { s := Store{seen: map[string]Entry{}} for _, a := range []int{5, 5, 7} { n, e := s.apply("request-1", a) fmt.Println(n, e) }}The lock protects check, effect and result together within one process. This toy store has bounded sample inputs, not bounded lifetime storage. It loses all state on restart; it cannot protect multiple replicas. A production database needs a unique scoped key and transaction or equivalent atomic mechanism; external effects may require their own idempotency protocol.
Expected output:
5 <nil>5 <nil>0 conflictKeep caller scopes distinct
package main
import ( "fmt")
type Key struct{ Caller, Operation, ID string }
func main() { seen := map[Key]bool{} a := Key{"alice", "reserve", "1"} b := Key{"bob", "reserve", "1"} seen[a] = true fmt.Println(seen[a], seen[b])}Struct keys avoid delimiter collisions. Authenticate the caller before looking up an old result. Define retention at least as long as the supported retry window and document what happens after expiry. Deduplication is not a universal exactly-once guarantee.
Expected output:
true falseTry it locally
Process message IDs a, a, b using a map, applying an increment only for unseen IDs. Print the final count. Assume one sequential consumer.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Distributed services 03: Implement idempotency and deduplication
Check the lesson objective before moving on.
What should happen if the same key has a different payload?
Why is an in-memory map insufficient across replicas?