Room booking with holds
Hold a room for several nights while a guest pays, then confirm or let it expire. The data structure is small. The test is what happens when 100 guests want the same nights.
- 1A night belongs to one hold. It is free when that hold is not live, so expiry and cancel need no cleanup.
- 2All nights or none: check every night before writing any.
- 3One lock per room, taken in sorted order, so a stay across rooms cannot deadlock.
- 4Read the clock after the locks. A clock read before the wait can sell a night twice.
Build a room booking service as an HTTP API, in memory. Clients list rooms and their free nights for a date range. A client places a hold on a room for several nights, and the hold expires. A client can confirm or cancel a hold. Many clients call the service at once, and no night may be sold twice.
| ask | answer assumed |
|---|---|
| Is the last date a night of the stay? | No. It is the day of leaving. |
| Can one hold cover several rooms? | Yes. All rooms and all nights, or nothing. |
| Who sets the expiry? | The client sends ttl_ms, up to one hour, so tests stay fast. |
| Confirm after the expiry? | 409, even if the nights are still free. |
| Can a confirmed booking be cancelled? | Yes. Its nights come free. |
| Longest stay? | 90 nights. |
Before I type, I confirm that the last date is the day of leaving, and that a hold may span rooms.
| request | success | errors |
|---|---|---|
| PUT /rooms/{id} | 200 id | |
| GET /rooms?from=&to= | 200 rooms | 400 |
| POST /holds | 201 hold | 400, 404, 409 |
| POST /holds/{id}/confirm | 200 hold | 404, 409 |
| POST /holds/{id}/cancel | 200 hold | 404 |
- POST /holds takes a list of rooms, from, to and ttl_ms. Dates are YYYY-MM-DD.
- Each room in the list has id and free, the free nights in the range.
- A hold has id, rooms, nights, status and expires_at.
Confirm and cancel are safe to retry. A taken night is 409, and so is a hold that has ended.
| by | build | proof | if you are late |
|---|---|---|---|
| 15 min | The kit, renamed. Rooms, the list of nights, the free list, one hold. | TestRooms | Skip the limits on stay length and TTL. Add them in the last 5 minutes. |
| 30 min | All nights or none. Confirm and cancel. Expiry checked on read. | TestHoldConfirmCancel, TestExpiry | Keep one global mutex for now. It is correct, and it is one change to split. |
| 45 min | One lock per room, in sorted order. Holds that span rooms. Race test. | TestParallelHolds | Keep the global mutex and say the lock order out loud. |
I keep a running service at each checkpoint. If I am late at 30 minutes, I finish one room and describe the lock order.
Each night points at the hold that owns it. Liveness is a question I ask the hold, so nothing has to run when a hold expires.
| part | value |
|---|---|
| Lines, with tests | 476 |
| Typed characters | 9,936 |
| Typing at 500 a minute | 19:52 |
| Typing at 300 a minute | 33:07 |
| Left for thinking, at 500 a minute | 25:08 |
| Dependencies | 0 |
- Build the store interface from the kit. It carries over to the talk.
- In the room, keep every file in package main. Here main.go sits in its own folder, so the production version can import the build.
Typed characters leave out imports, closing brackets, indentation and comments. Arithmetic, not a measurement of a person.
I have rehearsed the kit part of this build. The new work is the store.
| choice | status |
|---|---|
| Check every night, then write every night, under one lock | Approved |
| Sort rooms before locking | Approved |
| Decide expiry on read | Approved |
| Lock rooms in the order the request lists them | Not approved |
| Check a night, release the lock, then write | Not approved |
| A background job as the only way a hold expires | Not approved |
| One global mutex | Say the cost |
I say what I chose and what it costs, then I move on.
package build
import (
"context"
"errors"
"fmt"
"maps"
"slices"
"sync"
"time"
)
var (
ErrInvalid = errors.New("invalid")
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
)
const (
Held = "held"
Confirmed = "confirmed"
Cancelled = "cancelled"
)
// Hold claims every night in every room it lists. Nights are dates, YYYY-MM-DD.
type Hold struct {
ID string `json:"id"`
Rooms []string `json:"rooms"`
Nights []string `json:"nights"`
Status string `json:"status"`
Expires time.Time `json:"expires_at"`
}
// live says whether h still owns its nights. A free night is one whose hold is nil or not live, so
// expiry and cancel need no cleanup.
func (h *Hold) live(now time.Time) bool {1
if h == nil {
return false
}
return h.Status == Confirmed || h.Status == Held && now.Before(h.Expires)
}
// Room lists the nights of one room that are free.
type Room struct {
ID string `json:"id"`
Free []string `json:"free"`
}
type Store interface {
AddRoom(ctx context.Context, id string) error
Rooms(ctx context.Context, nights []string) ([]Room, error)
// Hold takes all nights in all rooms, or returns ErrConflict and takes none.
Hold(ctx context.Context, h Hold, ttl time.Duration) (Hold, error)
// Confirm is safe to retry. It returns ErrConflict if the hold has expired or was cancelled.
Confirm(ctx context.Context, id string) (Hold, error)
Cancel(ctx context.Context, id string) (Hold, error)
}
type room struct {
mu sync.Mutex
nights map[string]*Hold
}
type MemStore struct {
mu sync.RWMutex2 // guards the two maps; never held while a room lock is awaited
rooms map[string]*room
holds map[string]*Hold
}
func NewMemStore() *MemStore {
return &MemStore{rooms: map[string]*room{}, holds: map[string]*Hold{}}
}
func (s *MemStore) AddRoom(_ context.Context, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.rooms[id]; !ok {
s.rooms[id] = &room{nights: map[string]*Hold{}}
}
return nil
}
func (s *MemStore) Rooms(_ context.Context, nights []string) ([]Room, error) {
s.mu.RLock()
ids := slices.Sorted(maps.Keys(s.rooms))
rooms, err := s.find(ids)
s.mu.RUnlock()
if err != nil {
return nil, err
}
out := make([]Room, len(ids))
for i, r := range rooms {
out[i] = Room{ID: ids[i], Free: []string{}}
r.mu.Lock()
now := time.Now()
for _, night := range nights {
if !r.nights[night].live(now) {
out[i].Free = append(out[i].Free, night)
}
}
r.mu.Unlock()
}
return out, nil
}
// find returns the rooms sorted by id, in whatever order the caller listed them. The caller must
// hold s.mu.
func (s *MemStore) find(ids []string) ([]*room, error) {
rooms := make([]*room, len(ids))
for i, id := range slices.Sorted(slices.Values(ids)) {3
r, ok := s.rooms[id]
if !ok {
return nil, fmt.Errorf("%w: room %s", ErrNotFound, id)
}
rooms[i] = r
}
return rooms, nil
}
// lock takes the locks of the rooms in sorted order, so two stays can never wait for each other,
// and returns the function that releases them.
func (s *MemStore) lock(ids []string) (rooms []*room, unlock func(), err error) {
s.mu.RLock()
rooms, err = s.find(ids)
s.mu.RUnlock()
if err != nil {
return nil, nil, err
}
for _, r := range rooms {
r.mu.Lock()
}
return rooms, func() {
for _, r := range rooms {
r.mu.Unlock()
}
}, nil
}
func (s *MemStore) Hold(_ context.Context, h Hold, ttl time.Duration) (Hold, error) {
rooms, unlock, err := s.lock(h.Rooms)
if err != nil {
return Hold{}, err
}
defer unlock()
now := time.Now()
for _, r := range rooms {
for _, night := range h.Nights {
if r.nights[night].live(now) {5
return Hold{}, fmt.Errorf("%w: %s is taken", ErrConflict, night)
}
}
}
h.Status, h.Expires = Held, now.Add(ttl)
for _, r := range rooms {
for _, night := range h.Nights {
r.nights[night] = &h
}
}
s.mu.Lock()
defer s.mu.Unlock()
s.holds[h.ID] = &h
return h, nil
}
// change runs fn on hold id with its rooms locked. The clock is read after the locks, so a request
// that waited cannot act on a time from before another request's decision.
func (s *MemStore) change(id string, fn func(h *Hold, now time.Time) error) (Hold, error) {
s.mu.RLock()
h, ok := s.holds[id]
s.mu.RUnlock()
if !ok {
return Hold{}, ErrNotFound
}
_, unlock, err := s.lock(h.Rooms)
if err != nil {
return Hold{}, err
}
defer unlock()
if err := fn(h, time.Now()); err != nil {6
return Hold{}, err
}
return *h, nil
}
func (s *MemStore) Confirm(_ context.Context, id string) (Hold, error) {
return s.change(id, func(h *Hold, now time.Time) error {
if !h.live(now) {
return fmt.Errorf("%w: hold expired or cancelled", ErrConflict)
}
h.Status = Confirmed
return nil
})
}
func (s *MemStore) Cancel(_ context.Context, id string) (Hold, error) {
return s.change(id, func(h *Hold, _ time.Time) error {
h.Status = Cancelled7
return nil
})
}
- 1The one rule. A nil hold, a cancelled hold and an expired hold all mean free, so no job has to run.
- 2This lock covers only the two maps, and it is released before a room lock is awaited. One busy room cannot stop the others.
- 3The fixed order. Every request takes room locks in sorted order, whatever order it listed them in.
- 4The clock is read after the locks. A time from before the wait could make a dead hold look alive.
- 5All checks run before any write, so a refused stay takes nothing.
- 6Confirm also reads the clock after its locks. It shares them with Hold, so the two run in an order.
- 7Cancel changes one field. The night cells keep their pointer, and the next hold overwrites it.
Hold checks every night before it writes one, with all its rooms locked. Confirm and cancel change the hold, not the nights.
package build
import (
"context"
"crypto/rand"
"fmt"
"slices"
"time"
)
const (
maxNights = 90
maxTTLMs = 3600000
)
type Service struct {
store Store
}
func NewService(store Store) *Service {
return &Service{store: store}
}
// nights lists each night from `from` up to, not including, `to`: the guest leaves on `to`.
func nights(from, to string) ([]string, error) {
start, err1 := time.Parse(time.DateOnly, from)
end, err2 := time.Parse(time.DateOnly, to)
if err1 != nil || err2 != nil {
return nil, fmt.Errorf("%w: want dates as YYYY-MM-DD", ErrInvalid)
}
n := int(end.Sub(start).Hours() / 24)1
if n < 1 || n > maxNights {
return nil, fmt.Errorf("%w: want 1 to %d nights", ErrInvalid, maxNights)
}
out := make([]string, n)
for i := range out {
out[i] = start.AddDate(0, 0, i).Format(time.DateOnly)2
}
return out, nil
}
func (s *Service) AddRoom(ctx context.Context, id string) error {
return s.store.AddRoom(ctx, id)
}
func (s *Service) Rooms(ctx context.Context, from, to string) ([]Room, error) {
list, err := nights(from, to)
if err != nil {
return nil, err
}
return s.store.Rooms(ctx, list)
}
func (s *Service) Hold(ctx context.Context, rooms []string, from, to string, ttlMs int64) (Hold, error) {
list, err := nights(from, to)
if err != nil {
return Hold{}, err
}
sorted := slices.Sorted(slices.Values(rooms))
if len(rooms) == 0 || len(slices.Compact(sorted)) != len(rooms)3 {
return Hold{}, fmt.Errorf("%w: want one or more different rooms", ErrInvalid)
}
if ttlMs < 1 || ttlMs > maxTTLMs4 {
return Hold{}, fmt.Errorf("%w: ttl_ms must be 1 to %d", ErrInvalid, maxTTLMs)
}
ttl := time.Duration(ttlMs) * time.Millisecond
return s.store.Hold(ctx, Hold{ID: rand.Text(), Rooms: rooms, Nights: list}, ttl)
}
func (s *Service) Confirm(ctx context.Context, id string) (Hold, error) {
return s.store.Confirm(ctx, id)
}
func (s *Service) Cancel(ctx context.Context, id string) (Hold, error) {
return s.store.Cancel(ctx, id)
}
- 1Both dates parse as UTC midnight, so every day has 24 hours and daylight saving cannot change the count.
- 2AddDate handles month ends and leap days.
- 3A room listed twice would lock itself and wait forever, so it is refused here.
- 4Check before the multiplication. A huge ttl_ms would overflow a Duration and look valid.
The service turns dates into a list of nights and checks the input. The store sees only clean values.
package build
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
)
func Handler(svc *Service) http.Handler {
step := func(fn func(context.Context, string) (Hold, error)) http.Handler {1
return route(200, func(r *http.Request) (any, error) {
return fn(r.Context(), r.PathValue("id"))
})
}
mux := http.NewServeMux()
mux.Handle("PUT /rooms/{id}", route(200, func(r *http.Request) (any, error) {
id := r.PathValue("id")
return map[string]string{"id": id}, svc.AddRoom(r.Context(), id)
}))
mux.Handle("GET /rooms", route(200, func(r *http.Request) (any, error) {
q := r.URL.Query()
rooms, err := svc.Rooms(r.Context(), q.Get("from"), q.Get("to"))
return map[string][]Room{"rooms": rooms}, err
}))
mux.Handle("POST /holds", route(201, func(r *http.Request) (any, error) {
var body struct {
Rooms []string
From, To string
TTLMs int64 `json:"ttl_ms"`2
}
if err := readJSON(r, &body); err != nil {
return nil, err
}
return svc.Hold(r.Context(), body.Rooms, body.From, body.To, body.TTLMs)
}))
mux.Handle("POST /holds/{id}/confirm", step(svc.Confirm))
mux.Handle("POST /holds/{id}/cancel", step(svc.Cancel))
return mux
}
func route(status int, fn func(*http.Request) (any, error)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
code := status
v, err := fn(r)
if err != nil {
code, v = failure(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Print(err)
}
})
}
func readJSON(r *http.Request, v any) error {
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
return fmt.Errorf("%w: %v", ErrInvalid, err)
}
return nil
}
func failure(err error) (int, any) {
status := 500
switch {
case errors.Is(err, ErrInvalid):
status = 400
case errors.Is(err, ErrNotFound):
status = 404
case errors.Is(err, ErrConflict):
status = 409
default:
log.Print(err)
err = errors.New("internal error")
}
return status, map[string]string{"error": err.Error()}
}
- 1Method values fit this signature, so each route is one line.
- 2Other fields match by name, because the JSON decoder ignores case. This one needs a tag.
// Command main serves the 45-minute room booking service.
package main
import (
"log"
"net/http"
"github.com/rudrite/system-design/arena/exercises/booking/build"
)
func main() {
svc := build.NewService(build.NewMemStore())
handler := build.Handler(svc)
log.Fatal(http.ListenAndServe(":8080", handler))
}
Confirm and cancel share one route helper, because they have one signature.
package build
import (
"fmt"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
type step struct {
method, path, body string
status int
want string
}
func do(h http.Handler, method, path, body string) (int, string) {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
return w.Code, w.Body.String()
}
func run(t *testing.T, h http.Handler, hold string, steps []step) {
t.Helper()
for i, s := range steps {
status, body := do(h, s.method, strings.ReplaceAll(s.path, "HOLD", hold), s.body)
if status != s.status || !strings.Contains(body, s.want) {
t.Errorf("step %d, %s %s: got %d %s", i, s.method, s.path, status, body)
}
}
}
func stay(from, to, ttl int) string {
return fmt.Sprintf(`{"rooms":["a"],"from":"2027-01-0%d","to":"2027-01-0%d","ttl_ms":%d}`, from, to, ttl)
}
func hold(t *testing.T, h http.Handler, body string) string {
t.Helper()
status, got := do(h, "POST", "/holds", body)
if status != 201 {
t.Fatalf("hold: %d %s", status, got)
}
return regexp.MustCompile(`[A-Z0-9]{26}`).FindString(got)
}
func newHandler() http.Handler {
h := Handler(NewService(NewMemStore()))
do(h, "PUT", "/rooms/a", "")
return h
}
func TestRooms(t *testing.T) {
run(t, newHandler(), "", []step{
{"GET", "/rooms?from=2027-01-01&to=2027-01-03", "", 200, `"free":["2027-01-01","2027-01-02"]`},
{"POST", "/holds", stay(1, 2, 60000), 201, `"held"`},
{"GET", "/rooms?from=2027-01-01&to=2027-01-03", "", 200, `"free":["2027-01-02"]`},
})
}
func TestHoldConfirmCancel(t *testing.T) {
h := newHandler()
id := hold(t, h, stay(1, 4, 60000))
run(t, h, id, []step{
{"POST", "/holds", stay(3, 5, 60000), 409, "taken"},
{"GET", "/rooms?from=2027-01-04&to=2027-01-05", "", 200, `"free":["2027-01-04"]`},1
{"POST", "/holds/HOLD/confirm", "", 200, "confirmed"},
{"POST", "/holds/HOLD/confirm", "", 200, "confirmed"},
{"POST", "/holds/HOLD/cancel", "", 200, "cancelled"},
{"POST", "/holds/HOLD/confirm", "", 409, "conflict"},
{"POST", "/holds", stay(3, 5, 60000), 201, ""},
})
}
func TestExpiry(t *testing.T) {
h := newHandler()
id := hold(t, h, stay(1, 2, 1))
time.Sleep(5 * time.Millisecond)2
run(t, h, id, []step{
{"POST", "/holds/HOLD/confirm", "", 409, "expired"},
{"GET", "/rooms?from=2027-01-01&to=2027-01-02", "", 200, `"free":["2027-01-01"]`},
{"POST", "/holds", stay(1, 2, 60000), 201, ""},
})
}
func TestParallelHolds(t *testing.T) {
h := newHandler()
var won atomic.Int64
var wg sync.WaitGroup
for range 100 {
wg.Go(func() {
if status, _ := do(h, "POST", "/holds", stay(1, 4, 60000)); status == 201 {
won.Add(1)
}
})
}
wg.Wait()
if won.Load() != 1 {3
t.Fatalf("%d holds won, want 1", won.Load())
}
}
- 1The refused stay left January 4 free: all nights or none.
- 2The hold lasts 1 ms. The grader checks expiry too, with a longer TTL.
- 3Run with -race. Exactly one of 100 holds wins.
Each test is a list of steps, so a new behaviour is one row. The race test counts winners.
arena run booking --base http://localhost:8080
correctness
PASS a new room is free on every night
PASS a hold takes its nights and no others
PASS the last date is the day of leaving
PASS a hold can span rooms
PASS confirm keeps the nights past the expiry
PASS cancel frees the nights
PASS cancel of a confirmed booking frees the nights
PASS an expired hold frees its nights
PASS adding a room twice keeps its holds
PASS an old hold's cancel leaves the new owner alone
status codes
PASS hold is 201 and returns an id
PASS confirm is safe to retry
PASS cancel is safe to retry
PASS a taken night is 409
PASS one taken night fails the whole stay
PASS one taken room fails the whole stay
PASS an unknown room is 404 and takes nothing
PASS an unknown hold is 404
PASS confirm after the expiry is 409
PASS confirm after cancel is 409
validation
PASS malformed JSON is 400
PASS a date of the wrong shape is 400
PASS a date not on the calendar is 400
PASS a stay of no nights is 400
PASS a stay over 90 nights is 400
PASS a list with no dates is 400
PASS a hold with no rooms is 400
PASS a room listed twice is 400
PASS a ttl outside 1 ms to one hour is 400
concurrency
PASS 100 parallel holds on one stay: exactly one wins
PASS 100 parallel holds on overlapping nights: no night is sold twice
PASS 100 parallel holds on two rooms in opposite orders finish
PASS 100 parallel holds around a ring of rooms: all rooms or none
PASS 100 parallel confirms of one hold all succeed
PASS 100 parallel holds and cancels leave the room free
PASS 100 confirms race the expiry: confirm and a new hold never both win
36 checks: 36 passed, 0 failedAll checks pass, with 100 parallel holds on overlapping nights.
{Name: "100 parallel holds on overlapping nights: no night is sold twice", Group: grader.Concurrency, Run: func(t *grader.T) {
r := room(t, "r")
var mu sync.Mutex
sold := map[int]int{}
t.Parallel(parallel, func(i int) {
from := i % 12
x := place(t, []string{r}, from, from+3, long)
t.Status(x, 201, 409)
if x.Status != 201 {
return
}
step(t, t.Field(x, "id"), "confirm", "confirmed")
mu.Lock()
defer mu.Unlock()
for n := from; n < from+3; n++ {
sold[n]++
}
})
wantSold(t, r, 15, sold)
}},{Name: "an expired hold frees its nights", Group: grader.Correctness, Run: func(t *grader.T) {
r := room(t, "r")
hold(t, []string{r}, 0, 2, short)
wantFree(t, r, 0, 2)
time.Sleep(2 * short * time.Millisecond)
wantFree(t, r, 0, 2, 0, 1)
hold(t, []string{r}, 0, 2, long)
}},Winners confirm their nights, then the grader compares what it sold with what the server lists. A loser that left nights behind fails too.
| the interviewer asks | the answer | goes deeper |
|---|---|---|
| Run two instances. What breaks? | Each room mutex covers one process, and each map holds different data, so both instances can sell one night. The lock moves to a row per room per night in Postgres, which every instance shares. | T4 Locks in the database |
| Why lock the rows and also use a conditional update? | The lock gives the order, so two stays cannot deadlock. The update makes the decision, and its row count says how many nights were taken. One night short rolls back the whole stay. | T8 Booking |
| A night nobody has held has no row. What do you lock? | Insert the missing rows first with ON CONFLICT DO NOTHING, in lock order. Then every night has a row to lock. A nightly job that seeds the calendar also works. | T8 Booking |
| A second guest waits on a lock past the first guest's expiry. Which clock do you read? | The clock after the wait. In Postgres, now() is the start of the transaction, so a confirm that queued past the expiry would still win. These queries use clock_timestamp(), and a test proves the difference. | T4 Locks in the database |
| Who cleans up expired holds? | Nothing has to. A night is free when its hold is not live, so every read checks the expiry. A sweeper would only delete old rows, and a late or failed sweep sells nothing twice. | T8 Booking |
| The hold response is lost. The client retries. Then what? | Without a key, the retry gets 409 from its own hold. Production takes an Idempotency-Key header and claims it in the same transaction as the nights, so a retry returns the first hold. A refusal rolls the claim back. The same key with a different stay gets 422. | T8 Booking |
| Can Redis hold the nights instead? | It can, as a fast first gate while the guest pays: one atomic script takes all nights with a TTL. Postgres still decides at confirm. A Redis lock alone can expire during a pause, and only a fencing token at the database stops the late writer. | T6 Distributed locks |
| Why not one lock per night, or one global lock? | One global lock is simple, but unrelated rooms then wait for each other. One lock per night in memory costs a map of mutexes and more ordering rules. One lock per room is the middle: each hold is short, and rooms stay independent. | T4 Locks in the database |
| One hotel gets a flash sale. What happens? | Guests queue on the same rows, and connections sit waiting. Filter early: a cache of sold-out nights stops most refused requests before they reach a lock. Keep each transaction short so the queue drains quickly. | T8 Booking |
| The table outgrows one primary. How do you shard? | Shard by hotel. A stay touches one hotel, so a transaction stays on one shard, and row locks still work. A key like room id would split a multi-room stay across shards and need a distributed commit. | X2 Sharding |
| What goes on the dashboard? | Rate, errors and duration per route. The 409 rate on holds shows demand for full nights, and the rate of confirm 409s shows guests who ran out of time. Lock wait shows contention before users report it. | O3 Observability |
| Who may confirm a hold? | Only its owner. The bearer token gives an owner, and each hold query filters on it. A different owner gets 404 and not 403, so an ID reveals nothing. | O5 Security |
I start from what the build lacks: durability, two instances, then retries. I name each limit before the interviewer does.
Instances hold no state. The night row replaces the room mutex, so any instance can serve any request.
| tool | build | production |
|---|---|---|
| Postgres | A mutex per room | A row per room per night, locked in one order |
| Postgres | Check, then write | One conditional update and its row count |
| Postgres | time.Now after the locks | clock_timestamp in the query |
| Postgres | A retry gets 409 | Idempotency-Key, claimed with the nights; a reused key gets 422 |
| Service | No auth | Bearer tokens; each hold has an owner |
| Service | ListenAndServe | Timeouts, a body limit, metrics, drain on SIGTERM |
Tested: production passes the same 36 grader checks. The real binary passes them over a socket, then exits cleanly on SIGTERM.
One interface, one new implementation, and a wrapper around the same handler. The service file does not change.
store.go's interface, service.go and handler.go of the build are imported as they are. Auth and metrics come from the production version of E1. handler.go answers 409 for every conflict, so a small wrapper turns the 409 for a reused key into 422.
+ // Command main serves the production booking service. It reads DATABASE_URL, API_TOKENS
+ // (owner:token,owner:token) and ADDR, which defaults to :8080.
- // Command main serves the 45-minute room booking service.
package main
import (
+ "cmp"
+ "context"
+ "errors"
"log"
"net/http"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/rudrite/system-design/arena/exercises/booking/prod"
+ kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
- "github.com/rudrite/system-design/arena/exercises/booking/build"
)
func main() {
+ if err := run(); err != nil {
+ log.Fatal(err)
+ }
+ }
+
+ func run() error {
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+
+ pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
+ if err != nil {
+ return err
+ }
+ defer pool.Close()
+ if err := prod.Migrate(ctx, pool); err != nil {
+ return err
+ }
+ tokens, err := kv.ParseTokens(os.Getenv("API_TOKENS"))
+ if err != nil {
+ return err
+ }
+
+ srv := &http.Server{
+ Addr: cmp.Or(os.Getenv("ADDR"), ":8080"),
+ Handler: prod.Handler(pool, tokens, kv.NewMetrics()),
+ ReadHeaderTimeout: 5 * time.Second,
+ ReadTimeout: 10 * time.Second,
+ WriteTimeout: 10 * time.Second,
+ IdleTimeout: 60 * time.Second,
+ }
+ failed := make(chan error, 1)
+ go func() { failed <- srv.ListenAndServe() }()
+
+ select {
+ case err := <-failed:
+ return err
+ case <-ctx.Done():
+ }
+ // SIGTERM: stop accepting, finish what is running, then exit.
+ drain, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ if err := srv.Shutdown(drain); err != nil {
+ return err
+ }
+ if err := <-failed; !errors.Is(err, http.ErrServerClosed) {
+ return err
+ }
+ return nil
- svc := build.NewService(build.NewMemStore())
- handler := build.Handler(svc)
- log.Fatal(http.ListenAndServe(":8080", handler))
}CREATE TABLE IF NOT EXISTS rooms (
id text PRIMARY KEY
);
-- One row per hold. The unique key makes a retried request safe.
CREATE TABLE IF NOT EXISTS holds (
id text PRIMARY KEY,
owner text NOT NULL,
rooms text[] NOT NULL,
nights text[] NOT NULL,
status text NOT NULL CHECK (status IN ('held', 'confirmed', 'cancelled')),
expires_at timestamptz NOT NULL,
idempotency_key text,
fingerprint bytea,
UNIQUE (owner, idempotency_key)
);
-- One row per room per night. This row is the lock.
CREATE TABLE IF NOT EXISTS room_nights (
room_id text NOT NULL REFERENCES rooms (id),
night date NOT NULL,
hold_id text REFERENCES holds (id),
held_until timestamptz, -- NULL with a hold_id means confirmed
PRIMARY KEY (room_id, night)
);
CREATE INDEX IF NOT EXISTS room_nights_hold ON room_nights (hold_id);pgstore: implements Storenew file, +235
+ // Package prod is the booking service made production grade. It imports the 45-minute build and
+ // replaces the in-memory store behind its interface, then adds idempotency keys, auth, metrics and
+ // health. The service and the handler do not change.
+ package prod
+
+ import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/rudrite/system-design/arena/exercises/booking/build"
+ kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
+ "github.com/rudrite/system-design/arena/internal/idempotent"
+ )
+
+ // PGStore implements build.Store on Postgres.
+ type PGStore struct {
+ pool *pgxpool.Pool
+ }
+
+ // NewPGStore returns a store on pool.
+ func NewPGStore(pool *pgxpool.Pool) *PGStore {
+ return &PGStore{pool: pool}
+ }
+
+ // AddRoom creates the room. A second call changes nothing.
+ func (s *PGStore) AddRoom(ctx context.Context, id string) error {
+ if _, err := s.pool.Exec(ctx, `INSERT INTO rooms (id) VALUES ($1) ON CONFLICT DO NOTHING`, id); err != nil {
+ return fmt.Errorf("add room %s: %w", id, err)
+ }
+ return nil
+ }
+
+ // A night with no row is free, so the list starts from the nights asked for, not from the rows.
+ const freeNights = `
+ SELECT r.id, coalesce(array_agg(wanted ORDER BY wanted) FILTER (
+ WHERE n.hold_id IS NULL OR n.held_until <= clock_timestamp()), '{}')
+ FROM rooms r
+ CROSS JOIN unnest($1::text[]) AS wanted
+ LEFT JOIN room_nights n ON n.room_id = r.id AND n.night = wanted::date
+ GROUP BY r.id
+ ORDER BY r.id`
+
+ // Rooms takes no lock, so a list never waits for a hold.
+ func (s *PGStore) Rooms(ctx context.Context, nights []string) ([]build.Room, error) {
+ rows, err := s.pool.Query(ctx, freeNights, nights)
+ if err != nil {
+ return nil, fmt.Errorf("list rooms: %w", err)
+ }
+ rooms, err := pgx.CollectRows(rows, pgx.RowToStructByPos[build.Room])
+ if err != nil {
+ return nil, fmt.Errorf("list rooms: %w", err)
+ }
+ return rooms, nil
+ }
+
+ const (
+ claim = `
+ INSERT INTO holds (id, owner, rooms, nights, status, expires_at, idempotency_key, fingerprint)
+ VALUES ($1, $2, $3, $4, 'held', clock_timestamp(), NULLIF($5, ''), $6)
+ ON CONFLICT (owner, idempotency_key) DO NOTHING`
+
+ // A night that nobody has held has no row to lock, so make the rows first, in lock order.
+ addNights = `
+ INSERT INTO room_nights (room_id, night)
+ SELECT room, night::date FROM unnest($1::text[]) AS room, unnest($2::text[]) AS night
+ ORDER BY 1, 2
+ ON CONFLICT DO NOTHING`
+
+ // One order for every request, so two stays can never wait for each other.
+ lockNights = `
+ SELECT 1 FROM room_nights
+ WHERE room_id = ANY($1) AND night = ANY($2::text[]::date[])
+ ORDER BY room_id, night
+ FOR UPDATE`
+
+ // clock_timestamp, not now: now is the start of the transaction, before the wait for the locks.
+ setExpiry = `
+ UPDATE holds SET expires_at = clock_timestamp() + $2::interval WHERE id = $1 RETURNING expires_at`
+
+ takeNights = `
+ UPDATE room_nights SET hold_id = $3, held_until = $4
+ WHERE room_id = ANY($1) AND night = ANY($2::text[]::date[])
+ AND (hold_id IS NULL OR held_until <= clock_timestamp())`
+
+ confirmNights = `
+ UPDATE room_nights SET held_until = NULL
+ WHERE hold_id = $1 AND held_until > clock_timestamp()`
+
+ freeHold = `
+ UPDATE room_nights SET hold_id = NULL, held_until = NULL WHERE hold_id = $1`
+ )
+
+ func lock(ctx context.Context, tx pgx.Tx, h build.Hold) error {
+ if _, err := tx.Exec(ctx, lockNights, h.Rooms, h.Nights); err != nil {
+ return fmt.Errorf("lock nights: %w", err)
+ }
+ return nil
+ }
+
+ // Hold takes all the nights in one transaction. The count of rows changed is the check: one night
+ // short rolls everything back, the claim on the idempotency key included.
+ func (s *PGStore) Hold(ctx context.Context, h build.Hold, ttl time.Duration) (build.Hold, error) {
+ req, _ := ctx.Value(requestKey{}).(request)
+ err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
+ tag, err := tx.Exec(ctx, claim, h.ID, kv.OwnerFrom(ctx), h.Rooms, h.Nights, req.key, req.fingerprint)
+ if err != nil {
+ return fmt.Errorf("claim hold: %w", err)
+ }
+ if tag.RowsAffected() == 0 {
+ h, err = replay(ctx, tx, req)
+ return err
+ }
+ var known int
+ if err := tx.QueryRow(ctx, `SELECT count(*) FROM rooms WHERE id = ANY($1)`, h.Rooms).Scan(&known); err != nil {
+ return fmt.Errorf("find rooms: %w", err)
+ }
+ if known != len(h.Rooms) {
+ return fmt.Errorf("%w: a room does not exist", build.ErrNotFound)
+ }
+ if _, err := tx.Exec(ctx, addNights, h.Rooms, h.Nights); err != nil {
+ return fmt.Errorf("add nights: %w", err)
+ }
+ if err := lock(ctx, tx, h); err != nil {
+ return err
+ }
+ if err := tx.QueryRow(ctx, setExpiry, h.ID, ttl).Scan(&h.Expires); err != nil {
+ return fmt.Errorf("set expiry: %w", err)
+ }
+ tag, err = tx.Exec(ctx, takeNights, h.Rooms, h.Nights, h.ID, h.Expires)
+ if err != nil {
+ return fmt.Errorf("take nights: %w", err)
+ }
+ if tag.RowsAffected() != int64(len(h.Rooms)*len(h.Nights)) {
+ return fmt.Errorf("%w: a night is taken", build.ErrConflict)
+ }
+ h.Status = build.Held
+ return nil
+ })
+ if err != nil {
+ return build.Hold{}, err
+ }
+ return h, nil
+ }
+
+ // replay returns the hold an earlier request made with this key. The same key on a different
+ // request is a client bug, and it must not return the wrong answer.
+ func replay(ctx context.Context, tx pgx.Tx, req request) (build.Hold, error) {
+ var h build.Hold
+ var fingerprint []byte
+ err := tx.QueryRow(ctx,
+ `SELECT id, rooms, nights, status, expires_at, fingerprint FROM holds WHERE owner = $1 AND idempotency_key = $2`,
+ req.owner, req.key).Scan(&h.ID, &h.Rooms, &h.Nights, &h.Status, &h.Expires, &fingerprint)
+ if err != nil {
+ return build.Hold{}, fmt.Errorf("read hold: %w", err)
+ }
+ if !bytes.Equal(fingerprint, req.fingerprint) {
+ idempotent.MarkReused(ctx)
+ return build.Hold{}, fmt.Errorf("%w: key used for a different request", build.ErrConflict)
+ }
+ return h, nil
+ }
+
+ // change runs fn on the caller's hold with its nights locked. A hold of another owner reads as
+ // missing. Rooms and nights never change, so they are safe to read before the locks. Status must
+ // be read after them, because a parallel request may have changed it while this one waited.
+ func (s *PGStore) change(ctx context.Context, id string, fn func(tx pgx.Tx, h *build.Hold) error) (build.Hold, error) {
+ var h build.Hold
+ err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
+ err := tx.QueryRow(ctx, `SELECT id, rooms, nights FROM holds WHERE id = $1 AND owner = $2`,
+ id, kv.OwnerFrom(ctx)).Scan(&h.ID, &h.Rooms, &h.Nights)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return build.ErrNotFound
+ }
+ if err != nil {
+ return fmt.Errorf("find hold: %w", err)
+ }
+ if err := lock(ctx, tx, h); err != nil {
+ return err
+ }
+ if err := tx.QueryRow(ctx, `SELECT status, expires_at FROM holds WHERE id = $1`, id).Scan(&h.Status, &h.Expires); err != nil {
+ return fmt.Errorf("read hold: %w", err)
+ }
+ return fn(tx, &h)
+ })
+ if err != nil {
+ return build.Hold{}, err
+ }
+ return h, nil
+ }
+
+ func setStatus(ctx context.Context, tx pgx.Tx, h *build.Hold, status string) error {
+ if _, err := tx.Exec(ctx, `UPDATE holds SET status = $2 WHERE id = $1`, h.ID, status); err != nil {
+ return fmt.Errorf("set status: %w", err)
+ }
+ h.Status = status
+ return nil
+ }
+
+ // Confirm is one conditional update on the night rows. If the hold has expired, or a new hold owns
+ // a night, fewer rows change than the stay has, and the transaction rolls back.
+ func (s *PGStore) Confirm(ctx context.Context, id string) (build.Hold, error) {
+ return s.change(ctx, id, func(tx pgx.Tx, h *build.Hold) error {
+ if h.Status == build.Confirmed {
+ return nil
+ }
+ conflict := fmt.Errorf("%w: the hold has expired or was cancelled", build.ErrConflict)
+ if h.Status != build.Held {
+ return conflict
+ }
+ tag, err := tx.Exec(ctx, confirmNights, h.ID)
+ if err != nil {
+ return fmt.Errorf("confirm nights: %w", err)
+ }
+ if tag.RowsAffected() != int64(len(h.Rooms)*len(h.Nights)) {
+ return conflict
+ }
+ return setStatus(ctx, tx, h, build.Confirmed)
+ })
+ }
+
+ // Cancel frees only the rows this hold still owns, so an old hold cannot free a new owner's nights.
+ func (s *PGStore) Cancel(ctx context.Context, id string) (build.Hold, error) {
+ return s.change(ctx, id, func(tx pgx.Tx, h *build.Hold) error {
+ if _, err := tx.Exec(ctx, freeHold, h.ID); err != nil {
+ return fmt.Errorf("free nights: %w", err)
+ }
+ return setStatus(ctx, tx, h, build.Cancelled)
+ })
+ }server: keys and authnew file, +80
+ package prod
+
+ import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ _ "embed"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/rudrite/system-design/arena/exercises/booking/build"
+ kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
+ "github.com/rudrite/system-design/arena/internal/idempotent"
+ )
+
+ //go:embed schema.sql
+ var schema string
+
+ // Migrate applies the schema. It is safe to run twice.
+ func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
+ if _, err := pool.Exec(ctx, schema); err != nil {
+ return fmt.Errorf("apply schema: %w", err)
+ }
+ return nil
+ }
+
+ // maxBody limits a request body. A larger one fails to decode and answers 400.
+ const maxBody = 1 << 20
+
+ type requestKey struct{}
+
+ // request identifies one idempotent call: who sent it, their key, and a hash of what they sent.
+ type request struct {
+ owner, key string
+ fingerprint []byte
+ }
+
+ // Idempotent hands the Idempotency-Key header to the store, with a hash of the route and body.
+ func Idempotent(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ key := r.Header.Get("Idempotency-Key")
+ if key == "" {
+ next.ServeHTTP(w, r)
+ return
+ }
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, `{"error":"invalid: cannot read body"}`, http.StatusBadRequest)
+ return
+ }
+ r.Body = io.NopCloser(bytes.NewReader(body))
+ sum := sha256.Sum256(append([]byte(r.URL.Path+"\n"), body...))
+ ctx := context.WithValue(r.Context(), requestKey{}, request{kv.OwnerFrom(r.Context()), key, sum[:]})
+ next.ServeHTTP(w, r.WithContext(ctx))
+ })
+ }
+
+ // Handler serves the API behind auth, plus the two routes an operator needs. Auth and metrics come
+ // from the key-value exercise, unchanged.
+ func Handler(pool *pgxpool.Pool, tokens kv.Tokens, metrics *kv.Metrics) http.Handler {
+ api := build.Handler(build.NewService(NewPGStore(pool)))
+
+ mux := http.NewServeMux()
+ mux.Handle("/", metrics.Wrap(kv.Auth(tokens, http.MaxBytesHandler(Idempotent(idempotent.AnswerReused(api)), maxBody))))
+ mux.Handle("GET /metrics", metrics)
+ mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), time.Second)
+ defer cancel()
+ if err := pool.Ping(ctx); err != nil {
+ http.Error(w, "database unreachable", http.StatusServiceUnavailable)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+ })
+ return mux
+ }reuse: 422 for a reused keynew file, +38
+ package idempotent
+
+ import (
+ "context"
+ "net/http"
+ )
+
+ type reusedKey struct{}
+
+ // MarkReused records that this request reused a key with a different request. The store still
+ // returns its conflict error, so the build's handler writes the response as usual.
+ func MarkReused(ctx context.Context) {
+ if reused, ok := ctx.Value(reusedKey{}).(*bool); ok {
+ *reused = true
+ }
+ }
+
+ // AnswerReused turns the 409 of a marked request into 422. It is for a production version that
+ // imports the build's handler: that error map has one status for every conflict, and a store
+ // cannot reach it. Other responses pass through, so a marked request that fails stays a 500.
+ func AnswerReused(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ out := &reuseWriter{ResponseWriter: w}
+ next.ServeHTTP(out, r.WithContext(context.WithValue(r.Context(), reusedKey{}, &out.reused)))
+ })
+ }
+
+ type reuseWriter struct {
+ http.ResponseWriter
+ reused bool
+ }
+
+ func (w *reuseWriter) WriteHeader(status int) {
+ if w.reused && status == http.StatusConflict {
+ status = http.StatusUnprocessableEntity
+ }
+ w.ResponseWriter.WriteHeader(status)
+ }The diff is one changed file and a few new ones. That is what the store interface in the build was for.
0 of 9 known
A stay lists room b, then room a. Another lists room a, then room b. How does the build stop them from deadlocking?
Why does cancel not clear the night cells?
Confirm reads the clock before it takes the locks. What can go wrong?
A hold needs three nights and the second is taken. How many nights does it take?
A guest confirms a hold twice. What does the second call return?
A guest confirms a hold that has expired, and nobody has taken the nights. Does it succeed?
In production, why does a confirm lock the night rows? It only needs to change a status.
Why does the store release the map lock before it waits for a room?
In production, one key arrives with a different stay. What is the answer?
- build
- 476 lines with tests, 19:52 of typing at 100 words a minute.
- checks
- 36 grader checks, in 4 groups.
- race
- 100 parallel holds on overlapping nights; no night is sold twice.
- limits
- 90 nights a stay. A hold lasts up to one hour.
- body limit
- 1 MiB in production.
Design values from the tested code, not load measurements.