Driver delivery payments
A small ledger with a sharp edge: money must be exact, and a parallel pay must lose nothing. The data structure is a sorted list. The test is whether your totals still add up after 100 clients race.
- 1Rate in cents an hour times whole seconds is an integer. Keep that integer, and nothing rounds until a total is shown.
- 2Unpaid deliveries stay sorted by end time. Pay cuts the list, and each delivery is paid once.
- 3Running totals change under the same lock as the list, so a total costs one read.
- 4Every write is an op, and every request is a batch of ops. An undo log makes a batch all or nothing.
Build a service that pays delivery drivers, as an HTTP API, in memory. Add a driver with an hourly rate. Record a delivery: driver, start time, end time. Times are integers. Report the total cost of all deliveries. Pay all deliveries up to a given time. Report the amount still unpaid. Money must be exact. Many clients call the service at once.
| ask | answer assumed |
|---|---|
| What unit is a time? | Whole seconds. Start is 0 or more, and end is after start. |
| What unit is a rate? | Whole cents an hour, from 1 to 1,000,000. |
| Which deliveries does pay cover? | Those that end at or before the time. A delivery that spans it stays unpaid. |
| Two deliveries overlap? | Each is paid in full. The follow-up changes this. |
| A delivery arrives after pay? | It stays unpaid until the next pay. |
| Longest delivery? | 7 days. The limit keeps totals inside 64 bits. |
Before I type, I confirm the unit of time, what pay covers, and how overlapping deliveries are paid.
| request | success | errors |
|---|---|---|
| POST /drivers | 201 | 400, 409 |
| POST /rates | 201 | 400, 404, 409 |
| POST /deliveries | 201 | 400, 404 |
| POST /pay | 200 | 400 |
| POST /batch | 200 results | The failed op's status |
| GET /cost | 200 | |
| GET /unpaid | 200 |
- A driver has the body {"driver":"a","rate_cents":2000}. A rate adds "from".
- A delivery has "driver", "start" and "end". Pay has "up_to".
- A batch has "ops": each op has an "op" of add_driver, set_rate, record or pay.
- An answer has deliveries, units (exact, as a string) and amount (rounded, for display).
Every write answers one shape: how many deliveries it covered, and the money. All writes share one path through the service.
| by | build | proof | if you are late |
|---|---|---|---|
| 15 min | The kit, renamed. Add driver, record delivery, total cost. Units from the first line. | TestDeliveries | Use one rate per driver. Add the rate list last. |
| 30 min | The sorted unpaid list, pay and unpaid. Running totals under the lock. | TestPay | Scan an unsorted list, and say out loud what sorting saves. |
| 45 min | Rate changes. The batch route and the undo log. Race test. | TestRateChange, TestBatch, TestParallelRecordAndPay | Keep the lock and the race test. Say the undo log out loud: "each write records its own reverse." |
I keep a running service at each checkpoint. If I am late at 30 minutes, I skip the batch and describe the undo log.
I keep unpaid deliveries sorted by end time. Pay cuts the list at the time, and total minus paid gives unpaid with no scan.
| method | case | result | status |
|---|---|---|---|
| Float dollars | Ten deliveries of 0.10 | 0.9999999999999999 | Not approved |
| Whole cents per delivery | Three of a third of 1.00 | 0.99 | Not approved |
| Rational type | Both | Exact | Slower, no gain |
| Units of 1/3600 cent | Both | 1.00 | Approved |
- A float stores 0.10 as the nearest binary fraction, so each addition can add a small error.
- The denominator here is always 3600: cents an hour, divided by seconds in an hour.
- The amount rounds half up, once, on the total. Paid plus unpaid in units always equals the total.
I pick the unit first. Rate in cents an hour times seconds is an integer, so I keep that integer and round once, for display.
| part | value |
|---|---|
| Lines, with tests | 463 |
| Typed characters | 9,976 |
| Typing at 500 a minute | 19:57 |
| Typing at 300 a minute | 33:15 |
| Left for thinking, at 500 a minute | 25:03 |
| Dependencies | 0 |
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 and the pricing.
| choice | status |
|---|---|
| Integer units from the first line | Approved |
| Float money, or rounding each delivery | Not approved |
| One lock over the whole ledger | Say the cost |
| Running totals changed under that lock | Approved |
| Read the list, unlock, write it back | Not approved |
| One paid-up-to time instead of a list | Not approved |
| A recorded cost changes with the rate | Not approved |
I say what I chose and what it costs, then I move on.
package build
import (
"context"
"errors"
"slices"
"sort"
"sync"
)
var (
ErrInvalid = errors.New("invalid")
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
)
// Rate holds from its From time until the driver's next rate.
type Rate struct {
From int64
Cents int64
}
// Delivery is one job. Units is its cost, fixed when it is recorded.
type Delivery struct {
Driver string
Start, End int64
Units int64
}
// Totals are running sums, so a read costs the same at any size.
type Totals struct{ Total, Paid int64 }1
// Tx is what one atomic update may do.
type Tx interface {
// Rates returns a driver's rates, oldest first, or ErrNotFound.
Rates(id string) ([]Rate, error)
AddRate(id string, r Rate) error
AddDelivery(d Delivery) error
Pay(upTo int64) (count, units int64, err error)
}
type Store interface {
Totals(ctx context.Context) (Totals, error)
// Update runs fn alone. If fn fails, none of its writes remain.
Update(ctx context.Context, fn func(Tx) ([]Result, error)) ([]Result, error)2
}
type MemStore struct {
mu sync.RWMutex
rates map[string][]Rate
unpaid []Delivery // sorted by End
totals Totals
undo []func()
}
func NewMemStore() *MemStore {
return &MemStore{rates: map[string][]Rate{}}
}
func (s *MemStore) Totals(context.Context) (Totals, error) {
s.mu.RLock()
defer s.mu.RUnlock()
return s.totals, nil
}
func (s *MemStore) Update(_ context.Context, fn func(Tx) ([]Result, error)) ([]Result, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.undo = nil
out, err := fn(memTx{s})
if err != nil {
for _, undo := range slices.Backward(s.undo) {4
undo()
}
}
return out, err
}
// memTx is the store with its lock held. Each write records how to reverse itself.
type memTx struct{ *MemStore }
func (s memTx) Rates(id string) ([]Rate, error) {
rates := s.rates[id]
if len(rates) == 0 {
return nil, ErrNotFound
}
return rates, nil
}
func (s memTx) AddRate(id string, r Rate) error {
old := s.rates[id]
s.rates[id] = append(old, r)
s.undo = append(s.undo, func() { s.rates[id] = old })
return nil
}
// endsAfter finds the first unpaid delivery that ends after t.
func (s memTx) endsAfter(t int64) int {
return sort.Search(len(s.unpaid), func(i int) bool { return s.unpaid[i].End > t })5
}
func (s memTx) AddDelivery(d Delivery) error {
i := s.endsAfter(d.End)
s.unpaid = slices.Insert(s.unpaid, i, d)
s.totals.Total += d.Units
s.undo = append(s.undo, func() {
s.unpaid = slices.Delete(s.unpaid, i, i+1)
s.totals.Total -= d.Units
})
return nil
}
func (s memTx) Pay(upTo int64) (int64, int64, error) {
all, n := s.unpaid, s.endsAfter(upTo)
var units int64
for _, d := range all[:n] {
units += d.Units
}
// Clip makes the next insert copy, so it cannot shift the array that undo restores.
s.unpaid = slices.Clip(all[n:])6
s.totals.Paid += units
s.undo = append(s.undo, func() {
s.unpaid = all
s.totals.Paid -= units
})
return int64(n), units, nil
}
- 1Two sums. Unpaid is their difference, so there is no third number to keep correct.
- 2The Postgres store implements this same method with a database transaction. It sees the results, so it can save them for a retry.
- 3Deliveries arrive near time order, so an insert moves few entries. The worst case moves all of them: say so.
- 4Newest first. Each undo finds the state its write left, so saved indexes stay valid.
- 5Ends equal to the time count as covered, so pay takes the delivery that ends exactly then.
- 6Undo keeps the old slice. Clip forces the next insert to copy, so that slice cannot change under it. A random test found this.
Update is the only write path. It holds the lock for the whole function, and on failure it runs the undo log backwards.
package build
import (
"context"
"fmt"
"strconv"
)
// A rate is in cents an hour and time is in seconds, so rate × seconds is a whole number of units,
// and one unit is 1/3600 of a cent. Nothing divides, so nothing rounds until a total is shown.
const unitsPerCent = 36001
const (
maxRate = 1_000_000
maxLength = 7 * 24 * 3600
)
// Op is one write. POST /batch takes a list of them.
type Op struct {
Op string `json:"op"`
Driver string `json:"driver"`
Cents int64 `json:"rate_cents"`
From *int64 `json:"from"`
Start *int64 `json:"start"`
End *int64 `json:"end"`
UpTo *int64 `json:"up_to"`
}
// Result is an amount. Units is a string, because many JSON clients read a number as a float.
type Result struct {
Deliveries int64 `json:"deliveries"`
Units string `json:"units"`2
Amount string `json:"amount"`
}
func result(deliveries, units int64) Result {
cents := (units + unitsPerCent/2) / unitsPerCent3
amount := fmt.Sprintf("%d.%02d", cents/100, cents%100)
return Result{deliveries, strconv.FormatInt(units, 10), amount}
}
func invalid(message string) error {
return fmt.Errorf("%w: %s", ErrInvalid, message)
}
// cost prices each second at the rate in force at that second.
func cost(rates []Rate, start, end int64) int64 {
var units int64
for i, r := range rates {
to := end
if i+1 < len(rates) {
to = min(end, rates[i+1].From)4
}
if from := max(start, r.From); from < to {
units += r.Cents * (to - from)
}
}
return units
}
type Service struct{ store Store }
func NewService(store Store) *Service {
return &Service{store}
}
// Do runs ops in one atomic update. A plain request is a batch of one.
func (s *Service) Do(ctx context.Context, ops ...Op) ([]Result, error) {5
return s.store.Update(ctx, func(tx Tx) ([]Result, error) {
out := make([]Result, len(ops))
for i, op := range ops {
r, err := apply(tx, op)
if err != nil {
return nil, fmt.Errorf("op %d: %w", i, err)6
}
out[i] = r
}
return out, nil
})
}
func apply(tx Tx, op Op) (Result, error) {
if op.Op != "pay" && op.Driver == "" {
return Result{}, invalid("driver is required")
}
switch op.Op {
case "add_driver":
if op.Cents < 1 || op.Cents > maxRate {
return Result{}, invalid("rate out of range")
}
if _, err := tx.Rates(op.Driver); err == nil {
return Result{}, fmt.Errorf("%w: driver exists", ErrConflict)
}
return result(0, 0), tx.AddRate(op.Driver, Rate{0, op.Cents})
case "set_rate":
return setRate(tx, op)
case "record":
return record(tx, op)
case "pay":
if op.UpTo == nil || *op.UpTo < 0 {
return Result{}, invalid("up_to is required")
}
count, units, err := tx.Pay(*op.UpTo)
return result(count, units), err
}
return Result{}, invalid("unknown op")
}
func setRate(tx Tx, op Op) (Result, error) {
if op.From == nil || op.Cents < 1 || op.Cents > maxRate {
return Result{}, invalid("bad from or rate")
}
rates, err := tx.Rates(op.Driver)
if err != nil {
return Result{}, err
}
if *op.From <= rates[len(rates)-1].From {7
return Result{}, fmt.Errorf("%w: stale rate", ErrConflict)
}
return result(0, 0), tx.AddRate(op.Driver, Rate{*op.From, op.Cents})
}
func record(tx Tx, op Op) (Result, error) {
if op.Start == nil || op.End == nil || *op.Start < 0 || *op.End <= *op.Start || *op.End-*op.Start > maxLength {
return Result{}, invalid("want 0 <= start < end, up to 7 days")
}
rates, err := tx.Rates(op.Driver)
if err != nil {
return Result{}, err
}
units := cost(rates, *op.Start, *op.End)
return result(1, units), tx.AddDelivery(Delivery{op.Driver, *op.Start, *op.End, units})
}
func (s *Service) Cost(ctx context.Context) (Result, error) {
t, err := s.store.Totals(ctx)
return result(0, t.Total), err
}
func (s *Service) Unpaid(ctx context.Context) (Result, error) {
t, err := s.store.Totals(ctx)
return result(0, t.Total-t.Paid), err
}
- 1The only division in the file uses this constant, and it runs only for the displayed amount.
- 2A string keeps every digit past 2^53.
- 3Half up, and only for display. Units stay as they are.
- 4A delivery across a rate change is priced in parts, so each second gets the rate in force.
- 5Single routes and POST /batch both call this. The whole list runs under one lock.
- 6The wrapped error keeps its status, and the message names the op that failed.
- 7Rates only go forward. A recorded delivery keeps its cost, so a rate change never rewrites history.
A plain request is a batch of one, so there is one code path. Pricing happens once, when a delivery is recorded.
package build
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
)
func Handler(svc *Service) http.Handler {
write := func(status int, name string) http.Handler {
return route(status, func(r *http.Request) (any, error) {
var op Op
if err := readJSON(r, &op); err != nil {
return nil, err
}
op.Op = name1
out, err := svc.Do(r.Context(), op)
if err != nil {
return nil, err
}
return out[0], nil
})
}
mux := http.NewServeMux()
mux.Handle("POST /drivers", write(201, "add_driver"))
mux.Handle("POST /rates", write(201, "set_rate"))
mux.Handle("POST /deliveries", write(201, "record"))
mux.Handle("POST /pay", write(200, "pay"))
mux.Handle("POST /batch", route(200, func(r *http.Request) (any, error) {
var body struct{ Ops []Op }
if err := readJSON(r, &body); err != nil {
return nil, err
}
out, err := svc.Do(r.Context(), body.Ops...)2
return map[string][]Result{"results": out}, err
}))
mux.Handle("GET /cost", route(200, func(r *http.Request) (any, error) {
return svc.Cost(r.Context())
}))
mux.Handle("GET /unpaid", route(200, func(r *http.Request) (any, error) {
return svc.Unpaid(r.Context())
}))
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()}
}
- 1The route sets the op, so a body cannot change which op runs.
- 2A failure rolls back the whole list and answers with the status of the op that failed.
// Command main serves the 45-minute delivery ledger.
package main
import (
"log"
"net/http"
"github.com/rudrite/system-design/arena/exercises/delivery/build"
)
func main() {
handler := build.Handler(build.NewService(build.NewMemStore()))
log.Fatal(http.ListenAndServe(":8080", handler))
}
Four write routes share one helper, because they differ only in the name of the op.
package build
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
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, steps []step) {
t.Helper()
for i, s := range steps {
status, body := do(h, s.method, s.path, 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 newHandler() http.Handler {
return Handler(NewService(NewMemStore()))
}
func TestDeliveries(t *testing.T) {
run(t, newHandler(), []step{
{"POST", "/drivers", `{"driver":"a","rate_cents":1000}`, 201, ""},
{"POST", "/drivers", `{"driver":"a","rate_cents":1000}`, 409, ""},
{"POST", "/deliveries", `{"driver":"x","start":0,"end":60}`, 404, ""},
{"POST", "/deliveries", `{"driver":"a","start":0,"end":3600}`, 201, `"10.00"`},
{"POST", "/deliveries", `{"driver":"a","start":1800,"end":2400}`, 201, `"1.67"`},1
{"GET", "/cost", "", 200, `"units":"4200000"`},
})
}
func TestPay(t *testing.T) {
run(t, newHandler(), []step{
{"POST", "/drivers", `{"driver":"a","rate_cents":3600}`, 201, ""},
{"POST", "/deliveries", `{"driver":"a","start":0,"end":100}`, 201, ""},
{"POST", "/deliveries", `{"driver":"a","start":50,"end":200}`, 201, ""},
{"POST", "/pay", `{"up_to":100}`, 200, `"deliveries":1`},
{"GET", "/unpaid", "", 200, `"units":"540000"`},
{"POST", "/deliveries", `{"driver":"a","start":0,"end":10}`, 201, ""},2
{"POST", "/pay", `{"up_to":200}`, 200, `"deliveries":2`},
{"GET", "/unpaid", "", 200, `"units":"0"`},
})
}
func TestRateChange(t *testing.T) {
run(t, newHandler(), []step{
{"POST", "/drivers", `{"driver":"a","rate_cents":100}`, 201, ""},
{"POST", "/rates", `{"driver":"a","from":100,"rate_cents":200}`, 201, ""},
{"POST", "/deliveries", `{"driver":"a","start":50,"end":150}`, 201, `"units":"15000"`3},
})
}
func TestBatch(t *testing.T) {
add := `{"op":"add_driver","driver":"a","rate_cents":100}`
bad := `{"op":"record","driver":"none","start":0,"end":10}`
run(t, newHandler(), []step{
{"POST", "/batch", `{"ops":[` + add + `,` + bad + `]}`, 404, "op 1"},
{"POST", "/batch", `{"ops":[` + add + `]}`, 200, ""},4
})
}
func TestParallelRecordAndPay(t *testing.T) {
h := newHandler()
do(h, "POST", "/drivers", `{"driver":"a","rate_cents":100}`)
var wg sync.WaitGroup
for i := range 100 {
wg.Go(func() {5
do(h, "POST", "/deliveries", fmt.Sprintf(`{"driver":"a","start":%d,"end":%d}`, i, i+10))
do(h, "POST", "/pay", `{"up_to":1000}`)
})
}
wg.Wait()
run(t, h, []step{
{"GET", "/cost", "", 200, `"units":"100000"`},
{"GET", "/unpaid", "", 200, `"units":"0"`},
})
}
- 1This one overlaps the first delivery, and both are paid in full.
- 2A late delivery. It ends before the last pay time, and the next pay still takes it.
- 350 seconds at 100, then 50 at 200.
- 4The add in the failed batch left no trace. If it had, this would answer 409.
- 5Run with -race. The totals must end exact.
Each test is a list of steps, so a new behaviour is one row. The race test mixes records and pays.
arena run delivery --base http://localhost:8080
correctness
PASS one hour at 20.00 costs exactly 20.00
PASS one second at 10.00 keeps its fraction of a cent
PASS the amount rounds half up
PASS three thirds add up to exactly 1.00
PASS the total covers every driver
PASS overlapping deliveries are each paid in full
PASS pay covers deliveries that end at or before the time
PASS a delivery that spans the time stays unpaid
PASS paying twice pays once
PASS pay leaves the total cost alone
PASS a late delivery stays unpaid until the next pay
PASS a delivery across a rate change is priced in two parts
PASS a rate change leaves recorded deliveries alone
PASS a batch sees its own earlier ops
PASS a failed batch changes nothing
status codes
PASS add driver is 201
PASS a driver added twice is 409
PASS a delivery for an unknown driver is 404
PASS a rate for an unknown driver is 404
PASS a rate that is not the latest is 409
PASS pay with nothing to pay is 200
PASS a batch answers with the status of the op that failed
validation
PASS malformed JSON is 400
PASS a missing driver is 400
PASS a rate below 1 or above 1,000,000 cents is 400
PASS a rate of 1,000,000 cents is fine
PASS a time that is not an integer is 400
PASS a missing time is 400
PASS end at or before start is 400
PASS a negative time is 400
PASS a delivery over 7 days is 400
concurrency
PASS 100 parallel records: the total is exact
PASS 100 parallel records and pays: no money is lost or paid twice
PASS 100 parallel pays of one list: each delivery is paid once
PASS 100 parallel adds of one driver: exactly one wins
PASS 100 parallel batches, half failing: the failures leave no trace
36 checks: 36 passed, 0 failedAll checks pass, with 100 parallel requests in each race.
{Name: "100 parallel records and pays: no money is lost or paid twice", Group: grader.Concurrency, Run: func(t *grader.T) {
driver := addDriver(t, centAsecond)
settle(t)
before := amount(t, "/cost")
var paid atomic.Int64
t.Parallel(parallel, func(i int) {
if i%2 == 0 {
post(t, "/deliveries", delivery(driver, i, i+7), 201)
return
}
paid.Add(units(t, post(t, "/pay", upTo(far), 200)))1
})
recorded := parallel / 2 * 7 * centAsecond
wantAmount(t, "/cost", before+int64(recorded))
left := units(t, post(t, "/pay", upTo(far), 200))
if got := paid.Load() + left; got != int64(recorded) {2
t.Failf("%d units recorded, but %d paid in the race and %d after it", recorded, paid.Load(), left)
}
wantAmount(t, "/unpaid", 0)
}},- 1The grader adds up what each pay says it paid.
- 2More than recorded means paid twice. Less means lost.
A server whose pay reads the list, unlocks, and writes it back. The race detector stays quiet, because each step holds the lock.
FAIL a failed batch changes nothing
want 12119599 units, got 12299599
FAIL 100 parallel records and pays: no money is lost or paid twice
1260000 units recorded, but 1486800 paid in the race and 0 after it
FAIL 100 parallel pays of one list: each delivery is paid once
want 0 units, got -226800
FAIL 100 parallel batches, half failing: the failures leave no trace
want 80159599 units, got 81959599
36 checks: 32 passed, 4 failedThis one test states the invariant: everything recorded is paid exactly once, whichever request wins each race.
| follow-up | answer | where |
|---|---|---|
| Rates change over time | A list of rates per driver. Price each second at the rate in force. A recorded cost stays fixed. | In the build |
| Totals must be fast | Keep two running sums under the write lock. A read costs one lookup. | In the build |
| Transactions over these operations | POST /batch runs a list of ops under one lock. An undo log reverses a failure. | In the build |
| Pay overlapping time only once | Keep each driver's covered time as sorted spans. Price only the new parts. | Below |
// Package followups holds the answer to one rule change that the 45-minute build does not make:
// pay a driver once for time covered by overlapping deliveries.
package followups
// Span is a time range. It includes Start and excludes End.
type Span struct{ Start, End int64 }
// Cover keeps one driver's paid time as sorted spans that do not touch.
type Cover struct{ spans []Span }
// Add merges s and returns the parts of it that no earlier span covered. Price those parts with
// the driver's rates, and a second delivery in the same hour costs nothing extra.
func (c *Cover) Add(s Span) []Span {
var fresh, merged []Span
at, joined := s.Start, s
for _, old := range c.spans {
if old.End < s.Start || old.Start > s.End {1
merged = append(merged, old)
continue
}
if at < old.Start {
fresh = append(fresh, Span{at, old.Start})2
}
at = max(at, old.End)3
joined = Span{min(joined.Start, old.Start), max(joined.End, old.End)}
}
if at < s.End {
fresh = append(fresh, Span{at, s.End})
}
c.spans = insert(merged, joined)
return fresh
}
func insert(spans []Span, s Span) []Span {
i := 0
for i < len(spans) && spans[i].Start < s.Start {
i++
}
spans = append(spans, Span{})
copy(spans[i+1:], spans[i:])
spans[i] = s
return spans
}
- 1A span that does not touch the new one stays as it is. Spans that touch merge, so the list stays short.
- 2The gap before an old span is new time.
- 3Time up to the end of the old span is already paid, so skip it.
Three follow-ups are already in the build. For the fourth, the rule changes, so I price only the time not yet covered.
| the interviewer asks | the answer | goes deeper |
|---|---|---|
| A client times out on POST /deliveries and retries. What happens? | In the build, the driver is paid twice. Production takes an Idempotency-Key header and saves the result in the same database transaction as the delivery. A retry returns the saved result. The same key with a different body gets 422. | T9 Exactly-once |
| Two pays run at once on two instances. Can a delivery be paid twice? | No. Each write first locks the one ledger row, so the second pay waits and then finds nothing left to pay. The row lock is the database form of the mutex. | T5 Concurrency control |
| That one row is a queue of every writer. How far does it go? | It is simple and safe, and it limits writes to one line. Next, keep one row per driver, and sum those rows at read. Pay then locks drivers in a fixed order. | T9 Hot accounts |
| Why keep running totals? Why not SUM at read? | A SUM reads every row, so its cost grows with history. A running total costs one row read. The update shares a transaction with the delivery, and a test compares the totals with the rows. | T2 Isolation levels |
| Why units of 1/3600 of a cent and not a rational type? | The denominator is always 3600, so plain integer addition is exact. A rational type stores a denominator per value and slows every sum. Units also fit bigint, so the database stores them as they are. | T9 Money |
| The bank pays whole cents, and a payout is 12.34 and a fraction. Then what? | Pay the whole cents and keep the fraction as unpaid units. It joins the next payout, so no fraction is lost or created. Rounding each delivery would drift, and the sum would no longer match. | T9 Ledgers |
| A rate was wrong last month. Do you edit the deliveries? | No. A recorded cost is a fact that someone may have been paid on. Add a correction row with its own amount and reason. A ledger only gets new rows. | T9 Ledgers |
| Why /batch and not begin and commit over HTTP? | A batch is one request, so it holds no lock while a client thinks, and an abandoned transaction cannot exist. Begin and commit need sessions and expiry. The key-value exercise shows that shape. | T4 Locks in the database |
| Pay must now call a bank. What changes? | Hold no database transaction across the call. Save the intent, call the bank with an idempotency key, then record the outcome. A daily job compares our rows with the bank report. | C19 Payments |
| What makes this API safe for a real client? | Money travels as strings, because many JSON clients read numbers as floats. Times are integers. Errors carry the failed op. History reads need cursor pagination, not offsets. | R3 Requirements to API |
| The process dies just after pay answers. Is the payment safe? | In the build, no: everything is in memory. In Postgres, yes: the answer comes after the commit, and the commit flushes the write-ahead log first. | T1 ACID and the log |
| History grows to billions of paid rows. What slows down? | Not pay: the partial index holds only unpaid rows, so it stays small. Partition old deliveries by month and archive them. The running totals do not change. | D2 Indexes |
I start from what the build lacks: durability, retries, then two instances. I name each limit before the interviewer does.
Instances hold no state. Postgres holds the ledger, and one row lock lines up every writer.
| tool | build | production |
|---|---|---|
| Postgres | Mutex | A row lock on the one ledger row |
| Postgres | Sorted slice | Partial index on end time, unpaid rows only |
| Postgres | Undo log | A database transaction rolls back |
| Postgres | No retry safety | Idempotency keys, saved with the writes, kept 24 hours; a reused key gets 422 |
| Service | No auth, no metrics | The same bearer tokens and metrics as the key-value exercise |
| Service | ListenAndServe | Timeouts, a body limit, drain on SIGTERM |
Tested: production passes the same 36 grader checks. The running totals then match the rows. The real binary passes 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, service.go and handler.go of the build are imported as they are. The production package adds the files below. 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 delivery ledger. It reads DATABASE_URL, API_TOKENS
+ // (owner:token,owner:token) and ADDR, which defaults to :8080.
- // Command main serves the 45-minute delivery ledger.
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/delivery/prod"
+ kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
- "github.com/rudrite/system-design/arena/exercises/delivery/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
+ }
+ go sweep(ctx, pool)
+
+ 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
+ }
+
+ func sweep(ctx context.Context, pool *pgxpool.Pool) {
+ tick := time.NewTicker(time.Hour)
+ defer tick.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-tick.C:
+ if _, err := prod.Sweep(ctx, pool, 24*time.Hour); err != nil && ctx.Err() == nil {
+ log.Print(err)
+ }
+ }
+ }
- handler := build.Handler(build.NewService(build.NewMemStore()))
- log.Fatal(http.ListenAndServe(":8080", handler))
}CREATE TABLE IF NOT EXISTS rates (
driver text NOT NULL,
from_time bigint NOT NULL,
cents bigint NOT NULL CHECK (cents > 0),
PRIMARY KEY (driver, from_time)
);
CREATE TABLE IF NOT EXISTS deliveries (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
driver text NOT NULL,
start_time bigint NOT NULL,
end_time bigint NOT NULL CHECK (end_time > start_time),
units bigint NOT NULL CHECK (units >= 0),
paid boolean NOT NULL DEFAULT false
);
-- Pay reads only unpaid deliveries, so the index stays small as paid history grows.
CREATE INDEX IF NOT EXISTS deliveries_unpaid ON deliveries (end_time) WHERE NOT paid;
-- One row: the running totals, and the lock that puts writers in one line.
CREATE TABLE IF NOT EXISTS ledger (
id integer PRIMARY KEY CHECK (id = 1),
total_units bigint NOT NULL DEFAULT 0,
paid_units bigint NOT NULL DEFAULT 0
);
INSERT INTO ledger (id) VALUES (1) ON CONFLICT DO NOTHING;
CREATE TABLE IF NOT EXISTS idempotency (
owner text NOT NULL,
key text NOT NULL,
fingerprint bytea NOT NULL,
results jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (owner, key)
);pgstore: implements Storenew file, +159
+ // Package prod is the delivery ledger 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"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/rudrite/system-design/arena/exercises/delivery/build"
+ "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}
+ }
+
+ // Totals reads the running totals. It takes no lock, so reads do not wait for writers.
+ func (s *PGStore) Totals(ctx context.Context) (build.Totals, error) {
+ var t build.Totals
+ err := s.pool.QueryRow(ctx, `SELECT total_units, paid_units FROM ledger WHERE id = 1`).Scan(&t.Total, &t.Paid)
+ if err != nil {
+ return t, fmt.Errorf("read totals: %w", err)
+ }
+ return t, nil
+ }
+
+ // Update runs fn in one database transaction. The row lock on the ledger is the Postgres form of
+ // the build's mutex: it covers every instance, and it makes writers run one at a time, so two pays
+ // cannot deadlock on the rows they share. A request with an idempotency key saves its results in
+ // the same transaction, so a retry finds either the whole effect or none of it.
+ func (s *PGStore) Update(ctx context.Context, fn func(build.Tx) ([]build.Result, error)) ([]build.Result, error) {
+ var out []build.Result
+ err := pgx.BeginFunc(ctx, s.pool, func(db pgx.Tx) error {
+ if _, err := db.Exec(ctx, `SELECT 1 FROM ledger WHERE id = 1 FOR UPDATE`); err != nil {
+ return fmt.Errorf("lock ledger: %w", err)
+ }
+ req, keyed := ctx.Value(requestKey{}).(request)
+ if keyed {
+ saved, found, err := replay(ctx, db, req)
+ if err != nil {
+ return err
+ }
+ if found {
+ out = saved
+ return nil
+ }
+ }
+ var err error
+ if out, err = fn(pgTx{ctx, db}); err != nil {
+ return err
+ }
+ if !keyed {
+ return nil
+ }
+ _, err = db.Exec(ctx,
+ `INSERT INTO idempotency (owner, key, fingerprint, results) VALUES ($1, $2, $3, $4)`,
+ req.owner, req.key, req.fingerprint, out)
+ if err != nil {
+ return fmt.Errorf("save results: %w", err)
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+ }
+
+ // replay finds the saved results of an earlier request 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, db pgx.Tx, req request) ([]build.Result, bool, error) {
+ var fingerprint []byte
+ var results []build.Result
+ err := db.QueryRow(ctx, `SELECT fingerprint, results FROM idempotency WHERE owner = $1 AND key = $2`,
+ req.owner, req.key).Scan(&fingerprint, &results)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, false, nil
+ }
+ if err != nil {
+ return nil, false, fmt.Errorf("read results: %w", err)
+ }
+ if !bytes.Equal(fingerprint, req.fingerprint) {
+ idempotent.MarkReused(ctx)
+ return nil, false, fmt.Errorf("%w: key used for a different request", build.ErrConflict)
+ }
+ return results, true, nil
+ }
+
+ // pgTx implements build.Tx on one database transaction.
+ type pgTx struct {
+ ctx context.Context
+ db pgx.Tx
+ }
+
+ func (t pgTx) Rates(id string) ([]build.Rate, error) {
+ rows, err := t.db.Query(t.ctx, `SELECT from_time, cents FROM rates WHERE driver = $1 ORDER BY from_time`, id)
+ if err != nil {
+ return nil, fmt.Errorf("read rates: %w", err)
+ }
+ rates, err := pgx.CollectRows(rows, pgx.RowToStructByPos[build.Rate])
+ if err != nil {
+ return nil, fmt.Errorf("read rates: %w", err)
+ }
+ if len(rates) == 0 {
+ return nil, build.ErrNotFound
+ }
+ return rates, nil
+ }
+
+ func (t pgTx) AddRate(id string, r build.Rate) error {
+ _, err := t.db.Exec(t.ctx, `INSERT INTO rates (driver, from_time, cents) VALUES ($1, $2, $3)`, id, r.From, r.Cents)
+ if err != nil {
+ return fmt.Errorf("add rate: %w", err)
+ }
+ return nil
+ }
+
+ func (t pgTx) AddDelivery(d build.Delivery) error {
+ _, err := t.db.Exec(t.ctx, `INSERT INTO deliveries (driver, start_time, end_time, units) VALUES ($1, $2, $3, $4)`,
+ d.Driver, d.Start, d.End, d.Units)
+ if err != nil {
+ return fmt.Errorf("add delivery: %w", err)
+ }
+ _, err = t.db.Exec(t.ctx, `UPDATE ledger SET total_units = total_units + $1 WHERE id = 1`, d.Units)
+ if err != nil {
+ return fmt.Errorf("add to total: %w", err)
+ }
+ return nil
+ }
+
+ const pay = `
+ WITH paid AS (
+ UPDATE deliveries SET paid = true WHERE NOT paid AND end_time <= $1 RETURNING units
+ )
+ SELECT count(*), coalesce(sum(units), 0)::bigint FROM paid`
+
+ func (t pgTx) Pay(upTo int64) (int64, int64, error) {
+ var count, units int64
+ if err := t.db.QueryRow(t.ctx, pay, upTo).Scan(&count, &units); err != nil {
+ return 0, 0, fmt.Errorf("pay: %w", err)
+ }
+ _, err := t.db.Exec(t.ctx, `UPDATE ledger SET paid_units = paid_units + $1 WHERE id = 1`, units)
+ if err != nil {
+ return 0, 0, fmt.Errorf("add to paid: %w", err)
+ }
+ return count, units, nil
+ }server: keys and authnew file, +90
+ 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/delivery/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. It also limits a batch, and so the time a batch holds the ledger
+ // lock. A larger body 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))
+ })
+ }
+
+ // Sweep deletes saved results older than keep and returns how many.
+ func Sweep(ctx context.Context, pool *pgxpool.Pool, keep time.Duration) (int64, error) {
+ tag, err := pool.Exec(ctx, `DELETE FROM idempotency WHERE created_at < now() - $1::interval`, keep)
+ if err != nil {
+ return 0, fmt.Errorf("sweep idempotency keys: %w", err)
+ }
+ return tag.RowsAffected(), nil
+ }
+
+ // 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 10 known
Rate 1000 cents an hour, one second. Why does the service store 1000 and not 0.2777...?
Three deliveries each cost one third of a dollar. Why is rounding each one wrong?
Units go out as a JSON string. Why not a number?
Pay up to 100 has run. A delivery that ends at 70 arrives. What is the unpaid amount?
Why does pay cut the sorted list and not scan all deliveries?
Pay used to keep the old slice for its undo. A long random test found a bug. What was it?
Why does a failed batch run undo closures and not copy the store first?
Why does production lock the ledger row before it reads the idempotency key?
A request with a key fails with 404. Is the key saved?
In production, one key arrives with a different body. What is the answer?
- build
- 463 lines with tests, 19:57 of typing at 100 words a minute.
- checks
- 36 grader checks, in 4 groups.
- unit
- 1/3600 of a cent: cents an hour times seconds.
- largest
- 1,000,000 × 604,800 = 604,800,000,000 units for one delivery.
- headroom
- 15,250,284 of those fit in int64 (derived, tested).
- typical
- 30 minutes at 20.00 is 3,600,000 units, so about 2.5 trillion fit.
- race
- 50 records and 50 pays; paid plus left equals recorded.
- keys
- Kept 24 hours. The body limit of 1 MiB also bounds a batch.
Design values from the tested code, not load measurements.