Skip to content

Recognize a Retry

The Course
•
24 min study

Requests get sent twice. A connection drops after the server applied an order but before the reply arrived, and the client, seeing no answer, sends the order again. If the ledger treats the second copy as a new order, the customer has reserved twice as much as they wanted. The client cannot avoid this, because it cannot tell "the order was lost" from "the reply was lost". The fix belongs on the receiving side: the client gives each request an ID, and the ledger remembers which IDs it has applied.

An operation that has the same effect whether it runs once or several times is called idempotent. Reserving with an ID makes order A1 tent:2 idempotent: the first copy reserves, and every later identical copy is recognized as a replay and changes nothing.

Predict and run

The same order arrives twice, then a different order reuses its ID. What happens to the stock each time?

Predict, then run Go
package main

import (
	"errors"
	"fmt"
	"slices"
)

var errConflict = errors.New("order ID reused with different lines")

type Line struct {
	Item     string
	Quantity int
}

type Ledger struct {
	stock  map[string]int
	orders map[string][]Line
}

func (l *Ledger) Order(id string, lines []Line) (string, error) {
	if previous, exists := l.orders[id]; exists {
		if !slices.Equal(previous, lines) {
			return "", fmt.Errorf("order %s: %w", id, errConflict)
		}
		return "replayed", nil
	}
	for _, line := range lines {
		l.stock[line.Item] -= line.Quantity
	}
	l.orders[id] = slices.Clone(lines)
	return "reserved", nil
}

func main() {
	l := &Ledger{stock: map[string]int{"tent": 5}, orders: map[string][]Line{}}
	for _, lines := range [][]Line{{{"tent", 2}}, {{"tent", 2}}, {{"tent", 3}}} {
		outcome, err := l.Order("A1", lines)
		fmt.Println(outcome, err, l.stock["tent"])
	}
}
Check your prediction
Text
reserved <nil> 3
replayed <nil> 3
 order A1: order ID reused with different lines 3

The stock went from 5 to 3 once, and stayed there. The retry matched the stored lines and was recognized, and the third request was refused because it reused A1 for a different order: applying it, or silently ignoring it, would both hide a mistake on the client's side. Change the ID of the third request to A2 and predict the stock again.

Compare the meaning, not the text

To decide whether a request is a replay, compare what it means. tent:2 drill:1 and drill:1 tent:2 ask for the same thing, so a retry that lists the lines in another order must still be recognized. The simplest way is to normalize every order into one canonical form before storing or comparing it. The project's parser sorts each order's lines by item, so slices.Equal compares like with like. Without the sort, a harmless reordering would be rejected as a conflict, and that is one of the mutations the project's checks catch.

Normalize before comparing Go
package main

import (
	"cmp"
	"fmt"
	"slices"
)

type Line struct {
	Item     string
	Quantity int
}

func normalize(lines []Line) []Line {
	sorted := slices.Clone(lines)
	slices.SortFunc(sorted, func(a, b Line) int { return cmp.Compare(a.Item, b.Item) })
	return sorted
}

func main() {
	first := []Line{{"tent", 2}, {"drill", 1}}
	retry := []Line{{"drill", 1}, {"tent", 2}}
	fmt.Println(slices.Equal(first, retry))
	fmt.Println(slices.Equal(normalize(first), normalize(retry)))
	fmt.Println(first)
}
Text
false
true
[{tent 2} {drill 1}]

normalize sorts a clone, so the caller's slice keeps its order. Sorting in place would surprise any caller that still uses its slice afterwards.

Decide what a failed request records

A design choice hides here: when an order is rejected, is its ID used up? The project says no. Only a successful reservation records the ID, so a client whose order failed for lack of stock can restock and try again with the same ID. The cost is that a replay of a failed order is evaluated again and might succeed the second time. The other choice, recording failures too, gives every ID exactly one outcome forever. Neither is wrong, but the choice must be written down and tested, and the project's checks do both.

Return the outcome, not just nil

The ledger returns Reserved or Replayed rather than only nil. Both are successes, but a caller may want to know which one happened: for example, to avoid sending a second confirmation email. An outcome value makes that possible without guessing from the stock.

Practice

Exercise

Your turn

Write a Bookings type with Book(id string, seats []int) (string, error). Normalize the seats by sorting a copy. A new ID books its seats, unless one of them is already taken, in which case nothing is booked. A known ID with the same seats returns replayed, and with different seats returns errConflict. Check booking B1 for seats 4 and 2, retrying it as 2 and 4, booking B2 for 3 and 4, and booking B1 for seat 9, printing each result. Finally print how many seats are taken: it proves the failed B2 request didn't take seat 3 on its way to finding seat 4 held.

The output should be:

Text
booked <nil>
replayed <nil>
 booking B2: seat 4 is held by B1
 booking B1: booking ID reused with different seats
2

A line that starts with a space comes from printing an empty string before an error.

Your working space Go
package main

func main() {
	// Write Bookings and Book, then check the four requests.
}
Hint 1: the idea

Check the ID first: a replay must not even look at whether the seats are free, because it is the request that took them.

Hint 2: a first step

Keep taken map[int]string from seat to booking ID, and bookings map[string][]int from ID to normalized seats. Check every seat before marking any of them.

Worked solution
Run the solution Go
package main

import (
	"errors"
	"fmt"
	"slices"
)

var errConflict = errors.New("booking ID reused with different seats")

type Bookings struct {
	taken    map[int]string
	bookings map[string][]int
}

func (b *Bookings) Book(id string, seats []int) (string, error) {
	seats = slices.Sorted(slices.Values(seats))
	if previous, exists := b.bookings[id]; exists {
		if !slices.Equal(previous, seats) {
			return "", fmt.Errorf("booking %s: %w", id, errConflict)
		}
		return "replayed", nil
	}
	for _, seat := range seats {
		if owner, taken := b.taken[seat]; taken {
			return "", fmt.Errorf("booking %s: seat %d is held by %s", id, seat, owner)
		}
	}
	for _, seat := range seats {
		b.taken[seat] = id
	}
	b.bookings[id] = seats
	return "booked", nil
}

func main() {
	b := &Bookings{taken: map[int]string{}, bookings: map[string][]int{}}
	fmt.Println(b.Book("B1", []int{4, 2}))
	fmt.Println(b.Book("B1", []int{2, 4}))
	fmt.Println(b.Book("B2", []int{3, 4}))
	fmt.Println(b.Book("B1", []int{9}))
	fmt.Println(len(b.taken))
}
Text
booked <nil>
replayed <nil>
 booking B2: seat 4 is held by B1
 booking B1: booking ID reused with different seats
2

slices.Sorted(slices.Values(seats)) collects a sorted copy, so the caller's slice is untouched. B2 failed on seat 4 without taking seat 3, because every seat is checked before any is marked, and the final count of 2 confirms it.

Was this article helpful?

Your response is saved on this device.