Skip to content

On Your Own: Seat Holds

The Course
•
70 min study

Build a seat-hold service for a small theater, using the same design as the ledger but none of its code. A hold reserves several seats for one customer at once. Customers' apps retry when the network is slow, so the service must recognize repeated requests, and it must never hold half of what was asked for.

The rules

  • The theater has seats 1 to 20. A hold asks for 1 to 4 seats, and every seat must be in range and listed once.
  • Hold(id string, seats []int) takes every requested seat or none. If any seat is already held, return a *TakenError that names the first taken seat and the hold that owns it.
  • A known hold ID with the same seats, in any order, is a retry: return Replayed and change nothing. A known ID with different seats is a conflict.
  • Release(id string) frees a hold's seats. Releasing an unknown or released hold is an error, and a released ID cannot be used again.
  • Report every problem with a hold's seat list at once, using errors.Join, wrapped with hold ID: . Use these messages: a hold takes 1-4 seats for the wrong number of seats, seat N: seat is outside 1-20 and seat N: seat is listed twice for each bad seat, in the order they appear.

Prove it

Write checks, in the style of the project's checks.go, that show each rule holds. They fall into three groups: the first two bullets are holds and retries, the third is bad requests and the last is invariant.

  • a hold that collides on its last seat takes none of the others, and errors.As reads the taken seat and its owner
  • a reordered retry is replayed, a different request with the same ID conflicts, and a released ID is refused
  • a bad request reports every problem, and errors.Is finds each kind. Use Hold("H3", []int{0, 2, 2, 21, 4}), which has five seats, one duplicate and two out of range, and print its joined error on one line, indented by three spaces, with each newline replaced by ;
  • an invariant over 300 seeded random holds and releases: every held seat belongs to exactly one open hold, and the number of held seats equals the sum of the open holds' sizes

This is a larger project than the earlier checkpoints: plan on an hour or more. If you run short of time, build and check the first two groups, and come back to the invariant later.

Reuse the structure, not the code

You already know the shape: validate and normalize, recognize a replay, stage on a copy, check, commit, record. Try to write it without opening the ledger's files. Look at them afterwards and compare.

Exercise

Your turn

Build the seat-hold service and its checks as described. Print passed: and the group's name after each group of checks, the bad request's joined error inside its group, and All seat-hold checks passed at the end. Any failed check should panic with the group's name and the error.

The output should be:

Text
passed: holds and retries
   hold H3: a hold takes 1-4 seats; seat 0: seat is outside 1-20; seat 2: seat is listed twice; seat 21: seat is outside 1-20
passed: bad requests
passed: invariant
All seat-hold checks passed
Your working space Go
package main

func main() {
	// Build the seat-hold service, then check every rule.
}
Hint 1: the idea

Keep two maps: seat to hold ID for the seats that are held, and hold ID to its record, with the normalized seats and a released flag. Staging copies only the first map.

Hint 2: a first step

Start with normalize(seats []int) ([]int, error). It sorts a copy, collects range, duplicate and count problems, and returns errors.Join of them. Every other method can then trust its input.

Worked solution
Run the solution Go
package main

import (
	"errors"
	"fmt"
	"maps"
	"math/rand/v2"
	"slices"
	"strings"
)

const (
	firstSeat, lastSeat = 1, 20
	maxSeatsPerHold     = 4
)

var (
	errSeat      = errors.New("seat is outside 1-20")
	errDuplicate = errors.New("seat is listed twice")
	errCount     = errors.New("a hold takes 1-4 seats")
	errConflict  = errors.New("hold ID reused with different seats")
	errReleased  = errors.New("hold is released")
	errUnknown   = errors.New("hold not found")
)

type TakenError struct {
	Seat  int
	Owner string
}

func (e *TakenError) Error() string {
	return fmt.Sprintf("seat %d is held by %s", e.Seat, e.Owner)
}

type Outcome int

const (
	Held Outcome = iota
	Replayed
)

type hold struct {
	seats    []int
	released bool
}

type Theater struct {
	owners map[int]string
	holds  map[string]hold
}

func NewTheater() *Theater {
	return &Theater{owners: map[int]string{}, holds: map[string]hold{}}
}

func normalize(seats []int) ([]int, error) {
	var problems []error
	if len(seats) < 1 || len(seats) > maxSeatsPerHold {
		problems = append(problems, errCount)
	}
	seen := map[int]bool{}
	for _, seat := range seats {
		if seat < firstSeat || seat > lastSeat {
			problems = append(problems, fmt.Errorf("seat %d: %w", seat, errSeat))
		} else if seen[seat] {
			problems = append(problems, fmt.Errorf("seat %d: %w", seat, errDuplicate))
		}
		seen[seat] = true
	}
	return slices.Sorted(slices.Values(seats)), errors.Join(problems...)
}

func (t *Theater) Hold(id string, seats []int) (Outcome, error) {
	seats, err := normalize(seats)
	if err != nil {
		return 0, fmt.Errorf("hold %s: %w", id, err)
	}
	if previous, exists := t.holds[id]; exists {
		if previous.released {
			return 0, fmt.Errorf("hold %s: %w", id, errReleased)
		}
		if !slices.Equal(previous.seats, seats) {
			return 0, fmt.Errorf("hold %s: %w", id, errConflict)
		}
		return Replayed, nil
	}
	staged := maps.Clone(t.owners)
	for _, seat := range seats {
		if owner, taken := staged[seat]; taken {
			return 0, fmt.Errorf("hold %s: %w", id, &TakenError{Seat: seat, Owner: owner})
		}
		staged[seat] = id
	}
	t.owners = staged
	t.holds[id] = hold{seats: seats}
	return Held, nil
}

