Skip to content

Checkpoint: Apply a Batch Exactly Once

The Course
•
30 min study

Today's three lessons each guard against one way a ledger goes wrong: a sum that passes its limit, a batch that half-applies, and a retry that applies twice. In the project they meet in one method. This checkpoint asks you to build that method for a smaller problem, a shipment register, and to prove each guarantee with a check that would fail without it.

What you will use

  • A capacity check that cannot overflow. Each bin holds at most 50 units, and the check compares quantity > limit-have.
  • Staging. Apply a shipment's lines to maps.Clone of the bins and assign the copy only after the last line passes.
  • An ID per shipment. A known ID with the same normalized lines is a replay and changes nothing. A known ID with different lines is a conflict.
  • Normalization. Sort a copy of the lines by bin before comparing or storing them.

Plan before you type

  1. Declare the Line type, the Register type with its two maps, and a sentinel for conflicts.
  2. Write Receive(id string, lines []Line) (string, error): normalize, check the ID, stage, check each line, commit.
  3. Store the normalized lines under the ID only after the commit.
  4. Write checks: a shipment that overfills its second bin must leave the first bin unchanged, a reordered retry must be replayed, and a reused ID must conflict.
  5. Finish by checking that a bin can be filled to exactly 50.
Prove each guard is needed

Remove one guard at a time and run your checks. Replace maps.Clone(r.bins) with r.bins, delete the sort, or change > to >= in the capacity check. Each change should make a different check fail. If one does not, add the check that would catch it.

Mistakes worth checking for

  • A rejected shipment still records its ID, so fixing it and sending it again is reported as a conflict.
  • The retry is compared before normalizing, so B:5 A:3 conflicts with A:3 B:5.
  • The ID is stored before the capacity checks, so a failed shipment blocks its ID forever.
  • The capacity check computes have+quantity first: correct for small numbers, wrong near the top of the type.
Exercise

Your turn

Build the register as described, with bins A and B starting at 40 and 10 units and a capacity of 50. Check a shipment S1 of A:5 and B:45, which must fail and change nothing. Then receive S2 of B:5 and A:10, replay it as A:10 and B:5, and send S2 again as A:1. Print the bins at the end.

The output should be:

Text
 shipment S1: bin B would hold more than 50
map[A:40 B:10]
received <nil>
replayed <nil>
 shipment S2: shipment ID reused with different lines
map[A:50 B:15]

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

Your working space Go
package main

type Line struct {
	Bin      string
	Quantity int
}

func main() {
	// Build the register and Receive, then check the four shipments.
}
Hint 1: the idea

The method has three phases in a fixed order: recognize a replay, stage and check, then commit and record. Each phase can return early, and none of them changes anything before the commit.

Hint 2: a first step

Start Receive with lines = slices.Clone(lines) and a slices.SortFunc by bin, then look up r.shipments[id].

Worked solution
Run the solution Go
package main

import (
	"cmp"
	"errors"
	"fmt"
	"maps"
	"slices"
)

type Line struct {
	Bin      string
	Quantity int
}

const capacity = 50

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

type Register struct {
	bins      map[string]int
	shipments map[string][]Line
}

func (r *Register) Receive(id string, lines []Line) (string, error) {
	lines = slices.Clone(lines)
	slices.SortFunc(lines, func(a, b Line) int { return cmp.Compare(a.Bin, b.Bin) })
	if previous, exists := r.shipments[id]; exists {
		if !slices.Equal(previous, lines) {
			return "", fmt.Errorf("shipment %s: %w", id, errConflict)
		}
		return "replayed", nil
	}
	staged := maps.Clone(r.bins)
	for _, line := range lines {
		have := staged[line.Bin]
		if line.Quantity > capacity-have {
			return "", fmt.Errorf("shipment %s: bin %s would hold more than %d", id, line.Bin, capacity)
		}
		staged[line.Bin] = have + line.Quantity
	}
	r.bins = staged
	r.shipments[id] = lines
	return "received", nil
}

func main() {
	r := &Register{bins: map[string]int{"A": 40, "B": 10}, shipments: map[string][]Line{}}
	fmt.Println(r.Receive("S1", []Line{{"A", 5}, {"B", 45}}))
	fmt.Println(r.bins)
	fmt.Println(r.Receive("S2", []Line{{"B", 5}, {"A", 10}}))
	fmt.Println(r.Receive("S2", []Line{{"A", 10}, {"B", 5}}))
	fmt.Println(r.Receive("S2", []Line{{"A", 1}}))
	fmt.Println(r.bins)
}
Text
 shipment S1: bin B would hold more than 50
map[A:40 B:10]
received <nil>
replayed <nil>
 shipment S2: shipment ID reused with different lines
map[A:50 B:15]

S1 staged five units into bin A before bin B failed, and the bins show no trace of it. S2 filled bin A to exactly 50, its reordered retry was recognized, and the third request was refused without changing anything.

Was this article helpful?

Your response is saved on this device.