The productionization playbook
You have built an in-memory service. The interviewer asks how to make it production grade. This sheet is the map of that talk: the order, the time, what to say, and what changes in the code. Read it the night before.
- 1Walk from the data outward: durability, two copies, transactions, retries. Then the edge, then operations.
- 2Name each limit of your build before the interviewer does.
- 3A mutex covers one process. Move the lock to where the data lives.
- 4Most topics add one wrapper or one new Store, so the service does not change.
I will go in this order unless you want to jump to something.
This service is correct on one machine until that machine restarts. I will start with where the data lives, then what breaks when two copies run, and then work outward to the edge and to operations.
| leg | minutes | why here |
|---|---|---|
| The data | 18 | Every later topic assumes that the data is safe. |
| The edge | 11 | Who may call, what they see, and how much they may ask for. |
| Running it | 16 | How you know it works, and how it changes without downtime. |
- Each stop has 4 parts: the question, the answer to say, the code, the sheet that goes deeper.
- Say the answer in about 30 seconds. Stop, and let the interviewer pick the next depth.
- If the interviewer jumps, go with them. Come back to the route when they stop.
- Short of time? Finish the data leg, then name the rest in one line each.
- The minutes are a suggested plan, not a measurement.
The process restarts. What happens to the data?
All of the data is gone, so durable storage comes first. The Store interface makes that one new file: PGStore replaces MemStore, and the service does not change. Schema changes run as migrations, and each copy gets a sized connection pool.
func (s *PGStore) Update(ctx context.Context, key string, fn func(*Item) error) (Item, error) {
var item Item
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `INSERT INTO items (key) VALUES ($1) ON CONFLICT DO NOTHING1`, key); err != nil {
return fmt.Errorf("create %s: %w", key, err)
}
err := tx.QueryRow(ctx, `SELECT count FROM items WHERE key = $1 FOR UPDATE2`, key).Scan(&item.Count)
if err != nil {
return fmt.Errorf("lock %s: %w", key, err)
}
if err := fn(&item)3; err != nil {
return err
}
_, err = tx.Exec(ctx, `UPDATE items SET count = $2 WHERE key = $1`, key, item.Count)
return err
})
return item, err
}
- 1An absent key has no row to lock, so create the row first. A refused rule rolls this back too.
- 2The row lock replaces the mutex. It lasts until the transaction ends.
- 3The same fn as in the build. The service does not know that a database exists.
CREATE TABLE items (
key text PRIMARY KEY,
count integer NOT NULL DEFAULT 0 CHECK (count BETWEEN 0 AND 1000),
version bigint NOT NULL DEFAULT 0,
fence bigint NOT NULL DEFAULT 0
);
// Migrate applies each new file once. The advisory lock makes two
// copies that start together wait.
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
names, err := fs.Glob(migrations, "migrations/*.sql")
if err != nil {
return fmt.Errorf("list migrations: %w", err)
}
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(1)1`); err != nil {
return fmt.Errorf("lock migrations: %w", err)
}
if _, err := tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY)`); err != nil {
return fmt.Errorf("create schema_migrations: %w", err)
}
for _, name := range names {
tag, err := tx.Exec(ctx, `INSERT INTO schema_migrations VALUES ($1) ON CONFLICT DO NOTHING`, name)
if err != nil {
return fmt.Errorf("record %s: %w", name, err)
}
if tag.RowsAffected() == 0 {
continue
}
sql, err := migrations.ReadFile(name)
if err != nil {
return fmt.Errorf("read %s: %w", name, err)
}
if _, err := tx.Exec(ctx, string(sql)); err != nil {
return fmt.Errorf("apply %s: %w", name, err)
}
}
return nil
})
}
- 1Two copies that start at once wait here. Each file runs once.
// NewPool sizes the pool per copy. copies × MaxConns must stay under
// the max_connections setting of Postgres.
func NewPool(ctx context.Context, url string, maxConns int32) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
return nil, fmt.Errorf("parse database url: %w", err)
}
cfg.MaxConns = maxConns
cfg.MaxConnLifetime = 30 * time.Minute
cfg.ConnConfig.ConnectTimeout = 3 * time.Second
return pgxpool.NewWithConfig(ctx, cfg)
}
Goes deeper: D3 Data modeling, T1 ACID and the log. The same contract test passes on MemStore and on PGStore.
You run two copies behind a load balancer. Is it still safe?
No. A mutex protects one process, so two copies have two mutexes, and each holds its own data. I move the state to Postgres and let the database order the writes.
Two copies of the E1 build, one address, the E1 client. The copies share nothing, as two processes would.
commits lost tx final 100 clients add 1
100 0 100 one copy, memory
0 100 0 two copies, memory, round robin
100 0 50 two copies, memory, pinned
100 0 77 two copies, one Postgres, a mutex each, pinned
100 0 100 two copies, one Postgres, E1 production- Round robin: a transaction begins on one copy. The next request reaches the other copy and gets 404.
- Pinned: the mutexes work, and each copy holds half of the writes.
- One Postgres, a mutex each: the checks of two copies overlap, so a write overwrites another. This final count changes from run to run. The test asserts only that it stays under 100.
- E1 production: the lock is in Postgres, and any copy serves any request.
With a mutex in each copy over one Postgres, every commit returned 200 and the count ended at 77. The real fix moves the lock into the database.
| tool | method | use it when | status |
|---|---|---|---|
| Service | A mutex in each copy | Never, past one process | Not approved |
| Postgres | Conditional update | One statement can hold the rule | Approved |
| Postgres | Row lock, FOR UPDATE | The rule needs code, and the transaction is short | Approved |
| Postgres | Optimistic version | Conflicts are rare, or a client holds a value across requests | Low contention |
| Redis | Redis lease with fencing | The work spans systems that one transaction cannot cover | With a token |
// MutexStore keeps the mutex and swaps the map for Postgres.
// Each copy has its own mu, so the checks of two copies overlap.
type MutexStore struct {
mu sync.Mutex
pool *pgxpool.Pool
}
func (s *MutexStore) Apply(ctx context.Context, reads build.Reads, writes build.Writes) error {
s.mu.Lock()1
defer s.mu.Unlock()
for key, seen := range reads {
var version int64
err := s.pool.QueryRow(ctx, `SELECT version FROM kv WHERE key = $1`, key).Scan(&version)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("read %s: %w", key, err)
}
if version != seen {
return build.ErrConflict
}
}
time.Sleep(2 * time.Millisecond) // widens the gap, as a slow network does
for key, value := range writes {
_, err := s.pool.Exec(ctx, `INSERT INTO kv (key, value, version) VALUES ($1, $2, nextval('kv_version'))
ON CONFLICT (key) DO UPDATE SET value = excluded.value, version = excluded.version`, key, *value)
if err != nil {
return fmt.Errorf("write %s: %w", key, err)
}
}
return nil
}
- 1One lock per copy. Nothing stops the other copy between the check and the write.
// AddConditional puts the rule in the WHERE clause, so one statement
// checks and writes.
func AddConditional(ctx context.Context, pool *pgxpool.Pool, key string, by int) error {
tag, err := pool.Exec(ctx, `UPDATE items SET count = count + $2 WHERE key = $1 AND count + $2 <= 10001`, key, by)
if err != nil {
return fmt.Errorf("add to %s: %w", key, err)
}
if tag.RowsAffected() == 0 {
return ErrConflict
}
return nil
}
- 1The rule from service.go moves into the statement. The row lock lasts for one statement.
// AddOptimistic reads without a lock. The write succeeds only if the
// version has not moved.
func AddOptimistic(ctx context.Context, pool *pgxpool.Pool, key string, by int) error {
for ctx.Err() == nil {
var count int
var version int64
err := pool.QueryRow(ctx, `SELECT count, version FROM items WHERE key = $1`, key).Scan(&count, &version)
if err != nil {
return fmt.Errorf("read %s: %w", key, err)
}
if count+by > 1000 {
return ErrConflict
}
tag, err := pool.Exec(ctx, `UPDATE items SET count = $2, version = version + 1 WHERE key = $1 AND version = $31`,
key, count+by, version)
if err != nil {
return fmt.Errorf("write %s: %w", key, err)
}
if tag.RowsAffected() == 1 {
return nil
}
}
return ctx.Err()
}
- 1Zero rows affected means that someone else wrote first, so the loop reads again.
// AcquireLease returns a token that only goes up. A holder that loses
// the lease still has a token, but the next holder's token is higher.
func AcquireLease(ctx context.Context, rdb *redis.Client, name string, ttl time.Duration) (int64, error) {
token, err := rdb.Incr(ctx, name+":fence")1.Result()
if err != nil {
return 0, fmt.Errorf("next fence: %w", err)
}
err = rdb.SetArgs(ctx, name+":lock", token, redis.SetArgs{Mode: "NX", TTL: ttl}).Err()
if err == redis.Nil {
return 0, ErrConflict
}
if err != nil {
return 0, fmt.Errorf("take lease: %w", err)
}
return token, nil
}
// WriteFenced is the check the lock cannot make itself: the database
// refuses an old token.
func WriteFenced(ctx context.Context, pool *pgxpool.Pool, key string, token int64, count int) error {
tag, err := pool.Exec(ctx, `UPDATE items SET count = $3, fence = $2 WHERE key = $1 AND fence <= $22`, key, token, count)
if err != nil {
return fmt.Errorf("fenced write %s: %w", key, err)
}
if tag.RowsAffected() == 0 {
return ErrConflict
}
return nil
}
- 1A counter gives each holder a higher number than the last.
- 2A holder that paused past its lease writes with an old token, and this refuses it.
Goes deeper: T4 Locks in the database, T5 Concurrency control, T6 Distributed locks. The row lock is the Update in panel C.
I prefer a conditional update when one statement can hold the rule. A row lock is my default for anything else. Optimistic versions suit low contention. A Redis lock needs a fencing token, and it comes last.
What must be atomic here?
Whatever keeps an invariant: a debit and its credit land together or not at all. One transaction holds both, and locks go in one order, so two transfers cannot deadlock. Read Committed with row locks is enough here. A rule that reads many rows needs Serializable.
// Transfer moves by from one item to another. Both writes land, or
// neither does.
func Transfer(ctx context.Context, pool *pgxpool.Pool, from, to string, by int) error {
keys := []string{from, to}
slices.Sort(keys)1
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
for _, key := range keys {
var count int
if err := tx.QueryRow(ctx, `SELECT count FROM items WHERE key = $1 FOR UPDATE`, key).Scan(&count); err != nil {
return fmt.Errorf("lock %s: %w", key, err)
}
}
tag, err := tx.Exec(ctx, `UPDATE items SET count = count - $2 WHERE key = $1 AND count >= $22`, from, by)
if err != nil {
return fmt.Errorf("debit %s: %w", from, err)
}
if tag.RowsAffected() == 0 {
return ErrConflict
}
_, err = tx.Exec(ctx, `UPDATE items SET count = count + $2 WHERE key = $1`, to, by)
return err
})
}
- 1Without this line the test fails: Postgres reports deadlocks on opposite transfers.
- 2The rule. Zero rows rolls back the whole transaction.
Goes deeper: T2 Isolation levels.
The client times out and retries. Does it add twice?
It would, so the client sends an Idempotency-Key. I claim the key, do the work and save the answer in one transaction. A retry gets the saved answer, and the same key with a different body gets 422.
// AddOnce claims the idempotency key, does the work, and saves the
// answer in one transaction. A retry finds the key taken and returns
// the saved answer.
func AddOnce(ctx context.Context, pool *pgxpool.Pool, idemKey, key string, by int) (Item, error) {
hash := sha256.Sum256(fmt.Appendf(nil, "%s:%d", key, by))
var item Item
err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
tag, err := tx.Exec(ctx, `INSERT INTO idempotency (key, request_hash) VALUES ($1, $2) ON CONFLICT DO NOTHING1`,
idemKey, hash[:])
if err != nil {
return fmt.Errorf("claim key: %w", err)
}
if tag.RowsAffected() == 0 {
var saved []byte
err := tx.QueryRow(ctx, `SELECT request_hash, count FROM idempotency WHERE key = $1`, idemKey).Scan(&saved, &item.Count)
if err != nil {
return fmt.Errorf("read saved answer: %w", err)
}
if !bytes.Equal(saved, hash[:]) {
return ErrKeyReused2
}
return nil
}
err = tx.QueryRow(ctx, `UPDATE items SET count = count + $2 WHERE key = $1 RETURNING count`, key, by).Scan(&item.Count)
if err != nil {
return fmt.Errorf("add to %s: %w", key, err)
}
_, err = tx.Exec(ctx, `UPDATE idempotency SET count = $2 WHERE key = $1`, idemKey, item.Count)
return err
})
return item, err
}
- 1A parallel retry waits here on the unique key until the first transaction ends.
- 2The hash of the request. One key cannot name two requests.
Goes deeper: T8 Booking, T9 Exactly-once, R3 Requirements to API. Tested with 20 parallel retries: one add, one answer.
Who can call this, and how do you stop one customer reading another's data?
Authentication says who you are, and a failure is 401. Authorization says what you may do, and a failure is 403. I use a short JWT with a rotating refresh token, and every query carries the tenant.
// Principal is who the token says the caller is.
type Principal struct {
Tenant, Role string
}
type principalKey struct{}
// Authenticate answers "who are you?". An unknown caller gets 401.
func Authenticate(verify func(token string) (Principal, error)1, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
p, err := verify(token)
if !ok || err != nil {
w.Header().Set("WWW-Authenticate", "Bearer")
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), principalKey{}, p)))
})
}
// Require answers "may you do this?". A known caller without the role gets 403.
func Require(role string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, _ := r.Context().Value(principalKey{}).(Principal)
if p.Role != role {
http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// TenantStore puts the tenant in every key. Another tenant's key reads as absent: 404, not 403.
type TenantStore struct{ Store }2
func scoped(ctx context.Context, key string) string {
p, _ := ctx.Value(principalKey{}).(Principal)
return p.Tenant + "/" + key
}
func (s TenantStore) Get(ctx context.Context, key string) (Item, error) {
return s.Store.Get(ctx, scoped(ctx, key))
}
func (s TenantStore) Update(ctx context.Context, key string, fn func(*Item) error) (Item, error) {
return s.Store.Update(ctx, scoped(ctx, key), fn)
}
- 1A JWT check or a session lookup fits here. The rest of the code does not change.
- 2A wrapper around any Store. A real schema has a tenant_id column, with row-level security as a second check.
Goes deeper: O5 Security.
A list has a million rows. How do you page it? What else is in the API?
I use a cursor on a unique key and never OFFSET, because an insert shifts an offset page and repeats a row. Status codes stay exact, the path carries /v1, and each list has a page limit.
// List returns the rows after a cursor. The cursor is the last key
// seen, so an insert elsewhere cannot shift a page.
func List(ctx context.Context, pool *pgxpool.Pool, cursor string, limit int) (Page, error) {
if limit < 1 || limit > 100 {
return Page{}, fmt.Errorf("%w: limit is 1 to 100", ErrInvalid)
}
after, err := base64.RawURLEncoding.DecodeString(cursor)3
if err != nil {
return Page{}, fmt.Errorf("%w: bad cursor", ErrInvalid)
}
rows, err := pool.Query(ctx, `SELECT key, count FROM items WHERE key > $1 ORDER BY key LIMIT $21`, string(after), limit+12)
if err != nil {
return Page{}, fmt.Errorf("list items: %w", err)
}
found, err := pgx.CollectRows(rows, pgx.RowToStructByPos[Row])
if err != nil {
return Page{}, fmt.Errorf("read items: %w", err)
}
if len(found) <= limit {
return Page{Rows: found}, nil
}
found = found[:limit]
return Page{Rows: found, Next: base64.RawURLEncoding.EncodeToString([]byte(found[limit-1].Key))}, nil
}
- 1The index goes straight to the cursor, so page 1000 costs the same as page 1.
- 2One extra row tells if a next page exists, with no COUNT query.
- 3An opaque cursor. Clients cannot build one, so the sort key can change later.
Goes deeper: R3 Requirements to API. K2 is the answer if the interviewer asks to formalise the contract.
One client floods the API. What stops it?
A limiter per caller returns 429 with Retry-After. The count lives in Redis, so all copies share it. If Redis fails, I let traffic through and alert.
// RateLimit counts each caller's requests in Redis, so all copies share
// one count. If Redis fails, it logs and lets the request through.
func RateLimit(rdb *redis.Client, limit int64, window time.Duration, caller func(*http.Request) string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n, err := hit(r.Context(), rdb, caller(r), window)
if err != nil {
slog.Error("rate limit", "err", err)2
}
if n > limit {
w.Header().Set("Retry-After", strconv.Itoa(int(window.Seconds())))
http.Error(w, `{"error":"too many requests"}`, http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
func hit(ctx context.Context, rdb *redis.Client, caller string, window time.Duration) (int64, error) {
key := fmt.Sprintf("rate:%s:%d", caller, time.Now().UnixNano()/int64(window)1)
pipe := rdb.Pipeline()
n := pipe.Incr(ctx, key)
pipe.Expire(ctx, key, window)
if _, err := pipe.Exec(ctx); err != nil {
return 0, fmt.Errorf("count %s: %w", caller, err)
}
return n.Val(), nil
}
- 1A fixed window: one counter per window. It can pass twice the limit across a boundary. B3 shows the token bucket.
- 2Fail open. For a login route, fail closed instead.
Goes deeper: B3 Rate limiting. Tested across two copies: a limit of 5 passes 5 of 20.
Reads are far more than writes, and Postgres is at its limit.
First I check the query and the indexes. Then cache-aside in Redis: delete on write, with a TTL as the bound on staleness. Read replicas take the rest, and a read that must see its own write goes to the primary.
// CachedStore is cache-aside: it wraps any Store, so the service does not change.
type CachedStore struct {
Store
RDB *redis.Client
TTL time.Duration
}
func (s CachedStore) Get(ctx context.Context, key string) (Item, error) {
count, err := s.RDB.Get(ctx, "item:"+key).Int()
if err == nil {
return Item{Count: count}, nil
}
if !errors.Is(err, redis.Nil) {
slog.Error("cache read", "err", err) // a cache failure is slow, not wrong: read the store
}
item, err := s.Store.Get(ctx, key)
if err != nil {
return item, err
}
if err := s.RDB.Set(ctx, "item:"+key, item.Count, s.TTL).Err(); err != nil {
slog.Error("cache write", "err", err)
}
return item, nil
}
func (s CachedStore) Update(ctx context.Context, key string, fn func(*Item) error) (Item, error) {
item, err := s.Store.Update(ctx, key, fn)
if err != nil {
return item, err
}
if err := s.RDB.Del(ctx, "item:"+key).Err(); err != nil {2
slog.Error("cache delete", "err", err) // the TTL ends the stale value
}
return item, nil
}
- 1A wrapper around any Store, so the service does not change.
- 2Delete and do not update: two writers that update the cache can leave the older value.
Goes deeper: B4 Caching, X1 Replication.
It is launch day and errors are climbing. How do you find out why?
Rate, errors and duration per route show what broke. One structured log line per request, with a request ID, shows which calls. Traces show where the time went across services.
// Observe writes one log line per request and counts it by route
// pattern. The label is the pattern, not the path: /items/{key} is one
// series, but each key would be a new one.
func Observe(log *slog.Logger, m *Metrics, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-Id")
if id == "" {
id = rand.Text()
}
w.Header().Set("X-Request-Id", id)
rec := &recorder{ResponseWriter: w, status: http.StatusOK}
start := time.Now()
next.ServeHTTP(rec, r)
took := time.Since(start)
s := Series{Route: r.Pattern1, Status: rec.status}
m.mu.Lock()
stat := m.seen[s]
m.seen[s] = Stat{Count: stat.Count + 1, Seconds: stat.Seconds + took.Seconds()}
m.mu.Unlock()
log.Info("request"2, "id", id, "route", r.Pattern, "status", rec.status, "ms", took.Milliseconds())
})
}
- 1The matched route, since Go 1.23. A test proves that three paths give one route.
- 2JSON, one line, with the ID. Search the logs by ID to read one request.
Goes deeper: O3 Observability, R1 The 60 minutes.
Postgres is slow for a minute. What does your service do? And on deploy?
Every call has a timeout, so a slow dependency cannot hold every request. Retries use backoff with jitter, and only for errors a second try can fix. On deploy, readiness fails first, then the server drains.
// Retry waits a random time up to base, 2×base, 4×base, and so on, so
// clients that failed together do not retry together. It retries only
// an error that a second try can fix.
func Retry(ctx context.Context, tries int, base time.Duration, fn func(context.Context) error) error {
var err error
for i := range tries {
if err = fn(ctx); !errors.Is(err, ErrUnavailable)1 {
return err
}
if i == tries-1 {
break
}
select {
case <-time.After(rand.N(base << i)2):
case <-ctx.Done():
return ctx.Err()
}
}
return fmt.Errorf("after %d tries: %w", tries, err)
}
- 1A 409 stays a 409. Retrying a refusal only adds load.
- 2Full jitter: a random wait up to the cap, so clients spread out.
// NewServer sets the timeouts that ListenAndServe leaves at zero: no limit.
func NewServer(h http.Handler) *http.Server {
return &http.Server{
Handler: h,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
}
// Serve runs until ctx ends, then drains: readiness fails first, so the
// load balancer stops sending traffic, and then Shutdown waits for the
// requests already running.
func Serve(ctx context.Context, srv *http.Server, ln net.Listener, ready *atomic.Bool, drain, wait time.Duration) error {
failed := make(chan error, 1)
go func() { failed <- srv.Serve(ln) }()
ready.Store(true)
select {
case err := <-failed:
return fmt.Errorf("serve: %w", err)
case <-ctx.Done():
}
ready.Store(false)1
time.Sleep(drain)
stop, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
if err := srv.Shutdown(stop); err != nil {
return fmt.Errorf("drain: %w", err)
}
return nil
}
// Ready answers the load balancer. Liveness is a separate route that checks nothing external.
func Ready(ready *atomic.Bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if !ready.Load() {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusNoContent)
})
}
- 1The first step of a drain. A test holds a request open across it, and the request gets its 200.
Goes deeper: O2 Resilience patterns, B2 Load balancing.
How do you ship a schema change with no downtime?
One image, configured by the environment, rolled out a few copies at a time. A failed health check stops the rollout. Schema changes go expand, migrate, contract, so old and new code both work during it.
// Config comes from the environment, so one image runs in every environment.
type Config struct {
DatabaseURL string
PoolSize int32
}
// LoadConfig reports every problem at once, and a copy that cannot
// start fails its rollout.
func LoadConfig(getenv func(string) string) (Config, error) {
var problems []error
url := getenv("DATABASE_URL")
if url == "" {
problems = append(problems, errors.New("DATABASE_URL is required"))
}
size, err := strconv.ParseInt(getenv("POOL_SIZE"), 10, 32)
if err != nil || size < 1 {
problems = append(problems, fmt.Errorf("POOL_SIZE: want a positive number, got %q", getenv("POOL_SIZE")))
}
return Config{DatabaseURL: url, PoolSize: int32(size)}, errors.Join(problems...)1
}
- 1A copy with a bad config fails at start, so the rollout stops on the first copy.
-- Expand: the old code ignores a new nullable column.
SET LOCAL lock_timeout = '2s'1;
ALTER TABLE items ADD COLUMN label text;
- 1ALTER TABLE waits for a strong lock, and all later queries queue behind it. This limits that wait.
| step | old code | new code |
|---|---|---|
| Expand: add the column | Ignores it | Not running yet |
| Roll out, write both | Still serves | Uses it |
| Backfill in batches | Still serves | Uses it |
| Contract: drop the old | Gone | Uses it |
Goes deeper: O4 Change and migrations.
Traffic grows a hundred times. What do you do first?
The service holds no state now, so I add copies behind the load balancer. Reads go to replicas and the cache. I shard only when writes outgrow one primary, because a shard key is hard to change.
// ShardFor picks one of n databases from the key, so every copy agrees without a lookup.
func ShardFor(key string, n int) int {
h := fnv.New64a()
h.Write([]byte(key))
return int(h.Sum64() % uint64(n))
}
Hash mod n keeps a key only when its hash mod 4 equals its hash mod 5, which is 4 of the 20 residues. So going from 4 to 5 shards moves 80 percent of the keys, as a test on 100,000 keys confirms. A ring or fixed slots move only the new shard's share.
Goes deeper: B2 Load balancing, X2 Sharding.
How do you know that it works?
Table tests cover the rules, and -race covers memory safety. One contract test runs against MemStore and Postgres, so the swap cannot change behaviour. Load tests find the real limit before users do.
| level | finds |
|---|---|
| Table tests on the service | Wrong rules |
| The race detector | Unsafe memory access |
| Real Postgres, not a mock | Wrong SQL and wrong locks |
| Contract test, each Store | A swap that changes behaviour |
| Load test | The real limit and the slow query |
// storeContract is one test for every Store. If MemStore passes and PGStore fails, the swap broke
// a promise the service relies on.
func storeContract(t *testing.T, s Store) {
ctx := context.Background()
if _, err := s.Get(ctx, "k"); !errors.Is(err, ErrNotFound) {
t.Fatalf("absent key: got %v", err)
}
add := func(item *Item) error { item.Count++; return nil }
var wg sync.WaitGroup
for range 100 {1
wg.Go(func() {
if _, err := s.Update(ctx, "k", add); err != nil {
t.Error(err)
}
})
}
wg.Wait()
refuse := func(item *Item) error { item.Count = 999; return ErrConflict }
if _, err := s.Update(ctx, "k", refuse); !errors.Is(err, ErrConflict) {
t.Fatalf("refused update: got %v", err)
}
if item, err := s.Get(ctx, "k"); err != nil || item.Count != 100 {
t.Fatalf("got %+v, %v", item, err)
}
}
func TestStoreContract(t *testing.T) {
t.Run("memory", func(t *testing.T) { storeContract(t, NewMemStore()) })
t.Run("postgres", func(t *testing.T) { storeContract(t, NewPGStore(freshDB(t))) })
}
- 1Each Store must lose nothing under 100 parallel writers.
Goes deeper: T1 The grader.
What else worries you before launch?
Validate at the edge and cap the body size. Use TLS everywhere, keep secrets in a manager, and give the database role only the rights the service needs. Each change writes an audit row in the same transaction.
// ReadJSON caps the body and refuses a field it does not know.
func ReadJSON(w http.ResponseWriter, r *http.Request, limit int64, v any) error {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit)1)
dec.DisallowUnknownFields()
err := dec.Decode(v)
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return ErrTooLarge
}
if err != nil {
return fmt.Errorf("%w: %v", ErrInvalid, err)
}
return nil
}
- 1A large body fails here, before it fills memory. The handler maps it to 413.
// AddAudited writes the change and its audit row in one transaction, so neither exists alone.
func AddAudited(ctx context.Context, pool *pgxpool.Pool, actor, key string, by int) error {
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
tag, err := tx.Exec(ctx, `UPDATE items SET count = count + $2 WHERE key = $1 AND count + $2 <= 1000`, key, by)
if err != nil {
return fmt.Errorf("add to %s: %w", key, err)
}
if tag.RowsAffected() == 0 {
return ErrConflict
}
_, err = tx.Exec(ctx, `INSERT INTO audit1 (actor, action, key) VALUES ($1, 'add', $2)`, actor, key)
return err
})
}
- 1In the same transaction, so a change never exists without its record, and a refused change leaves no row.
Goes deeper: O5 Security.
| stop | the words to remember | |
|---|---|---|
| C | Persistence | Store interface, one new file. |
| D | Concurrency across copies | A mutex covers one process. |
| G | Transactions | What must land together. |
| H | Idempotency and retries | Claim, work, save: one transaction. |
| I | Auth | 401 is who, 403 is what. |
| J | API shape | Cursors, exact codes, /v1. |
| K | Rate limiting | One count in Redis, 429, fail open. |
| L | Caching and read scale | Delete on write, TTL as the bound. |
| M | Observability | RED per route, one log line, one ID. |
| N | Reliability | Timeouts, jitter, drain. |
| O | Deployment | One image, expand then contract. |
| P | Scaling | Copies first, shards last. |
| Q | Testing strategy | One contract, every store. |
| R | Security | Limits, least rights, audit. |
If I have this list in my head, I can always say the next thing.
- one copy
- 100 clients, final count 100.
- two copies
- 100 commits return 200, final count 50.
- a mutex each
- 100 commits return 200, and the count stays under 100.
- in the database
- 100 commits, final count 100.
- retries
- 20 parallel retries of one key: one add.
- limit
- 5 across two copies, not 5 each.
- resharding
- 4 to 5 shards by hash mod n moves 80 percent of the keys.
- page depth
- A cursor costs the same on every page. OFFSET reads every skipped row.
Counts from the tests. They show behaviour, not throughput.
0 of 10 known
You keep the mutex and swap the map for Postgres. Two copies run. Why can the count still end low?
Sticky sessions pin each client to one copy. Does that fix two copies with memory stores?
When is a conditional update better than a row lock?
A Redis lock has a TTL. The holder pauses past it. What protects the data?
You save the idempotency key after the work, in a second transaction. What can go wrong?
Another tenant asks for a key that exists. 403 or 404?
A client walks a list by OFFSET while rows are inserted. What does it see?
Each of 4 copies has a limit of 100 requests a minute in memory. What is the real limit?
On shutdown, why fail readiness before you stop the server?
Why is the metric label the route pattern and not the path?