func (t *Theater) Release(id string) error {
	h, exists := t.holds[id]
	if !exists {
		return fmt.Errorf("hold %s: %w", id, errUnknown)
	}
	if h.released {
		return fmt.Errorf("hold %s: %w", id, errReleased)
	}
	for _, seat := range h.seats {
		delete(t.owners, seat)
	}
	h.released = true
	t.holds[id] = h
	return nil
}

func checkHolds() error {
	t := NewTheater()
	if _, err := t.Hold("H1", []int{5, 6}); err != nil {
		return err
	}
	_, err := t.Hold("H2", []int{3, 4, 5})
	var taken *TakenError
	if !errors.As(err, &taken) || *taken != (TakenError{Seat: 5, Owner: "H1"}) {
		return fmt.Errorf("collision: got %v", err)
	}
	if _, held := t.owners[3]; held {
		return errors.New("a failed hold took seat 3")
	}
	if outcome, err := t.Hold("H1", []int{6, 5}); err != nil || outcome != Replayed {
		return fmt.Errorf("retry: got %v, %v", outcome, err)
	}
	if _, err := t.Hold("H1", []int{7}); !errors.Is(err, errConflict) {
		return fmt.Errorf("reused ID: got %v", err)
	}
	if err := t.Release("H1"); err != nil {
		return err
	}
	if _, err := t.Hold("H1", []int{5, 6}); !errors.Is(err, errReleased) {
		return fmt.Errorf("hold after release: got %v", err)
	}
	if err := t.Release("H1"); !errors.Is(err, errReleased) {
		return fmt.Errorf("second release: got %v", err)
	}
	if err := t.Release("H9"); !errors.Is(err, errUnknown) {
		return fmt.Errorf("unknown release: got %v", err)
	}
	return nil
}

func checkRequests() error {
	_, err := NewTheater().Hold("H3", []int{0, 2, 2, 21, 4})
	for _, want := range []error{errSeat, errDuplicate, errCount} {
		if !errors.Is(err, want) {
			return fmt.Errorf("%v does not include %v", err, want)
		}
	}
	fmt.Println("  ", strings.ReplaceAll(err.Error(), "\n", "; "))
	for _, seats := range [][]int{{1}, {17, 18, 19, 20}} {
		if _, err := NewTheater().Hold("H4", seats); err != nil {
			return fmt.Errorf("valid request %v: got %v", seats, err)
		}
	}
	return nil
}

func checkInvariant() error {
	random := rand.New(rand.NewPCG(4, 9))
	t := NewTheater()
	for step := 1; step <= 300; step++ {
		id := fmt.Sprintf("R%d", random.IntN(12))
		if random.IntN(3) == 0 {
			_ = t.Release(id)
		} else {
			seats := make([]int, 1+random.IntN(maxSeatsPerHold))
			for i := range seats {
				seats[i] = firstSeat + random.IntN(lastSeat)
			}
			_, _ = t.Hold(id, seats)
		}
		total := 0
		for id, h := range t.holds {
			if h.released {
				continue
			}
			total += len(h.seats)
			for _, seat := range h.seats {
				if t.owners[seat] != id {
					return fmt.Errorf("step %d: seat %d belongs to %q, not %s", step, seat, t.owners[seat], id)
				}
			}
		}
		if total != len(t.owners) {
			return fmt.Errorf("step %d: %d seats held, open holds have %d", step, len(t.owners), total)
		}
	}
	return nil
}

func main() {
	for _, check := range []struct {
		name string
		run  func() error
	}{{"holds and retries", checkHolds}, {"bad requests", checkRequests}, {"invariant", checkInvariant}} {
		if err := check.run(); err != nil {
			panic(fmt.Sprintf("%s: %v", check.name, err))
		}
		fmt.Println("passed:", check.name)
	}
	fmt.Println("All seat-hold checks passed")
}
Text
passed: holds and retries
   hold H3: a hold takes 1-4 seats; seat 0: seat is outside 1-20; seat 2: seat is listed twice; seat 21: seat is outside 1-20
passed: bad requests
passed: invariant
All seat-hold checks passed

H2 collided on seat 5 after staging seats 3 and 4, and the check confirms that seat 3 stayed free. The bad request reported four problems from one call. Duplicate seats are rejected in normalize, so staging never sees one, and the random run picks seats freely so that collisions, duplicates and releases all happen. Compare your version with the ledger's Order and Cancel: the steps should line up one to one.

Check your own work

Before you open the solution, or after, test your checks against these questions. Each is a bug that a passing run alone wouldn't rule out.

  • Do your checks fail when the code is wrong? Make Hold write seats directly instead of on a copy, and the collision check must fail. Remove the sort before comparing a retry, and the replay check must fail.
  • Is the error a value, not just text? errors.As reads the taken seat and its owner as fields, and errors.Is finds each joined sentinel. Change one %w to %v and a check must fail.
  • Is a released ID really retired? Releasing it twice is an error, and holding it again, with the same seats or different ones, is refused.
  • Does the invariant look at the right thing? It compares two independent records, the seat owners and the open holds, after every step, not only at the end. Break Release so it forgets one seat and the invariant must name the step.
  • Is the random run repeatable? It uses a fixed seed, so a failure happens at the same step on every run.

Was this article helpful?

Your response is saved on this device.