Wallet transfers
Move money between accounts, with no negative balance and no double spend. The sums are simple. The test is two opposite transfers at once, and a client that retries.
- 1Lock two accounts in id order. A waiter then holds nothing, so a cycle cannot form.
- 2A retry with the same key returns the first transfer. A refusal records nothing.
- 3A deposit is a transfer from a world account, so there is one money path and every balance sums to 0.
- 4Production writes a double-entry ledger, and the database refuses an overdraft or an unbalanced entry.
Build a wallet as an HTTP API, in memory. Clients create accounts, deposit, transfer between accounts, read a balance and list a statement with cursor pagination. A balance can never go below zero. A client may retry a transfer with the same idempotency key, and the money moves once. Many clients call the service at once, so make it safe.
| ask | answer assumed |
|---|---|
| What unit is money? | Whole cents, 1 to 1,000,000,000,000 per move. |
| Is the key required? | Yes, on every deposit and transfer. |
| What does a retry return? | The first transfer, with its ID and the same 201. |
| One key, a different transfer? | 409 in the build, to keep the error map small. Production answers 422. |
| After a refusal, can the key try again? | Yes. A refusal records nothing. |
| Statement order? | Newest first, up to 100 entries a page. |
Before I type, I confirm that money is whole cents, that a retry carries a key, and what a refused transfer does to that key.
| request | success | errors |
|---|---|---|
| POST /accounts | 201 id, balance | |
| GET /accounts/{id} | 200 id, balance | 404 |
| POST /accounts/{id}/deposit | 201 transfer | 400, 404, 409 |
| POST /transfers | 201 transfer | 400, 404, 409 |
| GET /accounts/{id}/statement | 200 entries, next_cursor | 400, 404 |
- POST /transfers takes from, to, amount and idempotency_key. A deposit takes the last two.
- A statement takes limit and cursor. An empty next_cursor means the last page.
- An entry has seq, transfer, other, a signed amount, and the balance after it.
- One key on a different transfer is 409 in the build and 422 in production. The grader accepts either, and it checks that no money moved.
Deposit and transfer take one body shape and return one shape, because they share one path.
| by | build | proof | if you are late |
|---|---|---|---|
| 15 min | The kit, renamed. Accounts, balance, and a transfer with the funds check. | TestTransfer | Skip the amount limit. Add it in the last 5 minutes. |
| 30 min | Deposit as a transfer from world. Idempotency keys. Two locks in id order. | TestRetryMovesMoneyOnce, TestOppositeTransfers | Use one global mutex. It is correct, and the lock order becomes a sentence in the talk. |
| 45 min | Entries on each account. The statement with a cursor. | TestStatementPages | Return every entry, and say how the cursor would work. |
I keep a running service at each checkpoint. If I am late at 30 minutes, I skip the statement and describe the cursor.
The deadlock needs a cycle. If every transfer locks the lower id first, whoever waits holds nothing, so no cycle can form.
| part | value |
|---|---|
| Lines, with tests | 450 |
| Typed characters | 9,978 |
| Typing at 500 a minute | 19:57 |
| Typing at 300 a minute | 33:16 |
| Left for thinking, at 500 a minute | 25:03 |
| 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 |
|---|---|
| Lock two accounts in id order | Approved |
| Whole cents in an int64 | Approved |
| One path for deposits and transfers | Approved |
| Lock the source first, then the destination | Not approved |
| Check the funds, release the lock, then write | Not approved |
| Floats for money | Not approved |
| Offsets for a statement that is newest first | 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"
"slices"
"sync"
)
var (
ErrInvalid = errors.New("invalid")
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
)
// World is the outside of the wallet: every deposit is a transfer from it, and only it can go
// below zero. All balances, World included, always sum to 0.
const World = "world"1
// Transfer moves Amount cents. Key makes a retry safe.
type Transfer struct {
ID string `json:"id"`
Key string `json:"idempotency_key"`
From string `json:"from"`
To string `json:"to"`
Amount int64 `json:"amount"`
}
// Entry is one line of a statement. Seq counts an account's entries from 1, and an entry never
// moves, so a seq is a stable cursor.
type Entry struct {
Seq int64 `json:"seq"`
Transfer string `json:"transfer"`
Other string `json:"other"`
Amount int64 `json:"amount"`
Balance int64 `json:"balance"`
}
type Store interface {
AddAccount(ctx context.Context, id string) error
Balance(ctx context.Context, id string) (int64, error)
// Transfer moves the money once per key: a retry returns the first transfer. A refused
// transfer records nothing, so its key can try again.
Transfer(ctx context.Context, t Transfer) (Transfer, error)
// Statement returns up to limit entries, newest first, with Seq below before. Zero means
// from the newest entry.
Statement(ctx context.Context, id string, before int64, limit int) ([]Entry, error)
}
type account struct {
mu sync.Mutex
balance int64
entries []Entry
}
func (a *account) post(transfer, other string, amount int64) {
a.balance += amount
a.entries = append(a.entries, Entry{int64(len(a.entries)) + 1, transfer, other, amount, a.balance})
}
type MemStore struct {
mu sync.RWMutex // guards the two maps; never held while an account lock is awaited
accounts map[string]*account
keys map[string]Transfer
}
func NewMemStore() *MemStore {
return &MemStore{accounts: map[string]*account{World: {}}, keys: map[string]Transfer{}}
}
func (s *MemStore) AddAccount(_ context.Context, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
s.accounts[id] = &account{}
return nil
}
func (s *MemStore) find(id string) (*account, error) {
s.mu.RLock()
defer s.mu.RUnlock()
a, ok := s.accounts[id]
if !ok {
return nil, fmt.Errorf("%w: account %s", ErrNotFound, id)
}
return a, nil
}
func (s *MemStore) Balance(_ context.Context, id string) (int64, error) {
a, err := s.find(id)
if err != nil {
return 0, err
}
a.mu.Lock()
defer a.mu.Unlock()
return a.balance, nil
}
func (s *MemStore) Transfer(_ context.Context, t Transfer) (Transfer, error) {
from, err := s.find(t.From)
if err != nil {
return Transfer{}, err
}
to, err := s.find(t.To)
if err != nil {
return Transfer{}, err
}
first, second := from, to
if t.To < t.From {2
first, second = to, from
}
first.mu.Lock()
defer first.mu.Unlock()
second.mu.Lock()
defer second.mu.Unlock()
funded := t.From == World || from.balance >= t.Amount3
s.mu.Lock()
prior, seen := s.keys[t.Key]
if !seen && funded {4
s.keys[t.Key] = t
}
s.mu.Unlock()
if seen {
t.ID = prior.ID5
if t != prior {
return Transfer{}, fmt.Errorf("%w: key used for a different transfer", ErrConflict)
}
return prior, nil
}
if !funded {
return Transfer{}, fmt.Errorf("%w: insufficient funds", ErrConflict)
}
from.post(t.ID, t.To, -t.Amount)
to.post(t.ID, t.From, t.Amount)
return t, nil
}
func (s *MemStore) Statement(_ context.Context, id string, before int64, limit int) ([]Entry, error) {
a, err := s.find(id)
if err != nil {
return nil, err
}
a.mu.Lock()
defer a.mu.Unlock()
end := int64(len(a.entries))
if before > 0 {6
end = min(end, before-1)
}
page := append([]Entry{}, a.entries[max(0, end-int64(limit)):end]...)
slices.Reverse(page)
return page, nil
}
- 1The outside of the wallet. It can go below zero, so all balances sum to 0, and that gives a simple audit.
- 2The fixed order. Opposite transfers take the same lock first, so neither can hold what the other needs.
- 3Read under both locks, so no other transfer can spend this money before the write.
- 4A refusal claims nothing, so the same key can try again after a deposit.
- 5Each attempt gets a new ID. Copy the first one, so the comparison covers only what the client sent.
- 6Seq counts from 1, so the entry with seq n sits at index n-1. Entries before the cursor end at before-1.
Transfer is the only write path. It takes both locks in id order, then decides on the key and the funds, then moves the money.
package build
import (
"cmp"
"context"
"crypto/rand"
"fmt"
"strconv"
)
const (
maxAmount = 1_000_000_000_000
maxLimit = 100
)
type Service struct {
store Store
}
func NewService(store Store) *Service {
return &Service{store: store}
}
func (s *Service) Open(ctx context.Context) (string, error) {
id := rand.Text()
return id, s.store.AddAccount(ctx, id)
}
func (s *Service) Balance(ctx context.Context, id string) (int64, error) {
if id == World {
return 0, ErrNotFound
}
return s.store.Balance(ctx, id)
}
func (s *Service) Deposit(ctx context.Context, id string, amount int64, key string) (Transfer, error) {
if id == World {
return Transfer{}, ErrNotFound
}
return s.move(ctx, Transfer{Key: key, From: World, To: id, Amount: amount})1
}
func (s *Service) Transfer(ctx context.Context, from, to string, amount int64, key string) (Transfer, error) {
if from == World || to == World {
return Transfer{}, ErrNotFound
}
if from == to {2
return Transfer{}, fmt.Errorf("%w: from and to are the same account", ErrInvalid)
}
return s.move(ctx, Transfer{Key: key, From: from, To: to, Amount: amount})
}
func (s *Service) move(ctx context.Context, t Transfer) (Transfer, error) {
if t.Key == "" {
return Transfer{}, fmt.Errorf("%w: idempotency_key is required", ErrInvalid)
}
if t.Amount < 1 || t.Amount > maxAmount {
return Transfer{}, fmt.Errorf("%w: amount must be 1 to %d cents", ErrInvalid, int64(maxAmount))
}
t.ID = rand.Text()
return s.store.Transfer(ctx, t)
}
// Statement returns one page and the cursor of the next. The cursor is empty on the last page.
func (s *Service) Statement(ctx context.Context, id, cursor, limit string) ([]Entry, string, error) {
if id == World {
return nil, "", ErrNotFound
}
n, err := strconv.Atoi(cmp.Or(limit, "20"))
if err != nil || n < 1 || n > maxLimit {
return nil, "", fmt.Errorf("%w: limit must be 1 to %d", ErrInvalid, maxLimit)
}
before, err := strconv.ParseInt(cmp.Or(cursor, "0"), 10, 64)
if err != nil || before < 0 {
return nil, "", fmt.Errorf("%w: bad cursor", ErrInvalid)
}
page, err := s.store.Statement(ctx, id, before, n)
if err != nil {
return nil, "", err
}
next := ""
if len(page) == n && page[n-1].Seq > 1 {3
next = strconv.FormatInt(page[n-1].Seq, 10)
}
return page, next, nil
}
- 1A deposit is a transfer from world. It has no second code path to get wrong.
- 2A transfer to the same account would lock one mutex twice and hang, so it stops here.
- 3A short page, or a page that reached seq 1, is the last. No cursor, so no empty page.
The service checks the input and hides the world account. Deposit and transfer become one Transfer value.
package build
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
)
type balance struct {
ID string `json:"id"`
Balance int64 `json:"balance"`
}
type moveBody struct {
From, To string
Amount int64
Key string `json:"idempotency_key"`1
}
func Handler(svc *Service) http.Handler {
mux := http.NewServeMux()
mux.Handle("POST /accounts", route(201, func(r *http.Request) (any, error) {
id, err := svc.Open(r.Context())
return balance{ID: id}, err
}))
mux.Handle("GET /accounts/{id}", route(200, func(r *http.Request) (any, error) {
id := r.PathValue("id")
cents, err := svc.Balance(r.Context(), id)
return balance{id, cents}, err
}))
mux.Handle("POST /accounts/{id}/deposit", route(201, func(r *http.Request) (any, error) {
var body moveBody
if err := readJSON(r, &body); err != nil {
return nil, err
}
return svc.Deposit(r.Context(), r.PathValue("id"), body.Amount, body.Key)
}))
mux.Handle("GET /accounts/{id}/statement", route(200, func(r *http.Request) (any, error) {
q := r.URL.Query()2
entries, next, err := svc.Statement(r.Context(), r.PathValue("id"), q.Get("cursor"), q.Get("limit"))
return map[string]any{"entries": entries, "next_cursor": next}, err
}))
mux.Handle("POST /transfers", route(201, func(r *http.Request) (any, error) {
var body moveBody
if err := readJSON(r, &body); err != nil {
return nil, err
}
return svc.Transfer(r.Context(), body.From, body.To, body.Amount, body.Key)
}))
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()}
}
- 1In the body, not a header, so the grader needs no custom header. Production could take either.
- 2Limit and cursor arrive as strings, and the service validates both.
// Command main serves the 45-minute wallet.
package main
import (
"log"
"net/http"
"github.com/rudrite/system-design/arena/exercises/wallet/build"
)
func main() {
svc := build.NewService(build.NewMemStore())
handler := build.Handler(svc)
log.Fatal(http.ListenAndServe(":8080", handler))
}
Deposit and transfer decode one body type. The handler only moves values between HTTP and the service.
package build
import (
"fmt"
"net/http"
"net/http/httptest"
"regexp"
"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 open(h http.Handler, cents int) string {
_, body := do(h, "POST", "/accounts", "")
id := regexp.MustCompile(`[A-Z0-9]{26}`).FindString(body)
do(h, "POST", "/accounts/"+id+"/deposit", fmt.Sprintf(`{"amount":%d,"idempotency_key":"open-%s"}`, cents, id))
return id
}
func move(from, to string, cents int, key string) string {
return fmt.Sprintf(`{"from":"%s","to":"%s","amount":%d,"idempotency_key":"%s"}`, from, to, cents, key)
}
func newHandler() http.Handler {
return Handler(NewService(NewMemStore()))
}
func TestTransfer(t *testing.T) {
h := newHandler()
a, b := open(h, 100), open(h, 0)
run(t, h, []step{
{"POST", "/transfers", move(a, b, 30, "k1"), 201, `"amount":30`},
{"GET", "/accounts/" + a, "", 200, `"balance":70`},
{"GET", "/accounts/" + b, "", 200, `"balance":30`},
{"POST", "/transfers", move(a, b, 71, "k2"), 409, "insufficient"},
{"POST", "/transfers", move(a, a, 1, "k3"), 400, "same account"},
{"POST", "/transfers", move(a, "nope", 1, "k5"), 404, "not found"},
})
}
func TestRetryMovesMoneyOnce(t *testing.T) {
h := newHandler()
a, b := open(h, 100), open(h, 0)
_, first := do(h, "POST", "/transfers", move(a, b, 30, "k1"))
run(t, h, []step{
{"POST", "/transfers", move(a, b, 30, "k1"), 201, first[:40]1},
{"GET", "/accounts/" + a, "", 200, `"balance":70`},
{"POST", "/transfers", move(a, b, 31, "k1"), 409, "different transfer"},
})
}
func TestStatementPages(t *testing.T) {
h := newHandler()
a, b := open(h, 100), open(h, 0)
do(h, "POST", "/transfers", move(a, b, 30, "k1"))
do(h, "POST", "/transfers", move(a, b, 20, "k2"))
path := "/accounts/" + a + "/statement"
run(t, h, []step{
{"GET", path + "?limit=2", "", 200, `"next_cursor":"2"`},
{"GET", path + "?limit=2&cursor=2", "", 200, `"next_cursor":""`},2
})
}
func TestOppositeTransfers(t *testing.T) {
h := newHandler()
a, b := open(h, 1000), open(h, 1000)
var wg sync.WaitGroup
for i := range 100 {
wg.Go(func() {
from, to := a, b
if i%2 == 1 {
from, to = b, a
}
do(h, "POST", "/transfers", move(from, to, 1, fmt.Sprint(i)))
})
}
wg.Wait()3
run(t, h, []step{
{"GET", "/accounts/" + a, "", 200, `"balance":1000`},
{"GET", "/accounts/" + b, "", 200, `"balance":1000`},
})
}
- 1The start of the body holds the ID, so a retry must return the first transfer.
- 2Three entries, two pages. The second page is the last.
- 3Run with -race. A deadlock hangs here until go test stops the run.
Each test is a list of steps, so a new behaviour is one row. The race test sends opposite transfers.
arena run wallet --base http://localhost:8080
correctness
PASS a new account holds 0
PASS a deposit adds to the balance
PASS a transfer moves the amount
PASS a transfer can empty an account
PASS a retried transfer moves the money once
PASS a retried deposit adds the money once
PASS a refused transfer moves nothing and its key can try again
PASS a statement lists entries newest first
PASS a cursor walks every entry once
PASS a deposit between pages moves no entry
status codes
PASS open is 201 and returns an id
PASS transfer is 201 and returns an id
PASS an unknown account is 404
PASS more than the balance is 409
PASS one key on a different transfer is 409 or 422
validation
PASS malformed JSON is 400
PASS an amount of 0 or less is 400
PASS an amount over the limit is 400
PASS an amount that is not a whole number is 400
PASS a missing key is 400
PASS a transfer to the same account is 400
PASS a bad limit is 400
PASS a bad cursor is 400
concurrency
PASS 100 parallel deposits: none is lost
PASS 100 parallel transfers cannot overdraw an account
PASS 100 parallel opposite transfers finish and conserve the total
PASS 100 parallel transfers around a ring conserve the total
PASS 100 parallel copies of one transfer move the money once
PASS after 100 parallel transfers each statement adds up to its balance
29 checks: 29 passed, 0 failedAll checks pass, with 100 opposite transfers and 100 copies of one key.
{Name: "100 parallel opposite transfers finish and conserve the total", Group: grader.Concurrency, Run: func(t *grader.T) {
a, b := open(t, 1000), open(t, 1000)
t.Parallel(parallel, func(i int) {
from, to := a, b
if i%2 == 1 {
from, to = b, a
}
t.Status(transfer(t, from, to, 7, t.Key("k"+strconv.Itoa(i))), 201)
})
wantBalance(t, a, 1000)
wantBalance(t, b, 1000)
}},{Name: "100 parallel copies of one transfer move the money once", Group: grader.Concurrency, Run: func(t *grader.T) {
a, b := open(t, 100), open(t, 0)
key := t.Key("k")
ids := make([]string, parallel)
t.Parallel(parallel, func(i int) {
x := transfer(t, a, b, 30, key)
t.Status(x, 201)
ids[i] = t.Field(x, "id")
})
if len(slices.Compact(ids)) != 1 {
t.Failf("copies of one transfer returned different ids")
}
wantBalance(t, a, 70)
wantBalance(t, b, 30)
}},A server that locks the source first. Requests time out, and the grader reports the checks that hung.
FAIL 100 parallel opposite transfers finish and conserve the total
FAIL 100 parallel transfers around a ring conserve the total
FAIL after 100 parallel transfers each statement adds up to its balance
29 checks: 26 passed, 3 failedA deadlock gives no wrong answer. It gives no answer. So the grader bounds each check with a timeout, and a hang is a failure.
| the interviewer asks | the answer | goes deeper |
|---|---|---|
| Why two tables of entries and not one balance column? | A balance says how much, not why. In double entry, every movement is one journal entry with postings that sum to 0, so money can only move and never appear. The balance becomes a cached sum you can check. | T9 Exactly-once |
| Run two instances. What breaks? | Each mutex covers one process, so both instances can spend one balance. The row lock replaces the mutex, and the unique index replaces the key map. Both work across instances. | T5 Concurrency control |
| Row locks, or an optimistic version check? | Row locks for money. A busy account conflicts on nearly every attempt, so optimistic retries waste the work. A lock queue is the cheaper order, and locks in id order cannot deadlock. | T5 Concurrency control |
| Two copies of one transfer arrive at the same moment. | Both insert the key. The second waits on the unique index until the first ends. If the first commits, the second finds the key and returns the same transfer. If it rolls back, the second goes on. | T9 Exactly-once |
| What if the key is saved in a separate step? | A crash between the two steps either loses the key, so a retry moves money twice, or saves it with no money moved. The claim and the postings must share one transaction. | T9 Exactly-once |
| What stops an overdraft if the code has a bug? | A CHECK constraint on the account row. The code does not compare balances at all in production: it subtracts, and the database refuses a negative result. The rule holds for every writer. | T9 Exactly-once |
| Why a cursor and not an offset? | A statement is newest first, so a new entry shifts every offset, and page 2 repeats a row. A cursor continues below the last seq the client saw. Each page is also an index seek, not a scan. | R3 Requirements to API |
| Which status code for a reused key, or for no funds? | No funds is 409 in both versions. For a reused key, the build answers 409 to keep the error map small. Production answers 422, as the IETF draft for the header suggests. A copy sent while the first request runs waits for it, so neither version needs the 409 that the draft gives that case. | R3 Requirements to API |
| One merchant receives most of the transfers. | One account is one row, so its lock is a queue, and shards do not help. Split it into sub-accounts and sum them for the balance. The world account here avoids the queue by keeping no cached balance. | C20 Digital wallet |
| The two accounts live on different shards. | One transaction no longer covers both. Use a saga: place a hold on the source, credit the destination, then capture the hold. Each step has a key, and a row on the source shard lets recovery finish. | C20 Digital wallet |
| How do you prove the balances are right? | Run an audit: all postings sum to 0, each entry sums to 0, and each cached balance equals the sum of its postings. The tests run this audit after the grader finishes. In production, schedule it to run every night. | C20 Digital wallet |
| Who may move money? | Only the owner of the source account, and anyone may pay into an account. Another owner gets 404 and not 403, so an ID reveals nothing. Real deposits come from a payment callback, not from a client. | O5 Security |
I start from what the build lacks: durability, an audit trail, then two instances. I name each limit before the interviewer does.
Instances hold no state. The account row replaces the mutex, and the unique index replaces the key map.
| tool | build | production |
|---|---|---|
| Postgres | Two mutexes in id order | Row locks with ORDER BY id |
| Postgres | A key map | A unique index, claimed with the postings |
| Postgres | A funds check in code | A CHECK constraint |
| Postgres | An entry slice per account | Journal entries and postings; a trigger checks each sum |
| Service | 409 for a reused key | 422 for a reused key; no funds stays 409 |
| Service | No auth | Bearer tokens; each account has an owner |
| Service | ListenAndServe | Timeouts, a body limit, metrics, drain on SIGTERM |
Tested: production passes the same 29 grader checks, then a ledger audit finds every count at 0. 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 wallet. It reads DATABASE_URL, API_TOKENS
+ // (owner:token,owner:token) and ADDR, which defaults to :8080.
- // Command main serves the 45-minute wallet.
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/wallet/prod"
- "github.com/rudrite/system-design/arena/exercises/wallet/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))
}-- Money is a whole number of cents. No floats anywhere.
CREATE TABLE IF NOT EXISTS accounts (
id text PRIMARY KEY,
owner text NOT NULL,
allow_negative boolean NOT NULL DEFAULT false,
balance bigint NOT NULL DEFAULT 0, -- cached: the sum of this account's postings
entries bigint NOT NULL DEFAULT 0, -- the seq of the newest posting
CONSTRAINT no_overdraft CHECK (allow_negative OR balance >= 0)
);
-- The outside of the wallet. It never locks and keeps no cached balance: the sum of its postings
-- is the figure, so deposits do not queue on one row.
INSERT INTO accounts (id, owner, allow_negative) VALUES ('world', '', true) ON CONFLICT DO NOTHING;
-- One row per money movement. The key makes a retried request safe.
CREATE TABLE IF NOT EXISTS journal_entries (
id text PRIMARY KEY,
owner text NOT NULL,
idempotency_key text NOT NULL,
from_id text NOT NULL,
to_id text NOT NULL,
amount bigint NOT NULL CHECK (amount > 0),
UNIQUE (owner, idempotency_key)
);
-- Each entry has two postings. A posting adds its amount to one account. seq is 0 for world.
CREATE TABLE IF NOT EXISTS postings (
entry_id text NOT NULL REFERENCES journal_entries (id),
account_id text NOT NULL REFERENCES accounts (id),
seq bigint NOT NULL,
other text NOT NULL,
amount bigint NOT NULL CHECK (amount <> 0),
balance bigint NOT NULL, -- the account's balance after this posting
PRIMARY KEY (entry_id, account_id)
);
CREATE UNIQUE INDEX IF NOT EXISTS postings_statement ON postings (account_id, seq) WHERE account_id <> 'world';-- Every entry balances: its postings sum to zero. Checked at commit.
CREATE OR REPLACE FUNCTION entry_balances() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF (SELECT sum(amount) FROM postings WHERE entry_id = NEW.entry_id) <> 0 THEN
RAISE EXCEPTION 'entry % does not balance', NEW.entry_id USING ERRCODE = 'check_violation';
END IF;
RETURN NULL;
END $$;
DROP TRIGGER IF EXISTS entry_balances ON postings;
CREATE CONSTRAINT TRIGGER entry_balances AFTER INSERT ON postings
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION entry_balances();pgstore: implements Storenew file, +192
+ // Package prod is the wallet made production grade. It imports the 45-minute build and replaces
+ // the in-memory store with a double-entry ledger behind its interface, then adds auth, metrics and
+ // health. The service and the handler do not change.
+ package prod
+
+ import (
+ "context"
+ "errors"
+ "fmt"
+ "slices"
+
+ "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/wallet/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}
+ }
+
+ // AddAccount opens an account owned by the caller.
+ func (s *PGStore) AddAccount(ctx context.Context, id string) error {
+ _, err := s.pool.Exec(ctx, `INSERT INTO accounts (id, owner) VALUES ($1, $2)`, id, kv.OwnerFrom(ctx))
+ if err != nil {
+ return fmt.Errorf("add account: %w", err)
+ }
+ return nil
+ }
+
+ // Balance reads the cached balance. A plain read waits for no writer.
+ func (s *PGStore) Balance(ctx context.Context, id string) (int64, error) {
+ var cents int64
+ err := s.pool.QueryRow(ctx, `SELECT balance FROM accounts WHERE id = $1 AND owner = $2`,
+ id, kv.OwnerFrom(ctx)).Scan(¢s)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return 0, build.ErrNotFound
+ }
+ if err != nil {
+ return 0, fmt.Errorf("read balance: %w", err)
+ }
+ return cents, nil
+ }
+
+ const (
+ // A copy of the same request waits on the unique key until the first one ends.
+ claim = `
+ INSERT INTO journal_entries (id, owner, idempotency_key, from_id, to_id, amount)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (owner, idempotency_key) DO NOTHING`
+
+ findEntry = `
+ SELECT id, from_id, to_id, amount FROM journal_entries WHERE owner = $1 AND idempotency_key = $2`
+
+ // Every transfer locks in id order, so two transfers can never wait for each other. World is
+ // left out: it has no balance to protect, and locking it would queue every deposit on one row.
+ lockAccounts = `
+ SELECT id, owner FROM accounts WHERE id = ANY($1) AND id <> 'world' ORDER BY id FOR UPDATE`
+
+ // The no_overdraft CHECK refuses a balance below zero.
+ apply = `
+ UPDATE accounts SET balance = balance + $2, entries = entries + 1 WHERE id = $1
+ RETURNING entries, balance`
+
+ post = `
+ INSERT INTO postings (entry_id, account_id, seq, other, amount, balance)
+ VALUES ($1, $2, $3, $4, $5, $6)`
+ )
+
+ // Transfer writes the entry, its two postings and the cached balances in one transaction. The
+ // claim on the key rolls back with a refusal, so a refused transfer can try again.
+ func (s *PGStore) Transfer(ctx context.Context, t build.Transfer) (build.Transfer, error) {
+ owner := kv.OwnerFrom(ctx)
+ err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
+ tag, err := tx.Exec(ctx, claim, t.ID, owner, t.Key, t.From, t.To, t.Amount)
+ if err != nil {
+ return fmt.Errorf("claim key: %w", err)
+ }
+ if tag.RowsAffected() == 0 {
+ t, err = replay(ctx, tx, owner, t)
+ return err
+ }
+ if err := lock(ctx, tx, owner, t); err != nil {
+ return err
+ }
+ if err := move(ctx, tx, t.ID, t.From, t.To, -t.Amount); err != nil {
+ return err
+ }
+ return move(ctx, tx, t.ID, t.To, t.From, t.Amount)
+ })
+ var pgErr *pgconn.PgError
+ if errors.As(err, &pgErr) && pgErr.ConstraintName == "no_overdraft" {
+ return build.Transfer{}, fmt.Errorf("%w: insufficient funds", build.ErrConflict)
+ }
+ if err != nil {
+ return build.Transfer{}, err
+ }
+ return t, nil
+ }
+
+ // replay returns the transfer an earlier request made with this key. The same key on a different
+ // transfer is a client bug, and it must not return the wrong answer.
+ func replay(ctx context.Context, tx pgx.Tx, owner string, t build.Transfer) (build.Transfer, error) {
+ prior := build.Transfer{Key: t.Key}
+ err := tx.QueryRow(ctx, findEntry, owner, t.Key).Scan(&prior.ID, &prior.From, &prior.To, &prior.Amount)
+ if err != nil {
+ return build.Transfer{}, fmt.Errorf("read entry: %w", err)
+ }
+ t.ID = prior.ID
+ if t != prior {
+ idempotent.MarkReused(ctx)
+ return build.Transfer{}, fmt.Errorf("%w: key used for a different transfer", build.ErrConflict)
+ }
+ return prior, nil
+ }
+
+ // lock takes the row locks and checks who may move the money: the source must be the caller's,
+ // and the destination must exist. Another owner's account reads as missing.
+ func lock(ctx context.Context, tx pgx.Tx, owner string, t build.Transfer) error {
+ rows, err := tx.Query(ctx, lockAccounts, []string{t.From, t.To})
+ if err != nil {
+ return fmt.Errorf("lock accounts: %w", err)
+ }
+ owners := map[string]string{}
+ var id, holder string
+ if _, err := pgx.ForEachRow(rows, []any{&id, &holder}, func() error {
+ owners[id] = holder
+ return nil
+ }); err != nil {
+ return fmt.Errorf("lock accounts: %w", err)
+ }
+ for _, want := range []string{t.From, t.To} {
+ if _, found := owners[want]; !found && want != build.World {
+ return fmt.Errorf("%w: account %s", build.ErrNotFound, want)
+ }
+ }
+ // A deposit has no source account, so the destination is the account to check.
+ source := t.From
+ if source == build.World {
+ source = t.To
+ }
+ if owners[source] != owner {
+ return fmt.Errorf("%w: account %s", build.ErrNotFound, source)
+ }
+ return nil
+ }
+
+ // move posts one side of an entry. World keeps no cached balance and no statement.
+ func move(ctx context.Context, tx pgx.Tx, entry, account, other string, amount int64) error {
+ var seq, balance int64
+ if account != build.World {
+ if err := tx.QueryRow(ctx, apply, account, amount).Scan(&seq, &balance); err != nil {
+ return fmt.Errorf("apply to %s: %w", account, err)
+ }
+ }
+ if _, err := tx.Exec(ctx, post, entry, account, seq, other, amount, balance); err != nil {
+ return fmt.Errorf("post to %s: %w", account, err)
+ }
+ return nil
+ }
+
+ const statement = `
+ SELECT seq, entry_id, other, amount, balance FROM postings
+ WHERE account_id = $1 AND ($2 = 0 OR seq < $2)
+ ORDER BY seq DESC
+ LIMIT $3`
+
+ // Statement checks the owner, then reads one page. The index on (account_id, seq) serves it, and
+ // a seq never changes, so a page does not move when new entries arrive.
+ func (s *PGStore) Statement(ctx context.Context, id string, before int64, limit int) ([]build.Entry, error) {
+ if _, err := s.Balance(ctx, id); err != nil {
+ return nil, err
+ }
+ rows, err := s.pool.Query(ctx, statement, id, before, limit)
+ if err != nil {
+ return nil, fmt.Errorf("read statement: %w", err)
+ }
+ entries, err := pgx.CollectRows(rows, pgx.RowToStructByPos[build.Entry])
+ if err != nil {
+ return nil, fmt.Errorf("read statement: %w", err)
+ }
+ return slices.Concat([]build.Entry{}, entries), nil
+ }server: auth and healthnew file, +49
+ 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/wallet/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); 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
+
+ // 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.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
Two transfers run at once, A to B and B to A. Each locks its source first. What happens?
Why is a transfer from an account to itself refused?
A transfer is refused for lack of funds. The client adds money and retries with the same key. What happens?
The same key arrives with a different amount. What should the server do?
Why does a deposit go through Transfer?
Why are amounts whole cents in an int64?
In the build, why does the key claim sit inside the two account locks?
A page ends exactly at the first entry. What is next_cursor?
In production, why does a deposit take no lock on the world account?
- build
- 450 lines with tests, 19:57 of typing at 100 words a minute.
- checks
- 29 grader checks, in 4 groups.
- race
- 100 opposite transfers finish, and the total does not change.
- retries
- 100 copies of one key move the money once.
- limits
- 100 entries a page. 1 MiB body in production.
Design values from the tested code, not load measurements.