Travel expense calculation
The arithmetic looks easy, and that is the test. Name the unit, name the rounding rule, and keep both in every path. A float passes every simple case and fails on a tie.
- 1Money is an integer of minor units, and a rate is an integer of millionths. No float touches a value.
- 2State one rounding rule: half up, once per expense, at conversion. Round again only for a percent, once per category.
- 3A rate is fixed once per date, and each expense keeps the rate that made its base.
- 4One net settles the trip: allowed minus what the company card paid. Its sign says who pays.
Build a travel expense service as an HTTP API, in memory. Record expenses for a trip, with a currency, a category and a date. Some categories have a per-diem limit. Compute what the company reimburses and what the employee owes. Money must be exact. Then add exchange rates fixed by date, caps per category, and partial reimbursement. Many clients call the service at once.
| ask | answer assumed |
|---|---|
| What currency does the company pay in? | US dollars. Limits and results are in cents. |
| Who paid? | Each expense says employee or company card. |
| How does a rate work? | Dollars for one major unit, in millionths. One rate per currency per date. |
| What is the rounding rule? | Half up to the cent, once per expense, at conversion. |
| In what order do limits apply? | Per diem, then cap, then percent. |
| A rate is missing? | The expense is refused with 422. |
| Who is on a trip? | One employee. |
Before I type, I confirm the unit, the rounding rule and the order of the limits. I write them down, because every number depends on them.
| request | success | errors |
|---|---|---|
| PUT /trips/{id} | 200 limits | 400 |
| PUT /rates/{currency}/{date} | 200 micros | 400, 409 |
| POST /trips/{id}/expenses | 201 id, base, micros | 400, 404, 422 |
| GET /trips/{id}/summary | 200 totals | 404 |
- A trip has the body {"per_diem":{"food":7500},"caps":{"hotel":25000},"percent":{"phone":50}}. All three are optional.
- A rate has the body {"micros":1082500}, which means 1.0825 dollars.
- An expense has category, date as YYYY-MM-DD, amount in minor units, currency, and paid_by.
- The summary has spent, allowed, company_paid, reimburse and owes, in cents.
- Currencies are USD, EUR, GBP, INR, JPY and KWD. A repeat of the same rate is 200. A different rate for a fixed date is 409.
Every amount is an integer with its unit in the contract. A rate cannot change, and a summary is computed on read.
| by | build | proof | if you are late |
|---|---|---|---|
| 15 min | The kit, renamed. Trips and expenses in dollars. Settle with allowed, company paid and the net. | TestSettle | Skip validation of limits. Add it in the last 5 minutes. |
| 30 min | Per diem by category and day. Caps and percent. mulDiv with half up. | TestSettle | Build per diem. Say the order of cap and percent out loud. |
| 45 min | Rates by date, the minor unit table, Convert at add time. Race test. | TestRates, TestParallelAdds | Keep rates in USD and EUR only. Name the minor unit problem. |
I keep a running service at each checkpoint. Follow-ups arrive in the order the interviewer chooses, so each one is a small change.
Convert once, then apply the limits in a fixed order. The result is one net number, and its sign says who pays.
| method | 1.00 EUR at 1.005 | status |
|---|---|---|
| Float rate, Round | 100.49999999999999, so 100 | Not approved |
| Float, then truncate | 100 | Not approved |
| Round half to even | 100 | State it |
| Integers, half up | 101 | Approved |
- Across 100 rates from 1.005 to 1.995, each a tie for one euro, float64 rounds 7 the wrong way.
- Half to even is also exact. It is a valid rule, but it is not the rule stated here, so the grader marks it wrong.
- The result must be one rule, written down, and used on every path.
A server that computes in float64 passes all but these checks.
FAIL rounding: half a cent rounds up
want reimburse 101, got 100
FAIL rounding: half a cent rounds up above an odd cent too
want reimburse 102, got 101
44 checks: 42 passed, 2 failed1.005 is not a number that float64 can hold. A tie falls on the wrong side, so I keep integers to the last step.
| where | rule | why there |
|---|---|---|
| Each expense, at conversion | Half up to the cent | A new expense cannot change an old one. |
| Each category, at percent | Half up to the cent | The percent applies to what the limits left. |
| Sums and limits | No rounding | Integers add exactly. |
| case | exact | cents |
|---|---|---|
| 1.00 EUR at 1.005 | 100.5 | 101 |
| 1.00 EUR at 1.004999 | 100.4999 | 100 |
| 1000 JPY at 0.0067 | 670 | 670 |
| 1.000 KWD at 3.255 | 325.5 | 326 |
| 0.001 KWD at 3.255 | 0.3255 | 0 |
| 3.33 at 50 percent | 166.5 | 167 |
Each row is a tested case.
There are two rounding points, and each runs once. Nothing else rounds, so sums stay exact.
| part | value |
|---|---|
| Lines, with tests | 443 |
| Typed characters | 9,900 |
| Typing at 500 a minute | 19:48 |
| Typing at 300 a minute | 33:00 |
| Left for thinking, at 500 a minute | 25:12 |
| Dependencies | 0 |
- Write the unit and the rounding rule at the top of your notes first.
- 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 two short functions in calc.go.
package build
import "math/big"
// Base is the currency the company pays in.
const Base = "USD"
// perMajor gives a currency's minor units in one major unit: 100 cents in a dollar, 1 yen in a yen.
var perMajor = map[string]int64{1"USD": 100, "EUR": 100, "GBP": 100, "INR": 100, "JPY": 1, "KWD": 1000}
// mulDiv returns a * b / d, rounded half up. a * b can pass 64 bits, so it uses big integers. None
// of the three is negative, and d is even.
func mulDiv(a, b, d int64) int64 {
n := new(big.Int).Mul(big.NewInt(a), big.NewInt(b))2
n.Add(n, big.NewInt(d/2))3
return n.Div(n, big.NewInt(d)).Int64()
}
// Convert turns an amount in a currency's minor units into cents. micros is the US dollars one
// major unit buys, in millionths of a dollar.
func Convert(amount int64, currency string, micros int64) int64 {
return mulDiv(amount*perMajor[Base], micros, perMajor[currency]*1_000_000)4
}
// Settle computes a trip from its expenses. It reads nothing but its arguments, and the order of
// the expenses does not change the result.
func Settle(trip Trip, expenses []Expense) Summary {
s := Summary{Trip: trip.ID}
days := map[[2]string]int64{}
for _, e := range expenses {
s.Spent += e.Base
days[[2]string{e.Category, e.Date}] += e.Base5
if e.PaidBy == "company" {
s.CompanyPaid += e.Base
}
}
allowed := map[string]int64{}
for day, amount := range days {
if limit, ok := trip.PerDiem[day[0]]; ok {
amount = min(amount, limit)
}
allowed[day[0]] += amount
}
for category, amount := range allowed {
if limit, ok := trip.Caps[category]; ok {
amount = min(amount, limit)
}
if percent, ok := trip.Percent[category]; ok {
amount = mulDiv(amount, percent, 100)7
}
s.Allowed += amount
}
net := s.Allowed - s.CompanyPaid8
s.Reimburse, s.Owes = max(net, 0), max(-net, 0)
return s
}
- 1Not every currency has cents. Yen has no minor unit, and the Kuwaiti dinar has 1000 fils.
- 2The product can pass 64 bits, even when the result fits.
- 3Half up: add half the divisor, then let the integer division cut. This works because no value is negative.
- 4One division, at the end. Dividing early would lose digits before the rounding.
- 5A per diem limits one category on one day, so the sum has that key.
- 6First limit: per diem, per day.
- 7Last limit: the percent applies to what remains. This is the second and last rounding point.
- 8One number. No expense needs to be matched to a payer.
All the arithmetic is in this file, and none of it touches the store. Settle is a pure function, so I can test it with a table.
package build
import (
"context"
"errors"
"sync"
)
var (
ErrInvalid = errors.New("invalid")
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
ErrNoRate = errors.New("no rate")
)
// Trip holds one trip's limits, in cents. PerDiem is a limit per category per day, Caps a limit per
// category per trip, and Percent the share of a category the company pays, from 0 to 100.
type Trip struct {
ID string `json:"id"`
PerDiem map[string]int64 `json:"per_diem"`
Caps map[string]int64 `json:"caps"`
Percent map[string]int64 `json:"percent"`
}
// Expense is one recorded expense. Amount is in the minor units of Currency. Base is the same
// money in cents, fixed when the expense is recorded, and Micros is the rate that made it.
type Expense struct {
ID string `json:"id"`
Trip string `json:"trip"`
Date string `json:"date"`
Category string `json:"category"`
Amount int64 `json:"amount"`
Currency string `json:"currency"`
PaidBy string `json:"paid_by"`
Micros int64 `json:"micros"`1
Base int64 `json:"base"`2
}
// Summary is what a trip comes to, in cents.
type Summary struct {
Trip string `json:"trip"`
Spent int64 `json:"spent"`
Allowed int64 `json:"allowed"`
CompanyPaid int64 `json:"company_paid"`
Reimburse int64 `json:"reimburse"`
Owes int64 `json:"owes"`
}
type Store interface {
PutTrip(ctx context.Context, trip Trip) error
// FixRate saves a rate once. A different rate for that currency and date is ErrConflict.
FixRate(ctx context.Context, currency, date string, micros int64) error
Rate(ctx context.Context, currency, date string) (int64, error)
AddExpense(ctx context.Context, e Expense) error
Expenses(ctx context.Context, trip string) (Trip, []Expense, error)
}
type MemStore struct {
mu sync.Mutex
trips map[string]Trip
expenses map[string][]Expense
rates map[string]int64
}
func NewMemStore() *MemStore {
return &MemStore{trips: map[string]Trip{}, expenses: map[string][]Expense{}, rates: map[string]int64{}}
}
func (s *MemStore) PutTrip(_ context.Context, trip Trip) error {
s.mu.Lock()
defer s.mu.Unlock()
s.trips[trip.ID] = trip
return nil
}
func (s *MemStore) FixRate(_ context.Context, currency, date string, micros int64) error {
s.mu.Lock()
defer s.mu.Unlock()
if fixed, ok := s.rates[currency+date]; ok && fixed != micros {3
return ErrConflict
}
s.rates[currency+date] = micros4
return nil
}
func (s *MemStore) Rate(_ context.Context, currency, date string) (int64, error) {
s.mu.Lock()
defer s.mu.Unlock()
micros, ok := s.rates[currency+date]
if !ok {
return 0, ErrNoRate
}
return micros, nil
}
func (s *MemStore) AddExpense(_ context.Context, e Expense) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.trips[e.Trip]; !ok {
return ErrNotFound
}
s.expenses[e.Trip] = append(s.expenses[e.Trip], e)5
return nil
}
func (s *MemStore) Expenses(_ context.Context, id string) (Trip, []Expense, error) {
s.mu.Lock()
defer s.mu.Unlock()
trip, ok := s.trips[id]
if !ok {
return Trip{}, nil, ErrNotFound
}
return trip, s.expenses[id], nil
}
- 1The rate that made Base. An auditor can repeat the arithmetic from this one row.
- 2Saved once. The summary reads it and never converts.
- 3The same rate again is fine, so a retry of the PUT is safe. Another value is 409.
- 4The key is safe as a joined string: the service has checked the currency and the date before this.
- 5No running total. The sum happens at read time, so there is no total to get wrong.
The store keeps rows. FixRate is the only check-then-act, and it runs under the lock.
package build
import (
"context"
"crypto/rand"
"fmt"
"time"
)
// Limits that keep every sum far from the end of int64.
const (
maxAmount = 10_000_000_000
maxMicros = 1_000_000_0001
)
type Service struct {
store Store
}
func NewService(store Store) *Service {
return &Service{store}
}
func invalid(format string, args ...any) error {
return fmt.Errorf("%w: "+format, append([]any{ErrInvalid}, args...)...)
}
func validDate(date string) error {
if _, err := time.Parse(time.DateOnly, date)3; err != nil {
return invalid("date must be YYYY-MM-DD")
}
return nil
}
func (s *Service) PutTrip(ctx context.Context, trip Trip) (Trip, error) {
for _, limits := range []map[string]int64{trip.PerDiem, trip.Caps, trip.Percent} {
for category, limit := range limits {
if limit < 0 {
return trip, invalid("%s must not be negative", category)
}
}
}
for category, percent := range trip.Percent {
if percent > 100 {
return trip, invalid("%s is over 100 percent", category)
}
}
return trip, s.store.PutTrip(ctx, trip)
}
func (s *Service) FixRate(ctx context.Context, currency, date string, micros int64) error {
if perMajor[currency] == 0 || currency == Base {2
return invalid("no rate for currency %q", currency)
}
if micros <= 0 || micros > maxMicros {
return invalid("micros must be from 1 to %d", maxMicros)
}
if err := validDate(date); err != nil {
return err
}
return s.store.FixRate(ctx, currency, date, micros)
}
// AddExpense reads the rate and then saves the expense, with no lock over both. A fixed rate never
// changes, so the two steps cannot disagree.
func (s *Service) AddExpense(ctx context.Context, e Expense) (Expense, error) {
if e.Category == "" || perMajor[e.Currency] == 0 {
return e, invalid("category and a known currency are required")
}
if e.PaidBy != "employee" && e.PaidBy != "company" {
return e, invalid("paid_by must be employee or company")
}
if e.Amount <= 0 || e.Amount > maxAmount {
return e, invalid("amount must be from 1 to %d", maxAmount)
}
if err := validDate(e.Date); err != nil {
return e, err
}
e.Micros = 1_000_0004
if e.Currency != Base {
var err error
if e.Micros, err = s.store.Rate(ctx, e.Currency, e.Date); err != nil {
return e, err
}
}
e.ID = rand.Text()
e.Base = Convert(e.Amount, e.Currency, e.Micros)5
return e, s.store.AddExpense(ctx, e)
}
func (s *Service) Summary(ctx context.Context, id string) (Summary, error) {
trip, expenses, err := s.store.Expenses(ctx, id)
if err != nil {
return Summary{}, err
}
return Settle(trip, expenses), nil
}
- 1These limits are what keep every result in int64: 10^10 at 1000 dollars each is 10^15 cents.
- 2A rate for the base currency is a mistake, so it is refused.
- 3Parse refuses 2026-02-30. A regular expression would not.
- 4Dollars have a rate of 1.000000, so they share one code path with every other currency.
- 5The first rounding point, and the only conversion in the program.
The service checks everything before it reads the rate. A bad request and a missing rate have different status codes, so the order matters.
package build
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
)
func Handler(svc *Service) http.Handler {
mux := http.NewServeMux()
mux.Handle("PUT /trips/{id}", route(200, func(r *http.Request) (any, error) {
var trip Trip
if err := readJSON(r, &trip); err != nil {
return nil, err
}
trip.ID = r.PathValue("id")1
return svc.PutTrip(r.Context(), trip)
}))
mux.Handle("PUT /rates/{currency}/{date}", route(200, func(r *http.Request) (any, error) {
var body struct {
Micros int64 `json:"micros"`
}
if err := readJSON(r, &body); err != nil {
return nil, err
}
return body, svc.FixRate(r.Context(), r.PathValue("currency"), r.PathValue("date"), body.Micros)
}))
mux.Handle("POST /trips/{id}/expenses", route(201, func(r *http.Request) (any, error) {
var e Expense
if err := readJSON(r, &e); err != nil {
return nil, err
}
e.Trip = r.PathValue("id")
return svc.AddExpense(r.Context(), e)
}))
mux.Handle("GET /trips/{id}/summary", route(200, func(r *http.Request) (any, error) {
return svc.Summary(r.Context(), r.PathValue("id"))
}))
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
case errors.Is(err, ErrNoRate):2
status = 422
default:
log.Print(err)
err = errors.New("internal error")
}
return status, map[string]string{"error": err.Error()}
}
- 1The path wins over the body, so a client cannot write to a different trip.
- 2A valid request that the current state cannot serve. The same request works after the rate is fixed.
// Command main serves the 45-minute travel expense calculator.
package main
import (
"log"
"net/http"
"github.com/rudrite/system-design/arena/exercises/travel/build"
)
func main() {
handler := build.Handler(build.NewService(build.NewMemStore()))
log.Fatal(http.ListenAndServe(":8080", handler))
}
The trip and the rate use PUT, because the client names them. The expense uses POST, because the server names it.
package build
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
const (
trip, summary = "/trips/t", "/trips/t/summary"
add, rate = "/trips/t/expenses", "/rates/EUR/2026-03-01"
)
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 expense(category string, day, amount int, currency, payer string) string {
return fmt.Sprintf(`{"category":%q,"date":"2026-03-%02d","amount":%d,"currency":%q,"paid_by":%q}`,
category, day, amount, currency, payer)
}
func TestSettle(t *testing.T) {
run(t, newHandler(), []step{
{"PUT", trip, `{"per_diem":{"food":5000}}`, 200, ""},
{"POST", add, expense("food", 1, 4000, "USD", "employee"), 201, ""},
{"POST", add, expense("food", 1, 4000, "USD", "employee"), 201, ""},
{"POST", add, expense("food", 2, 1000, "USD", "company"), 201, ""},
{"GET", summary, "", 200, `"allowed":6000,"company_paid":1000,"reimburse":5000,"owes":0`},1
{"POST", add, expense("hotel", 2, 9000, "USD", "company"), 201, ""},
{"PUT", trip, `{"caps":{"hotel":100},"percent":{"food":0}}`, 200, ""},
{"GET", summary, "", 200, `"reimburse":0,"owes":9900`},2
})
}
func TestRates(t *testing.T) {
run(t, newHandler(), []step{
{"PUT", trip, `{}`, 200, ""},
{"POST", add, expense("food", 1, 100, "EUR", "employee"), 422, ""},
{"PUT", rate, `{"micros":1005000}`, 200, ""},
{"PUT", rate, `{"micros":1100000}`, 409, ""},
{"POST", add, expense("food", 1, 100, "EUR", "employee"), 201, `"base":101`},3
})
}
func TestParallelAdds(t *testing.T) {
h := newHandler()
do(h, "PUT", trip, `{"per_diem":{"food":6000}}`)
var wg sync.WaitGroup
for range 100 {
wg.Go(func() { do(h, "POST", add, expense("food", 1, 100, "USD", "employee")) })
}
wg.Wait()
run(t, h, []step{{"GET", summary, "", 200, `"spent":10000,"allowed":6000`}})
}
- 1Day 1 stops at 5000 and day 2 adds 1000. The company card takes 1000 from the net.
- 2New limits apply to the whole trip, because a summary is computed on read.
- 3The tie. A float answers 100.
Each test is a list of steps, so a new behaviour is one row. The tie at 1.005 is in the test because float gets it wrong.
arena run travel --base http://localhost:8080
correctness
PASS an empty trip settles to zero
PASS the company reimburses what the employee paid
PASS a company card within limits settles to zero
PASS a company card over the limit: the employee owes the excess
PASS both payers on one day: the result is one net amount
PASS per diem: under the limit pays in full
PASS per diem: exactly the limit pays in full
PASS per diem: adds up within one day
PASS per diem: each day has its own limit
PASS per diem: each category has its own limit
PASS cap: limits a category across days
PASS cap: comes after per diem
PASS cap: of zero pays nothing
PASS partial: pays a percent of the category
PASS partial: comes after per diem and cap
PASS partial: of 100 and of 0
PASS trips are apart
PASS limits set later apply to the whole trip
PASS a date's rate applies to that date only
PASS per diem is compared in dollars after conversion
PASS a currency with no minor unit: JPY
PASS a currency with three digits: KWD
PASS rounding: half a cent rounds up
PASS rounding: just under half a cent rounds down
PASS rounding: half a cent rounds up above an odd cent too
PASS rounding: a very small amount can round to zero
PASS rounding: a large amount stays exact
PASS rounding: each expense rounds on its own, not the sum
PASS rounding: a percent rounds half up once, per category
status codes
PASS a trip is 200 on create and on replace
PASS a new expense is 201 and returns its id and base
PASS an unknown trip is 404
PASS an expense with no rate for its date is 422
PASS the same rate again is 200
PASS a different rate for a fixed date is 409
validation
PASS malformed JSON is 400
PASS a bad expense is 400
PASS a bad limit is 400
PASS a bad rate is 400
concurrency
PASS 100 parallel adds to one trip: every cent is counted
PASS 100 parallel adds in one day: per diem stops at the limit
PASS 100 parallel adds in JPY: each rounds on its own
PASS 100 parallel fixes of one rate: exactly one value wins
PASS 100 parallel adds to 10 trips stay apart
44 checks: 44 passed, 0 failedAll checks pass, with 100 parallel requests in each race.
{Name: "100 parallel adds to one trip: every cent is counted", Group: grader.Concurrency, Run: func(t *grader.T) {
id := putTrip(t, "{}")
date := day(t)
t.Parallel(parallel, func(i int) {
t.Status(addOn(t, id, food(int64(i+1)), date), 201)
})
wantSummary(t, id, want{"spent": 5050, "reimburse": 5050})
}},A server that copies the list, unlocks, and writes the copy back. The race detector stays quiet, because each step holds the lock.
FAIL 100 parallel adds to one trip: every cent is counted
want spent 5050, got 253
FAIL 100 parallel adds in one day: per diem stops at the limit
want spent 10000, got 100
FAIL 100 parallel adds in JPY: each rounds on its own
want spent 100, got 1
FAIL 100 parallel adds to 10 trips stay apart
want spent 70, got 14
44 checks: 40 passed, 4 failedAn add is safe only if no add is lost. The grader sends 100 at once, each with a different amount, so the sum proves that each one landed.
| follow-up | what changes |
|---|---|
| Rates fixed by date | A map with FixRate, and Convert at add time. |
| Per-category caps | One map on Trip, and one min in Settle. |
| Partial reimbursement | One map on Trip, and one mulDiv in Settle. |
| A second base currency | A base per company, and a rate per pair. Not in this build. |
| Per diem by city | A city on each expense, and a longer map key. Not in this build. |
Each follow-up is a few lines, because Settle has one place for each limit.
| choice | status |
|---|---|
| Integer minor units | Approved |
| Float dollars | Not approved |
| One stated rounding rule | Approved |
| Round the sum at the end | Not approved |
| Assume two decimals for every currency | Not approved |
| A running total on the trip | Sum on read |
| Overwrite a rate | Not approved |
| A live rate at summary time | Not approved |
I say what I chose and what it costs, then I move on.
| the interviewer asks | the answer | goes deeper |
|---|---|---|
| Why integers and not a decimal type? | Both are exact. An integer of minor units makes the unit plain in every column and every JSON field, and it fits in bigint. A decimal in Postgres is fine too, but the JSON layer must then carry strings. I must still choose where to round. | T9 Exactly-once |
| The company now pays the reimbursement. How do you pay exactly once? | This service computes the amount. Paying is a ledger entry with a unique key, and that key also goes to the bank. A retry finds the entry and sends nothing new. | T9 Exactly-once |
| The client times out and retries an add. | Without a key, the trip counts the expense twice, and the company pays twice. An Idempotency-Key header fixes this. The key row, the expense and the saved response commit in one database transaction. The same key with a different body gets 422. | T9 Exactly-once |
| A rate was wrong. How do you fix it? | A fixed rate never changes, so history stays true. Add a correction instead: a new expense line that reverses the old one, with a reason and a person. An audit can then explain each number. | T9 Exactly-once |
| Reimbursements go out with the monthly payroll. | Close the trip, so its summary stops changing, and add the amount to the payroll run as one item. The run then pays it with a unique key per employee. A failed item retries alone. | C24 Payroll run |
| A per diem changes in January. What about December trips? | Limits are effective dated, as tax rules are in payroll. The trip date picks the version, and the trip keeps it. In this build, a change to the limits applies to the whole trip, and I say so. | C24 Payroll run |
| Walk me through your API choices. | PUT for a trip and a rate, because the client names them, so a repeat is safe. POST for an expense, because the server names it, so it needs a key. Amounts are integers with the unit in the docs. | R3 Requirements to API |
| Why 422 for a missing rate and 400 for a bad date? | A bad date is wrong whatever the server holds. A missing rate is a valid request that the current state cannot serve, and the same request works after finance fixes the rate. The client needs to tell the two apart. | R3 Requirements to API |
| Run two instances. What breaks? | Nothing about the sum, because an add is one insert and the sum happens at read time. The rate needs care: the primary key gives one row per date, and the upsert returns the row that won. | T5 Concurrency control |
| A summary runs while limits change. What does it see? | It reads the limits and the rows in one repeatable read transaction, so it sees one state. At read committed, two statements could mix an old limit and new rows. | T2 Isolation levels |
| What goes in the schema? | Each expense keeps the amount, the currency, the rate and the base. The base is derived, but I store it, because the rounding rule could change one day and old numbers must not. Money columns are bigint with check constraints. | D3 Data modeling |
| Who may see a trip, and what do you watch? | Each row carries the owner from the token, and another owner gets 404. On the dashboard, I watch the 422 rate. It shows that finance has not fixed a rate for a date in use, or that a client reuses a key. | O5 Security |
I start from what the build lacks: paying the money, retries, then two instances. I name each limit before the interviewer does.
Instances hold no state. An add is one insert, so parallel adds do not wait for each other.
| tool | build | production |
|---|---|---|
| Postgres | MemStore: maps and one mutex | PGStore: three tables, bigint money |
| Postgres | FixRate under the mutex | A primary key, and an upsert that returns the winner |
| Postgres | A read under the mutex | One repeatable read snapshot |
| Postgres | A retry counts twice | Idempotency-Key, saved in the same transaction; a reused key gets 422 |
| Service | No auth | Bearer tokens, the same as E1; each row has an owner |
| Service | ListenAndServe | Metrics, health, a 64 KiB body limit, drain on SIGTERM |
Tested: production passes the same 44 grader checks. The real binary passes them over a socket, then exits cleanly on SIGTERM. Parallel adds and rate fixes across two instances lose nothing.
Not built: the payment itself, closing a trip, corrections, and a sweep of old idempotency keys.
One interface, one new implementation, and wrappers around the same handler. The arithmetic does not change.
calc.go, store.go, service.go and handler.go of the build are imported as they are. The production package adds the files below.
+ // Command main serves the production travel expense calculator. It reads DATABASE_URL, API_TOKENS
+ // (owner:token,owner:token) and ADDR, which defaults to :8080.
- // Command main serves the 45-minute travel expense calculator.
package main
import (
+ "cmp"
+ "context"
+ "errors"
"log"
"net/http"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
+ "github.com/rudrite/system-design/arena/exercises/travel/prod"
- "github.com/rudrite/system-design/arena/exercises/travel/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
- handler := build.Handler(build.NewService(build.NewMemStore()))
- log.Fatal(http.ListenAndServe(":8080", handler))
}CREATE TABLE IF NOT EXISTS trips (
owner text NOT NULL,
id text NOT NULL,
limits jsonb NOT NULL,
PRIMARY KEY (owner, id)
);
-- The primary key is what fixes a rate: a currency has one row per date.
CREATE TABLE IF NOT EXISTS rates (
owner text NOT NULL,
currency text NOT NULL,
day date NOT NULL,
micros bigint NOT NULL CHECK (micros > 0),
PRIMARY KEY (owner, currency, day)
);
-- Money is bigint, never float or numeric. Each row keeps the rate that made its base amount.
CREATE TABLE IF NOT EXISTS expenses (
id text PRIMARY KEY,
owner text NOT NULL,
trip text NOT NULL,
day date NOT NULL,
category text NOT NULL,
amount bigint NOT NULL CHECK (amount > 0),
currency text NOT NULL,
paid_by text NOT NULL CHECK (paid_by IN ('employee', 'company')),
micros bigint NOT NULL CHECK (micros > 0),
base bigint NOT NULL CHECK (base >= 0),
FOREIGN KEY (owner, trip) REFERENCES trips (owner, id)
);
CREATE INDEX IF NOT EXISTS expenses_trip ON expenses (owner, trip);pgstore: implements Storenew file, +146
+ // Package prod is the travel expense calculator made production grade. It imports the 45-minute
+ // build and replaces the in-memory store behind its interface, then adds auth, metrics, health and
+ // safe retries. The arithmetic, the service and the handler do not change.
+ package prod
+
+ import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
+ "github.com/rudrite/system-design/arena/exercises/travel/build"
+ "github.com/rudrite/system-design/arena/internal/idempotent"
+ )
+
+ // PGStore implements build.Store on Postgres. Every row carries the token's owner, so another
+ // owner's IDs read as missing.
+ type PGStore struct {
+ pool *pgxpool.Pool
+ }
+
+ // NewPGStore returns a store on pool.
+ func NewPGStore(pool *pgxpool.Pool) *PGStore {
+ return &PGStore{pool: pool}
+ }
+
+ type querier interface {
+ Exec(context.Context, string, ...any) (pgconn.CommandTag, error)
+ QueryRow(context.Context, string, ...any) pgx.Row
+ }
+
+ // conn joins the request's transaction when it has one, so the expense and the saved response land
+ // together. Otherwise it is the pool.
+ func (s *PGStore) conn(ctx context.Context) querier {
+ if tx, ok := idempotent.Tx(ctx); ok {
+ return tx
+ }
+ return s.pool
+ }
+
+ // PutTrip saves a trip's limits. Expenses have a foreign key to the trip, but an update of its
+ // limits does not touch the key, so it does not wait for adds in progress.
+ func (s *PGStore) PutTrip(ctx context.Context, trip build.Trip) error {
+ _, err := s.conn(ctx).Exec(ctx, `
+ INSERT INTO trips (owner, id, limits) VALUES ($1, $2, $3)
+ ON CONFLICT (owner, id) DO UPDATE SET limits = excluded.limits`,
+ kv.OwnerFrom(ctx), trip.ID, trip)
+ if err != nil {
+ return fmt.Errorf("save trip: %w", err)
+ }
+ return nil
+ }
+
+ // fixRate writes the rate if the date has none, and returns the rate that is now fixed. The
+ // DO UPDATE changes nothing. It is there because DO NOTHING returns no row.
+ const fixRate = `
+ INSERT INTO rates (owner, currency, day, micros) VALUES ($1, $2, $3::date, $4)
+ ON CONFLICT (owner, currency, day) DO UPDATE SET micros = rates.micros
+ RETURNING micros`
+
+ // FixRate saves a rate once. The first writer wins, and any other value is a conflict.
+ func (s *PGStore) FixRate(ctx context.Context, currency, date string, micros int64) error {
+ var fixed int64
+ err := s.conn(ctx).QueryRow(ctx, fixRate, kv.OwnerFrom(ctx), currency, date, micros).Scan(&fixed)
+ if err != nil {
+ return fmt.Errorf("fix rate: %w", err)
+ }
+ if fixed != micros {
+ return build.ErrConflict
+ }
+ return nil
+ }
+
+ // Rate reads a fixed rate.
+ func (s *PGStore) Rate(ctx context.Context, currency, date string) (int64, error) {
+ var micros int64
+ err := s.conn(ctx).QueryRow(ctx, `SELECT micros FROM rates WHERE owner = $1 AND currency = $2 AND day = $3::date`,
+ kv.OwnerFrom(ctx), currency, date).Scan(µs)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return 0, build.ErrNoRate
+ }
+ if err != nil {
+ return 0, fmt.Errorf("read rate: %w", err)
+ }
+ return micros, nil
+ }
+
+ // addExpense inserts one row, or none when the trip does not exist. A failed foreign key would
+ // abort the transaction, and then the 404 could not be saved for a retry.
+ const addExpense = `
+ INSERT INTO expenses (id, owner, trip, day, category, amount, currency, paid_by, micros, base)
+ SELECT $1, t.owner, t.id, $4::date, $5, $6, $7, $8, $9, $10
+ FROM trips t WHERE t.owner = $2 AND t.id = $3`
+
+ // AddExpense is one insert. Parallel adds to one trip do not wait for each other, and the sum
+ // happens at read time, so there is no running total to lose.
+ func (s *PGStore) AddExpense(ctx context.Context, e build.Expense) error {
+ tag, err := s.conn(ctx).Exec(ctx, addExpense, e.ID, kv.OwnerFrom(ctx), e.Trip, e.Date,
+ e.Category, e.Amount, e.Currency, e.PaidBy, e.Micros, e.Base)
+ if err != nil {
+ return fmt.Errorf("add expense: %w", err)
+ }
+ if tag.RowsAffected() == 0 {
+ return build.ErrNotFound
+ }
+ return nil
+ }
+
+ // Expenses reads the limits and the rows in one snapshot, so a summary never mixes two states.
+ func (s *PGStore) Expenses(ctx context.Context, id string) (build.Trip, []build.Expense, error) {
+ var (
+ trip build.Trip
+ expenses []build.Expense
+ )
+ options := pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}
+ err := pgx.BeginTxFunc(ctx, s.pool, options, func(tx pgx.Tx) error {
+ owner := kv.OwnerFrom(ctx)
+ err := tx.QueryRow(ctx, `SELECT limits FROM trips WHERE owner = $1 AND id = $2`, owner, id).Scan(&trip)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return build.ErrNotFound
+ }
+ if err != nil {
+ return fmt.Errorf("read trip: %w", err)
+ }
+ rows, err := tx.Query(ctx, `
+ SELECT id, trip, day::text, category, amount, currency, paid_by, micros, base
+ FROM expenses WHERE owner = $1 AND trip = $2`, owner, id)
+ if err != nil {
+ return fmt.Errorf("read expenses: %w", err)
+ }
+ expenses, err = pgx.CollectRows(rows, func(row pgx.CollectableRow) (build.Expense, error) {
+ var e build.Expense
+ err := row.Scan(&e.ID, &e.Trip, &e.Date, &e.Category, &e.Amount, &e.Currency, &e.PaidBy, &e.Micros, &e.Base)
+ return e, err
+ })
+ if err != nil {
+ return fmt.Errorf("read expenses: %w", err)
+ }
+ return nil
+ })
+ return trip, expenses, err
+ }server: wraps the build's handlernew file, +50
+ package prod
+
+ import (
+ "context"
+ _ "embed"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
+ "github.com/rudrite/system-design/arena/exercises/travel/build"
+ "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+idempotent.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 << 16
+
+ // Handler serves the API behind auth, plus the two routes an operator needs. The build's handler
+ // runs unchanged inside the wrappers.
+ func Handler(pool *pgxpool.Pool, tokens kv.Tokens, metrics *kv.Metrics) http.Handler {
+ api := build.Handler(build.NewService(NewPGStore(pool)))
+ retries := idempotent.Wrap(pool, kv.OwnerFrom, api)
+
+ mux := http.NewServeMux()
+ mux.Handle("/", metrics.Wrap(kv.Auth(tokens, http.MaxBytesHandler(retries, 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
+ }idempotent: safe retriesnew file, +141
+ // Package idempotent makes a POST safe to retry. A request with an Idempotency-Key header runs in
+ // one database transaction with the row that claims the key, so the work and the saved response
+ // land together or not at all. A retry gets the saved response and does no work.
+ package idempotent
+
+ import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+ )
+
+ // Schema is the table Wrap needs.
+ const Schema = `
+ CREATE TABLE IF NOT EXISTS idempotency_keys (
+ owner text NOT NULL,
+ key text NOT NULL,
+ request bytea NOT NULL,
+ status int,
+ body bytea,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (owner, key)
+ );`
+
+ type txKey struct{}
+
+ // Tx returns the database transaction a request runs in, if it has one.
+ func Tx(ctx context.Context) (pgx.Tx, bool) {
+ tx, ok := ctx.Value(txKey{}).(pgx.Tx)
+ return tx, ok
+ }
+
+ // errRetry rolls the transaction back, so the key stays free and a retry does the work.
+ var errRetry = errors.New("server error")
+
+ // response holds what the handler wrote until the transaction ends.
+ type response struct {
+ header http.Header
+ status int
+ body bytes.Buffer
+ }
+
+ func (r *response) Header() http.Header { return r.header }
+ func (r *response) WriteHeader(status int) { r.status = status }
+ func (r *response) Write(b []byte) (int, error) { return r.body.Write(b) }
+
+ func (r *response) send(w http.ResponseWriter) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(r.status)
+ if _, err := w.Write(r.body.Bytes()); err != nil {
+ log.Print(err)
+ }
+ }
+
+ func refuse(w http.ResponseWriter, status int, message string) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ if _, err := fmt.Fprintf(w, `{"error":%q}`, message); err != nil {
+ log.Print(err)
+ }
+ }
+
+ // Wrap runs each POST that has a key once per owner. A second POST with the key gets the first
+ // response. A POST with the key and a different body gets 422, as the IETF draft for the header
+ // suggests. The draft's 409 for a request still in flight never applies here: that request waits
+ // for the first one, then gets one of these two answers. Other requests pass through.
+ func Wrap(pool *pgxpool.Pool, owner func(context.Context) string, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ key := r.Header.Get("Idempotency-Key")
+ if key == "" || r.Method != http.MethodPost {
+ next.ServeHTTP(w, r)
+ return
+ }
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ refuse(w, http.StatusBadRequest, "invalid: request body")
+ return
+ }
+ // The path is part of the fingerprint: one key must not cover two different routes.
+ request := sha256.Sum256(append([]byte(r.URL.Path+"\n"), body...))
+ r.Body = io.NopCloser(bytes.NewReader(body))
+
+ ctx := r.Context()
+ who := owner(ctx)
+ out := &response{header: http.Header{}, status: http.StatusOK}
+ err = pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
+ // A parallel request with this key waits here until the first one commits.
+ tag, err := tx.Exec(ctx, `
+ INSERT INTO idempotency_keys (owner, key, request) VALUES ($1, $2, $3)
+ ON CONFLICT DO NOTHING`, who, key, request[:])
+ if err != nil {
+ return fmt.Errorf("claim key: %w", err)
+ }
+ if tag.RowsAffected() == 0 {
+ return replay(ctx, tx, who, key, request[:], out)
+ }
+ next.ServeHTTP(out, r.WithContext(context.WithValue(ctx, txKey{}, tx)))
+ if out.status >= http.StatusInternalServerError {
+ return errRetry
+ }
+ _, err = tx.Exec(ctx, `UPDATE idempotency_keys SET status = $3, body = $4 WHERE owner = $1 AND key = $2`,
+ who, key, out.status, out.body.Bytes())
+ if err != nil {
+ return fmt.Errorf("save response: %w", err)
+ }
+ return nil
+ })
+ if err != nil && !errors.Is(err, errRetry) {
+ log.Print(err)
+ refuse(w, http.StatusInternalServerError, "internal error")
+ return
+ }
+ out.send(w)
+ })
+ }
+
+ func replay(ctx context.Context, tx pgx.Tx, who, key string, request []byte, out *response) error {
+ var (
+ saved []byte
+ body []byte
+ )
+ err := tx.QueryRow(ctx, `SELECT request, status, body FROM idempotency_keys WHERE owner = $1 AND key = $2`,
+ who, key).Scan(&saved, &out.status, &body)
+ if err != nil {
+ return fmt.Errorf("read saved response: %w", err)
+ }
+ if !bytes.Equal(saved, request) {
+ out.status = http.StatusUnprocessableEntity
+ out.body.WriteString(`{"error":"conflict: this key was used with a different request"}` + "\n")
+ return nil
+ }
+ out.body.Write(body)
+ return nil
+ }The diff is one changed file and a few new ones. That is what the store interface in the build was for.
0 of 12 known
A rate is 1.005 and the amount is 1.00. What does float64 give, and what is correct?
Why does the rate come in as an integer number of micros?
Why divide by 100 for euros but by 1 for yen?
Three expenses each convert to 0.5 cents. Is the trip worth 1, 2 or 3 cents?
Why compute the base when the expense is recorded and not in the summary?
amount times micros times 100 can reach what size?
AddExpense reads a rate and then writes the expense, with no lock over both. Why is that safe?
One day has 80 paid by the employee and 80 on the company card. The per diem is 100. Which expense gets the allowance?
Why are parallel adds not a check-then-act race here, when a trip limit in a rules engine is?
In production, the rate upsert has DO UPDATE SET micros = rates.micros. Why write a value over itself?
In production, why does the expense insert read from trips and not rely on the foreign key?
In production, one key arrives with a different body. What is the answer?
- build
- 443 lines with tests, 19:48 of typing at 100 words a minute.
- checks
- 44 grader checks, in 4 groups.
- rounding
- Half up. Once per expense, and once per category for a percent.
- float
- 7 of 100 ties go the wrong way (tested).
- largest
- 10^10 minor units at 1,000 dollars is 10^15 cents.
- headroom
- 9,223 of those fit in int64 (derived).
- race
- 100 parallel adds of 1 to 100 cents: exactly 5,050.
Design values from the tested code, not load measurements.