Key-value store with nested transactions
Candidates report this question most often. The data structure takes minutes. The real test is what happens when two clients use it at once, and what you say in the talk that follows.
- 1A transaction is a stack of write layers. Reads walk down it. Only the outermost commit touches the store.
- 2Each transaction has its own ID, so two clients never share a stack.
- 3Commit checks the version of every key it read. A stale read gives 409, and the client starts again.
- 4Production swaps two interfaces. The service and the handler do not change.
Build a key-value store as an HTTP service, in memory. Clients can get, set and delete a key. Then add transactions: a client begins one, makes changes, and commits or rolls back. Transactions can nest. A rollback undoes only the current level. Nothing is visible to others until the outermost commit. Many clients call the service at once, so make it safe.
| ask | answer assumed |
|---|---|
| Can two clients have open transactions at once? | Yes. Each gets its own ID. |
| What does an inner commit do? | It merges one level down. Only depth 1 reaches the store. |
| Two transactions touch one key? | A stale read fails at commit with 409. Blind writes: the last commit wins. |
| After a conflict? | The transaction has ended. The client begins again. |
| Keys and values? | Strings. Keys up to 256 bytes. An empty value is valid. |
| Persistence? | Not in the build. It is the first topic of the talk. |
Before I type, I confirm that each client has its own transaction and that a conflict fails at commit.
| request | success | errors |
|---|---|---|
| GET /kv/{key} | 200 key, value | 404, 400 |
| PUT /kv/{key} | 200 key, value | 400 |
| DELETE /kv/{key} | 204 | 404, 400 |
| POST /tx | 201 id | |
| POST /tx/{id}/begin | 200 id | 404 |
| POST /tx/{id}/commit | 200 id | 404, 409 |
| POST /tx/{id}/rollback | 200 id | 404 |
| GET, PUT, DELETE /tx/{id}/kv/{key} | As above, inside the transaction | 404 |
- PUT has the body {"value":"..."}. A missing value is 400.
- The outermost commit or rollback ends the transaction. Its ID then gives 404.
Each key route has a twin under /tx/{id}, and they share one handler. Outside a transaction, the ID is empty.
| by | build | proof | if you are late |
|---|---|---|---|
| 15 min | The kit, renamed. Get, set and delete over MemStore. The error map. | TestKeys | Skip key length checks. Add them in the last 5 minutes. |
| 30 min | Tx with its layers. POST /tx, commit, rollback, then nested begin. Reads walk the stack. | TestNestedTransactions | Finish one level first. Nesting is then one more slice entry. |
| 45 min | Versions and the read check at commit. A mutex over the open transactions. Race test. | TestParallelIncrements | Keep the locks and say the check out loud: "reads hold versions, and commit compares them." |
I keep a running service at each checkpoint. If I am late at 30 minutes, I finish single-level transactions and describe nesting.
Each begin pushes a map of writes. A read checks those maps from the top down, then the store. Commit merges the top map down one level.
| part | value |
|---|---|
| Lines, with tests | 469 |
| Typed characters | 9,162 |
| Typing at 500 a minute | 18:19 |
| Typing at 300 a minute | 30:32 |
| Left for thinking, at 500 a minute | 26:41 |
| Dependencies | 0 |
- Build the two interfaces from the kit. They carry 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 transaction logic.
package build
import (
"context"
"errors"
"sync"
)
var (
ErrInvalid = errors.New("invalid")
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
)
// Entry is one stored value. Version changes on every write to the key.
type Entry struct {
Value string
Version int641
}
// Reads holds the version a transaction saw for each key it read. 0 means the key was absent.
type Reads map[string]int64
// Writes holds a transaction's new value for each key. nil means delete.
type Writes map[string]*string2
type Store interface {
Get(ctx context.Context, key string) (Entry, error)
// Apply makes all writes, or none: it returns ErrConflict if a read version is stale.
Apply(ctx context.Context, reads Reads, writes Writes) error3
}
type MemStore struct {
mu sync.RWMutex
entries map[string]Entry
version int64
}
func NewMemStore() *MemStore {
return &MemStore{entries: map[string]Entry{}}
}
func (s *MemStore) Get(_ context.Context, key string) (Entry, error) {
s.mu.RLock()
defer s.mu.RUnlock()
e, ok := s.entries[key]
if !ok {
return Entry{}, ErrNotFound
}
return e, nil
}
func (s *MemStore) Apply(_ context.Context, reads Reads, writes Writes) error {
s.mu.Lock()
defer s.mu.Unlock()
for key, seen := range reads {
if s.entries[key].Version != seen {4
return ErrConflict
}
}
for key, value := range writes {
if value == nil {
delete(s.entries, key)
continue
}
s.version++
s.entries[key] = Entry{Value: *value, Version: s.version}
}
return nil
}
- 1One counter gives every write a new version. It never goes back, so a key that is deleted and set again cannot look unchanged.
- 2A pointer, so nil can mean delete. An empty string is a real value.
- 3One method for plain writes and for commits. The Postgres store implements this same method.
- 4A missing key has version 0, so a read of an absent key is checked too. Two creators cannot both win.
Apply is the only write path. It checks every read version and makes every write under one lock, so a commit is atomic.
package build
import (
"context"
"crypto/rand"
"sync"
)
// Tx is one open transaction: a stack of write layers, one per begin, and every version it read.
// No layers left means the transaction has ended.
type Tx struct {
Reads Reads
Layers []Writes1
}
func NewTx() *Tx {
return &Tx{Reads: Reads{}, Layers: []Writes{{}}}
}
func (tx *Tx) top() Writes {
return tx.Layers[len(tx.Layers)-1]
}
func (tx *Tx) pop() Writes {
top := tx.top()
tx.Layers = tx.Layers[:len(tx.Layers)-1]
return top
}
type Sessions interface {
Create(ctx context.Context) (string, error)
// With runs fn alone on the open transaction id, or returns ErrNotFound. fn must use the
// context it receives: a store may run on the session's own database transaction.
With(ctx context.Context, id string, fn func(context.Context, *Tx) error) error2
}
type MemSessions struct {
mu sync.Mutex
open map[string]*Tx
}
func NewMemSessions() *MemSessions {
return &MemSessions{open: map[string]*Tx{}}
}
func (m *MemSessions) Create(context.Context) (string, error) {
m.mu.Lock()
defer m.mu.Unlock()
id := rand.Text()
m.open[id] = NewTx()
return id, nil
}
func (m *MemSessions) With(ctx context.Context, id string, fn func(context.Context, *Tx) error) error {
m.mu.Lock()
defer m.mu.Unlock()
tx, ok := m.open[id]
if !ok {
return ErrNotFound
}
err := fn(ctx, tx)
if len(tx.Layers) == 0 {
delete(m.open, id)4
}
return err
}
- 1One map per begin. No layers left means that the transaction has ended.
- 2Everything that touches a transaction goes through this method, so one lock covers all of it.
- 3The lock stays held for all of fn. Two requests on one transaction, or on two, run one at a time.
- 4A parallel commit that waited for the lock now finds no transaction, so exactly one commit wins.
One mutex covers all open transactions. That is coarse, but memory calls are fast, and it cannot deadlock. Production uses one row lock per transaction.
package build
import (
"context"
"errors"
"fmt"
"maps"
)
const maxKey = 256
type Service struct {
store Store
sessions Sessions
}
func NewService(store Store, sessions Sessions) *Service {
return &Service{store: store, sessions: sessions}
}
// do runs fn on transaction id. With no id, it runs fn in a one-level transaction of its own and
// commits at once, so plain requests and transactions share one code path.
func (s *Service) do(1ctx context.Context, id, key string, fn func(context.Context, *Tx) error) error {
if len(key) > maxKey {
return fmt.Errorf("%w: key is over %d bytes", ErrInvalid, maxKey)
}
if id != "" {
return s.sessions.With(ctx, id, fn)
}
for {
tx := NewTx()
if err := fn(ctx, tx); err != nil {
return err
}
if len(tx.top()) == 0 {
return nil
}
err := s.store.Apply(ctx, tx.Reads, tx.top())
if !errors.Is(err, ErrConflict) {7
return err
}
}
}
// read checks the layers from the top down, then the store. It records the version it saw, once.
func (s *Service) read(ctx context.Context, tx *Tx, key string) (string, error) {
for i := len(tx.Layers) - 1; i >= 0; i-- {2
if value, ok := tx.Layers[i][key]; ok {
if value == nil {
return "", ErrNotFound
}
return *value, nil
}
}
e, err := s.store.Get(ctx, key)
if err != nil && !errors.Is(err, ErrNotFound) {
return "", err
}
if _, seen := tx.Reads[key]; !seen {4
tx.Reads[key] = e.Version
}
return e.Value, err
}
func (s *Service) Get(ctx context.Context, id, key string) (string, error) {
var value string
err := s.do(ctx, id, key, func(ctx context.Context, tx *Tx) error {
var err error
value, err = s.read(ctx, tx, key)
return err
})
return value, err
}
func (s *Service) Set(ctx context.Context, id, key, value string) error {
return s.do(ctx, id, key, func(_ context.Context, tx *Tx) error {
tx.top()[key] = &value
return nil
})
}
func (s *Service) Delete(ctx context.Context, id, key string) error {
return s.do(ctx, id, key, func(ctx context.Context, tx *Tx) error {
if _, err := s.read(ctx, tx, key); err != nil {
return err
}
tx.top()[key] = nil
return nil
})
}
func (s *Service) Open(ctx context.Context) (string, error) {
return s.sessions.Create(ctx)
}
func (s *Service) Begin(ctx context.Context, id string) error {
return s.sessions.With(ctx, id, func(_ context.Context, tx *Tx) error {
tx.Layers = append(tx.Layers, Writes{})
return nil
})
}
// Commit ends the top layer: it merges into the layer below, or into the store at depth 1.
func (s *Service) Commit(ctx context.Context, id string) error {
return s.sessions.With(ctx, id, func(ctx context.Context, tx *Tx) error {
top := tx.pop()
if len(tx.Layers) > 0 {
maps.Copy(tx.top(), top)5
return nil
}
return s.store.Apply(ctx, tx.Reads, top)6
})
}
func (s *Service) Rollback(ctx context.Context, id string) error {
return s.sessions.With(ctx, id, func(_ context.Context, tx *Tx) error {
tx.pop()
return nil
})
}
- 1Get, Set and Delete have one path each, with or without a transaction. This is what keeps the build small.
- 2From the top down: the newest write in this transaction wins.
- 3A nil is a delete at this level. Stop here, or the key would show through from below.
- 4Keep the first version seen, so a later commit by another client cannot hide the conflict.
- 5An inner commit overwrites the level below, deletes included.
- 6Only here do writes reach the store. A conflict still ends the transaction: no layers remain.
- 7A plain request retries on a conflict. 100 parallel deletes give exactly one 204, and the rest find the key gone.
A plain request is a one-level transaction that commits at once, so there is only one code path. Rollback does not remove reads, because the client has seen them.
package build
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
)
type kv struct {
Key string `json:"key"`
Value string `json:"value"`
}
// Handler serves the three key routes with and without a transaction: outside one,
// r.PathValue("id")1 is empty.
func Handler(svc *Service) http.Handler {
get := route(200, func(r *http.Request) (any, error) {
key := r.PathValue("key")
value, err := svc.Get(r.Context(), r.PathValue("id"), key)
return kv{key, value}, err
})
set := route(200, func(r *http.Request) (any, error) {
var body struct{ Value *string }3
if err := readJSON(r, &body); err != nil {
return nil, err
}
if body.Value == nil {
return nil, fmt.Errorf("%w: value is required", ErrInvalid)
}
key := r.PathValue("key")
return kv{key, *body.Value}, svc.Set(r.Context(), r.PathValue("id"), key, *body.Value)
})
del := route(204, func(r *http.Request) (any, error) {
return nil, svc.Delete(r.Context(), r.PathValue("id"), r.PathValue("key"))
})
step := func(fn func(context.Context, string) error) http.Handler {
return route(200, func(r *http.Request) (any, error) {
id := r.PathValue("id")
return map[string]string{"id": id}, fn(r.Context(), id)
})
}
mux := http.NewServeMux()
for _, prefix := range []string{"", "/tx/{id}"} {2
mux.Handle("GET "+prefix+"/kv/{key}", get)
mux.Handle("PUT "+prefix+"/kv/{key}", set)
mux.Handle("DELETE "+prefix+"/kv/{key}", del)
}
mux.Handle("POST /tx", route(201, func(r *http.Request) (any, error) {
id, err := svc.Open(r.Context())
return map[string]string{"id": id}, err
}))
mux.Handle("POST /tx/{id}/begin", step(svc.Begin))
mux.Handle("POST /tx/{id}/commit", step(svc.Commit)4)
mux.Handle("POST /tx/{id}/rollback", step(svc.Rollback))
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 code == 204 {5
return
}
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()}
}
- 1Empty on /kv/{key}. The service reads that as no transaction.
- 2Each key route exists twice and serves one handler.
- 3A pointer tells a missing value from an empty string.
- 4A method value. Begin, Commit and Rollback share one signature, so they share one route helper.
- 5A 204 must have no body.
// Command main serves the 45-minute key-value store.
package main
import (
"log"
"net/http"
"github.com/rudrite/system-design/arena/exercises/kvstore/build"
)
func main() {
svc := build.NewService(build.NewMemStore(), build.NewMemSessions())
handler := build.Handler(svc)
log.Fatal(http.ListenAndServe(":8080", handler))
}
The same three handlers serve both route forms. Outside a transaction, the path value is empty.
package build
import (
"fmt"
"net/http"
"net/http/httptest"
"regexp"
"strconv"
"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, tx string, steps []step) {
t.Helper()
for i, s := range steps {
status, body := do(h, s.method, strings.ReplaceAll(s.path, "TX", tx)1, 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) string {
_, body := do(h, "POST", "/tx", "")
return regexp.MustCompile(`[A-Z0-9]{26}`).FindString(body)
}
func newHandler() http.Handler {
return Handler(NewService(NewMemStore(), NewMemSessions()))
}
func TestKeys(t *testing.T) {
run(t, newHandler(), "", []step{
{"GET", "/kv/a", "", 404, "not found"},
{"PUT", "/kv/a", `{"value":"1"}`, 200, `"1"`},
{"GET", "/kv/a", "", 200, `"1"`},
{"PUT", "/kv/a", `{}`, 400, "value is required"},
{"DELETE", "/kv/a", "", 204, ""},
{"DELETE", "/kv/a", "", 404, "not found"},
})
}
func TestNestedTransactions(t *testing.T) {
h := newHandler()
run(t, h, open(h), []step{
{"PUT", "/tx/TX/kv/a", `{"value":"1"}`, 200, ""},
{"GET", "/kv/a", "", 404, ""},
{"POST", "/tx/TX/begin", "", 200, ""},
{"PUT", "/tx/TX/kv/a", `{"value":"2"}`, 200, ""},
{"GET", "/tx/TX/kv/a", "", 200, `"2"`},
{"POST", "/tx/TX/rollback", "", 200, ""},2
{"GET", "/tx/TX/kv/a", "", 200, `"1"`},
{"POST", "/tx/TX/commit", "", 200, ""},
{"GET", "/kv/a", "", 200, `"1"`},
{"POST", "/tx/TX/commit", "", 404, ""},
})
}
func increment(t *testing.T, h http.Handler) {
for {
tx := "/tx/" + open(h)
_, body := do(h, "GET", tx+"/kv/n", "")
n, err := strconv.Atoi(regexp.MustCompile(`\d+`).FindString(body))
if err != nil {
t.Error(err)
return
}
do(h, "PUT", tx+"/kv/n", fmt.Sprintf(`{"value":"%d"}`, n+1))
if status, _ := do(h, "POST", tx+"/commit", ""); status == 200 {3
return
}
}
}
func TestParallelIncrements(t *testing.T) {
h := newHandler()
do(h, "PUT", "/kv/n", `{"value":"0"}`)
var wg sync.WaitGroup
for range 100 {
wg.Go(func() { increment(t, h) })4
}
wg.Wait()
run(t, h, "", []step{{"GET", "/kv/n", "", 200, `"100"`}})
}
- 1The server picks the ID, so the steps use a placeholder.
- 2Inner rollback: the next line reads the outer value again.
- 3A 409 falls through and the loop begins a new transaction.
- 4Run with -race. The final value must be exactly 100.
Each test is a list of steps, so a new behaviour is one row. The race test retries on 409 as a real client must.
arena run kvstore --base http://localhost:8080
correctness
PASS get returns what set stored
PASS set replaces the value
PASS an empty string is a value
PASS delete removes the key
PASS commit publishes the writes
PASS a transaction reads its own writes
PASS writes stay hidden until commit
PASS rollback discards the writes
PASS a delete in a transaction waits for commit
PASS nested rollback undoes only the inner level
PASS nested commit is undone by an outer rollback
PASS three levels unwind in order
status codes
PASS get of a missing key is 404
PASS delete of a missing key is 404
PASS begin is 201 and returns an id
PASS an unknown transaction is 404
PASS an ended transaction is 404
PASS a stale read gives 409 at commit
PASS two creators of one key: the second gets 409
validation
PASS malformed JSON is 400
PASS a missing value is 400
PASS a value of the wrong type is 400
PASS a key over 256 bytes is 400
PASS a key of exactly 256 bytes is fine
concurrency
PASS 100 parallel sets of one key all succeed
PASS 100 parallel deletes of one key: exactly one wins
PASS 100 parallel transactions increment one key: none is lost
PASS 100 parallel rollbacks leave the key alone
PASS 100 parallel writes in one transaction all land
PASS 100 parallel commits of one transaction: exactly one wins
30 checks: 30 passed, 0 failedAll checks pass, with 100 parallel transactions on one key.
| choice | status |
|---|---|
| A transaction ID per client | Approved |
| One global stack | Not approved |
| One global mutex for the whole build | Say the cost |
| Validate reads at commit | Approved |
| Locks held across HTTP requests | Not approved |
| A database transaction per HTTP transaction | Not approved |
| Copy the whole store at begin | Small data |
I say what I chose and what it costs, then I move on.
| the interviewer asks | the answer | goes deeper |
|---|---|---|
| Which isolation level does this give? | Serializable for single-key reads and writes. Every read version is checked at commit under one lock, so the commits act as if they ran one at a time. | T2 Isolation levels |
| Why check at commit and not lock at read? | A client can hold a transaction open for minutes, and a lock would block every other client that long. Validation holds no lock between requests. Under heavy conflict, retries grow, and then locks win. | T5 Concurrency control |
| A client reads two keys and wants a stable view. Does it get one? | Not during the transaction: a read can see a newer commit, and the commit then fails. For a true snapshot, keep old versions and read as of the start. That is MVCC. | T3 MVCC |
| One HTTP transaction, one database transaction. Why not? | That pins a connection and holds row locks while the client thinks. A few idle clients can use up the pool. We keep the state in a row and run one short database transaction per request. | T4 Locks in the database |
| Run two instances. What breaks? | Each mutex covers one process, and each map holds different data. Both move to Postgres: the row lock replaces the session mutex, and the advisory lock replaces the store mutex. | T6 Distributed locks |
| The process dies after a commit. Does the write survive? | In the build, no. With Postgres, yes: the commit returns after the write-ahead log is flushed. To build it yourself, append the commit to a log, flush it, then answer, and replay the log at startup. | T1 ACID and the log |
| Postgres, or your own log-structured store? | Postgres, because it already has durability, backups and replicas. A log plus an in-memory index is simple until it needs compaction and recovery. Write my own only for a throughput that Postgres cannot reach. | D1 Storage engines |
| The commit response is lost. The client retries. Then what? | It gets 404, because the session has ended, so it cannot tell success from expiry. Add an idempotency key on commit and store the outcome in the same database transaction. | T9 Exactly-once |
| A client begins and never returns. | Each request moves the expiry forward by 15 minutes. After that, requests answer 404, and a sweeper deletes the row. An open transaction holds no database resource, so waiting is cheap. | O2 Resilience patterns |
| Who may touch a transaction? | Only its owner. The bearer token gives an owner, and each session query filters on it. A different owner gets 404 and not 403, so an ID reveals nothing. | O5 Security |
| What goes on the dashboard? | Rate, errors and duration per route. The 409 rate on commit is the one that matters here. It shows contention before users report slow retries. | O3 Observability |
| One key takes most of the writes. | Every transaction on it retries, and the 409 rate climbs. Offer an atomic increment for counters, or split the key. For size rather than contention, shard by key. | X2 Sharding |
I start from what the build lacks: durability, two instances, then retries. I name each limit before the interviewer does.
Instances hold no state. Postgres holds the data and each open transaction, so any instance can serve any request.
| tool | build | production |
|---|---|---|
| Postgres | MemStore: map and mutex | PGStore: kv table, advisory locks per key |
| Postgres | MemSessions: map and mutexes | PGSessions: one row per transaction, FOR UPDATE, expiry |
| Service | No auth | Bearer tokens; each transaction has an owner |
| Service | No metrics | Requests and time by route and status; health route |
| Service | ListenAndServe | Timeouts, a body limit, drain on SIGTERM |
Tested: production passes the same 30 grader checks. The real binary passes them over a socket, then exits cleanly on SIGTERM.
Two interfaces, two new implementations, and a wrapper around the same handler. The service file does not change.
store.go, sessions.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 key-value store. It reads DATABASE_URL, API_TOKENS
+ // (owner:token,owner:token) and ADDR, which defaults to :8080.
- // Command main serves the 45-minute key-value store.
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/kvstore/prod"
- "github.com/rudrite/system-design/arena/exercises/kvstore/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 := prod.ParseTokens(os.Getenv("API_TOKENS"))
+ if err != nil {
+ return err
+ }
+ sessions := prod.NewPGSessions(pool, 15*time.Minute)
+ go sweep(ctx, sessions)
+
+ srv := &http.Server{
+ Addr: cmp.Or(os.Getenv("ADDR"), ":8080"),
+ Handler: prod.Handler(pool, sessions, tokens, prod.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, sessions *prod.PGSessions) {
+ tick := time.NewTicker(time.Minute)
+ defer tick.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-tick.C:
+ if _, err := sessions.Sweep(ctx); err != nil && ctx.Err() == nil {
+ log.Print(err)
+ }
+ }
+ }
- svc := build.NewService(build.NewMemStore(), build.NewMemSessions())
- handler := build.Handler(svc)
- log.Fatal(http.ListenAndServe(":8080", handler))
}CREATE SEQUENCE IF NOT EXISTS kv_version;
CREATE TABLE IF NOT EXISTS kv (
key text PRIMARY KEY,
value text NOT NULL,
version bigint NOT NULL
);
CREATE TABLE IF NOT EXISTS kv_sessions (
id text PRIMARY KEY,
owner text NOT NULL,
tx jsonb NOT NULL,
expires_at timestamptz NOT NULL
);
CREATE INDEX IF NOT EXISTS kv_sessions_expires ON kv_sessions (expires_at);pgstore: implements Storenew file, +110
+ // Package prod is the key-value store made production grade. It imports the 45-minute build and
+ // replaces the two in-memory parts behind their interfaces, then adds auth, metrics and health.
+ // The service and the handler do not change.
+ package prod
+
+ import (
+ "context"
+ "errors"
+ "fmt"
+ "maps"
+ "slices"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/rudrite/system-design/arena/exercises/kvstore/build"
+ )
+
+ // 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}
+ }
+
+ type txKey struct{}
+
+ // conn is the session's open database transaction when there is one, so a commit and the end of
+ // its session land together. Otherwise it is the pool.
+ func (s *PGStore) conn(ctx context.Context) interface {
+ Begin(context.Context) (pgx.Tx, error)
+ QueryRow(context.Context, string, ...any) pgx.Row
+ } {
+ if tx, ok := ctx.Value(txKey{}).(pgx.Tx); ok {
+ return tx
+ }
+ return s.pool
+ }
+
+ // Get returns the key's value and version.
+ func (s *PGStore) Get(ctx context.Context, key string) (build.Entry, error) {
+ var e build.Entry
+ err := s.conn(ctx).QueryRow(ctx, `SELECT value, version FROM kv WHERE key = $1`, key).Scan(&e.Value, &e.Version)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return build.Entry{}, build.ErrNotFound
+ }
+ if err != nil {
+ return build.Entry{}, fmt.Errorf("get %s: %w", key, err)
+ }
+ return e, nil
+ }
+
+ // lockKeys takes one lock per key, in one order, and it holds them to the end of the database
+ // transaction. A key that does not exist yet has no row to lock, so a row lock would not do.
+ const lockKeys = `
+ SELECT pg_advisory_xact_lock(hashtextextended(k, 0))
+ FROM (SELECT k FROM unnest($1::text[]) AS k ORDER BY hashtextextended(k, 0), k) AS sorted`
+
+ const upsert = `
+ INSERT INTO kv (key, value, version) VALUES ($1, $2, nextval('kv_version'))
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, version = excluded.version`
+
+ // Apply compares the read versions and makes the writes in one database transaction.
+ func (s *PGStore) Apply(ctx context.Context, reads build.Reads, writes build.Writes) error {
+ keys := slices.Sorted(maps.Keys(reads))
+ keys = slices.AppendSeq(keys, maps.Keys(writes))
+ err := pgx.BeginFunc(ctx, s.conn(ctx), func(tx pgx.Tx) error {
+ if _, err := tx.Exec(ctx, lockKeys, keys); err != nil {
+ return fmt.Errorf("lock keys: %w", err)
+ }
+ rows, err := tx.Query(ctx, `SELECT key, version FROM kv WHERE key = ANY($1)`, slices.Collect(maps.Keys(reads)))
+ if err != nil {
+ return fmt.Errorf("read versions: %w", err)
+ }
+ current := map[string]int64{}
+ var key string
+ var version int64
+ if _, err := pgx.ForEachRow(rows, []any{&key, &version}, func() error {
+ current[key] = version
+ return nil
+ }); err != nil {
+ return fmt.Errorf("read versions: %w", err)
+ }
+ for key, seen := range reads {
+ if current[key] != seen {
+ return build.ErrConflict
+ }
+ }
+ for key, value := range writes {
+ if value == nil {
+ _, err = tx.Exec(ctx, `DELETE FROM kv WHERE key = $1`, key)
+ } else {
+ _, err = tx.Exec(ctx, upsert, key, *value)
+ }
+ if err != nil {
+ return fmt.Errorf("write %s: %w", key, err)
+ }
+ }
+ return nil
+ })
+ var pgErr *pgconn.PgError
+ if errors.As(err, &pgErr) && pgErr.Code == "40P01" { // deadlock_detected: two keys shared a hash
+ return build.ErrConflict
+ }
+ return err
+ }pgsessions: implements Sessionsnew file, +90
+ package prod
+
+ import (
+ "context"
+ "crypto/rand"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/rudrite/system-design/arena/exercises/kvstore/build"
+ )
+
+ // PGSessions implements build.Sessions on Postgres. Any instance can serve any request of a
+ // transaction, an open transaction survives a restart, and an abandoned one expires. Between
+ // requests it holds no database transaction and no connection.
+ type PGSessions struct {
+ pool *pgxpool.Pool
+ ttl time.Duration
+ }
+
+ // NewPGSessions returns sessions on pool that expire after ttl without a request.
+ func NewPGSessions(pool *pgxpool.Pool, ttl time.Duration) *PGSessions {
+ return &PGSessions{pool: pool, ttl: ttl}
+ }
+
+ // Create opens a transaction owned by the caller.
+ func (p *PGSessions) Create(ctx context.Context) (string, error) {
+ id := rand.Text()
+ _, err := p.pool.Exec(ctx,
+ `INSERT INTO kv_sessions (id, owner, tx, expires_at) VALUES ($1, $2, $3, now() + $4::interval)`,
+ id, OwnerFrom(ctx), build.NewTx(), p.ttl)
+ if err != nil {
+ return "", fmt.Errorf("create session: %w", err)
+ }
+ return id, nil
+ }
+
+ // With runs fn on the caller's open transaction. The row lock lines up parallel requests on one
+ // transaction. Another owner's id reads as missing, so a caller cannot tell that it exists.
+ func (p *PGSessions) With(ctx context.Context, id string, fn func(context.Context, *build.Tx) error) error {
+ var fnErr error
+ err := pgx.BeginFunc(ctx, p.pool, func(db pgx.Tx) error {
+ var tx build.Tx
+ err := db.QueryRow(ctx,
+ `SELECT tx FROM kv_sessions WHERE id = $1 AND owner = $2 AND expires_at > now() FOR UPDATE`,
+ id, OwnerFrom(ctx)).Scan(&tx)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return build.ErrNotFound
+ }
+ if err != nil {
+ return fmt.Errorf("load session: %w", err)
+ }
+
+ fnErr = fn(context.WithValue(ctx, txKey{}, db), &tx)
+ if fnErr != nil && !isDomain(fnErr) {
+ return fnErr
+ }
+ if len(tx.Layers) == 0 {
+ _, err = db.Exec(ctx, `DELETE FROM kv_sessions WHERE id = $1`, id)
+ } else {
+ _, err = db.Exec(ctx, `UPDATE kv_sessions SET tx = $2, expires_at = now() + $3::interval WHERE id = $1`, id, tx, p.ttl)
+ }
+ if err != nil {
+ return fmt.Errorf("save session: %w", err)
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ return fnErr
+ }
+
+ // isDomain says whether err is an answer for the client. A read of an absent key is one, and its
+ // read version must still be saved. Anything else rolls the session back.
+ func isDomain(err error) bool {
+ return errors.Is(err, build.ErrNotFound) || errors.Is(err, build.ErrConflict) || errors.Is(err, build.ErrInvalid)
+ }
+
+ // Sweep deletes the sessions that have expired and returns how many.
+ func (p *PGSessions) Sweep(ctx context.Context) (int64, error) {
+ tag, err := p.pool.Exec(ctx, `DELETE FROM kv_sessions WHERE expires_at <= now()`)
+ if err != nil {
+ return 0, fmt.Errorf("sweep sessions: %w", err)
+ }
+ return tag.RowsAffected(), nil
+ }server: wraps the build's handlernew file, +47
+ package prod
+
+ import (
+ "context"
+ _ "embed"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/rudrite/system-design/arena/exercises/kvstore/build"
+ )
+
+ //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. Neither of those two
+ // takes a token: the load balancer and the metrics scraper have none.
+ func Handler(pool *pgxpool.Pool, sessions *PGSessions, tokens Tokens, metrics *Metrics) http.Handler {
+ svc := build.NewService(NewPGStore(pool), sessions)
+
+ mux := http.NewServeMux()
+ mux.Handle("/", metrics.Wrap(Auth(tokens, http.MaxBytesHandler(build.Handler(svc), 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
+ }middleware: auth and metricsnew file, +120
+ package prod
+
+ import (
+ "context"
+ "crypto/sha256"
+ "fmt"
+ "net/http"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+ )
+
+ type ownerKey struct{}
+
+ // OwnerFrom returns the authenticated caller.
+ func OwnerFrom(ctx context.Context) string {
+ owner, _ := ctx.Value(ownerKey{}).(string)
+ return owner
+ }
+
+ // Tokens maps the SHA-256 of an API token to its owner. A map lookup on a hash leaks no timing
+ // about the token itself.
+ type Tokens map[[sha256.Size]byte]string
+
+ // ParseTokens reads "owner:token,owner:token".
+ func ParseTokens(s string) (Tokens, error) {
+ tokens := Tokens{}
+ for part := range strings.SplitSeq(s, ",") {
+ owner, token, ok := strings.Cut(part, ":")
+ if !ok || owner == "" || token == "" {
+ return nil, fmt.Errorf("token list: want owner:token, got %q", part)
+ }
+ tokens[sha256.Sum256([]byte(token))] = owner
+ }
+ return tokens, nil
+ }
+
+ // Auth rejects a request without a known bearer token with 401, and passes the owner on.
+ func Auth(tokens Tokens, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ token, bearer := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
+ owner, known := tokens[sha256.Sum256([]byte(token))]
+ if !bearer || !known {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
+ return
+ }
+ next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ownerKey{}, owner)))
+ })
+ }
+
+ type series struct {
+ method, route string
+ status int
+ }
+
+ type sample struct {
+ count int64
+ seconds float64
+ }
+
+ // Metrics counts requests by method, route and status, in the Prometheus text format. A commit
+ // conflict shows up as a 409 on the tx route.
+ type Metrics struct {
+ mu sync.Mutex
+ seen map[series]sample
+ }
+
+ // NewMetrics returns empty counters.
+ func NewMetrics() *Metrics {
+ return &Metrics{seen: map[series]sample{}}
+ }
+
+ type recorder struct {
+ http.ResponseWriter
+ status int
+ }
+
+ func (r *recorder) WriteHeader(status int) {
+ r.status = status
+ r.ResponseWriter.WriteHeader(status)
+ }
+
+ // Wrap measures every request that passes through it. The route label is the first path segment,
+ // so keys and ids never reach a label and the series stay few.
+ func (m *Metrics) Wrap(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ start := time.Now()
+ rec := &recorder{ResponseWriter: w, status: 200}
+ next.ServeHTTP(rec, r)
+ route, _, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/")
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ s := m.seen[series{r.Method, route, rec.status}]
+ s.count++
+ s.seconds += time.Since(start).Seconds()
+ m.seen[series{r.Method, route, rec.status}] = s
+ })
+ }
+
+ // ServeHTTP writes the counters.
+ func (m *Metrics) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
+ m.mu.Lock()
+ lines := make([]string, 0, 2*len(m.seen))
+ for k, s := range m.seen {
+ labels := fmt.Sprintf(`{method=%q,route=%q,status="%d"}`, k.method, k.route, k.status)
+ lines = append(lines,
+ "http_requests_total"+labels+" "+strconv.FormatInt(s.count, 10),
+ "http_request_seconds_sum"+labels+" "+strconv.FormatFloat(s.seconds, 'f', 6, 64))
+ }
+ m.mu.Unlock()
+ slices.Sort(lines)
+ w.Header().Set("Content-Type", "text/plain; version=0.0.4")
+ if _, err := fmt.Fprintln(w, strings.Join(lines, "\n")); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ }The diff is one changed file and a few new ones. That is what the interfaces in the build were for.
0 of 9 known
Your CLI version keeps one global stack of layers. What goes wrong when you put it behind HTTP?
Why is a deleted key stored as nil in a layer instead of being removed from the layer?
Transaction T reads k and finds it absent. Another client creates k. T then writes k and commits. What happens?
An inner level reads k and rolls back. Then another client changes k. Does the outer commit conflict?
A key is deleted and set back to the same value while T is open. T read it earlier. Does T conflict?
MemSessions holds one mutex for all of fn, including a commit to the store. What does that cost?
Why does the session query in production use FOR UPDATE?
In production, why does Apply take an advisory lock and not a row lock?
Why do the session update and the data write share one database transaction?
- build
- 469 lines with tests, 18:19 of typing at 100 words a minute.
- checks
- 30 grader checks, in 4 groups.
- race
- 100 parallel transactions on one key; the value ends at exactly 100.
- expiry
- 15 minutes after the last request.
- body limit
- 1 MiB in production.
Design values from the tested code, not load measurements.