System Design

G17

Database work

Postgres from Go, with pgx, sqlc and goose. Each rule here comes from a run against a real server, and each cost is measured. The theory lives on the design sheets; this sheet is the Go.

Not startedSaved in this browser only.
  1. 1A transaction owns one connection. Inside it, every query goes through tx and never through the pool.
  2. 2WithTx ends every path: commit on nil, rollback on an error, a panic or a canceled context.
  3. 3Serializable work can fail with 40001 at commit. Retry the whole function, so it needs no side effects.
  4. 4A pool is a queue. Set the size from max_connections, and bound the wait with a context.
G17
    A

    The trap

    one wrong receiver, 1 connection
    a query inside a transactiongo
    func main() {
      ctx, cancel := context.WithTimeout(context.Background(),
        300*time.Millisecond)
      defer cancel()
      url := os.Getenv("DATABASE_URL") + "&pool_max_conns=11"
      pool, err := pgxpool.New(ctx, url)
      if err != nil {
        panic(err)
      }
      defer pool.Close()
    
      tx, err := pool.Begin(ctx)2
      if err != nil {
        panic(err)
      }
      defer tx.Rollback(context.Background())
    
      var n int
      err = pool.QueryRow(ctx, "SELECT 1")3.Scan(&n)
      fmt.Println("n:", n)
      fmt.Println("err:", err)
    }
    1. 1One connection makes the failure certain. N callers on a pool of N fail the same way.
    2. 2The transaction takes the only connection and keeps it until it ends.
    3. 3This asks the pool for another connection, and no other exists. It waits until ctx ends.
    receiverrecorded outputstatus
    pool.QueryRown: 0 err: context deadline exceededWaits for itself
    tx.QueryRown: 1 err: <nil>Same connection
    • The bug passes every test with a large pool. It appears under load, when all connections are in transactions.
    • A test ran 4 callers on a pool of 4. Each held a transaction and asked the pool for more: all 4 timed out.
    • The pool query also runs outside the transaction, so it cannot see uncommitted rows.
    • The fix is a type: pass a dbq.DBTX or a pgx.Tx, so helper functions cannot reach the pool.

    A query on the pool inside a transaction needs a second connection. With a full pool it waits for itself, so I pass tx down.

    B

    The model: a pool

    what a connection costs
    handler 1handler 2handler 3pgxpool.Pool, MaxConns 2conn 1, in useconn 2, in useacquire queuea waiter leaves when aconn returns or ctx endsPostgresbackend 1backend 2one process eachcounts againstmax_connectionsA transaction keeps its connection until Commit or Rollback. So does an open Rows.
    • A goroutine holds a connection for one query, one open Rows or one transaction.
    • The total across replicas must stay under max_connections.
    • The wait has no timeout of its own. Only ctx ends it.

    Each connection is one server process. The pool is a bounded queue in front of them.

    C

    database/sql or pgx

    measured, loopback
    topicpgxdatabase/sql
    One row49 µs, 11 allocs63 µs, 34 allocs
    1,000 rows370 µs, 4,008 allocs646 µs, 5,681 allocs
    COPY, batches, LISTENYesNot in the API
    Arrays, jsonb, rangesNative typesThrough the driver
    Portable to other databasesNoYes
    Libraries that need *sql.DBstdlib.OpenDBFromPoolYes

    Both APIs ran through the pgx driver. The difference is the database/sql layer on top.

    I use native pgx for Postgres. I use database/sql only where a library demands it, and pgx can serve both from one pool.

    D

    The rules: pool settings

    defaults from the source of each package
    settingpgxpool defaultdatabase/sql defaultwhat to do
    Largest poolMaxConns: the greater of 4 and NumCPUSetMaxOpenConns: 0, no limitNever leave database/sql unlimited One burst can use all of max_connections.
    Idle connections keptMinConns: 0, MinIdleConns: 0SetMaxIdleConns: 2Set it near the usual load, or each burst pays for new connections.
    Oldest connectionMaxConnLifetime: 1 hSetConnMaxLifetime: 0, foreverSet 30 to 60 min. This moves traffic after a failover and frees server memory.
    Reconnect spreadMaxConnLifetimeJitter: 0NoneSet about 10% of the lifetime, so connections do not all end together.
    Longest idle timeMaxConnIdleTime: 30 minSetConnMaxIdleTime: 0, foreverSet 5 min when replicas scale up and down.
    Background checkHealthCheckPeriod: 1 minNoneKeep it short enough to find dead connections before callers do.

    A connection string can set the pgxpool fields too, for example pool_max_conns=10. What a connection costs is on B1.

    I set MaxConns from max_connections divided by replicas, and I add a lifetime with jitter, so connections do not all reconnect at once.

    E

    Every limit stated, and a full pool

    tested
    NewPoolgo
    // NewPool opens a pool with every limit stated. The pool sizes are per
    // process, so MaxConns times the replica count must fit max_connections.
    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 pool config: %w", err)
      }
      cfg.MaxConns = maxConns
      cfg.MinIdleConns = 11
      cfg.MaxConnLifetime = 30 * time.Minute
      cfg.MaxConnLifetimeJitter = 3 * time.Minute
      cfg.MaxConnIdleTime = 5 * time.Minute
      cfg.HealthCheckPeriod = 30 * time.Second
      cfg.ConnConfig.BuildContextWatcherHandler = cancelOnServer2
      cfg.ConnConfig.RuntimeParams["application_name"] = "orders-api"
      cfg.ConnConfig.RuntimeParams["statement_timeout"3] = "5000"
      cfg.ConnConfig.RuntimeParams["lock_timeout"4] = "2000"
      pool, err := pgxpool.NewWithConfig(ctx, cfg)
      if err != nil {
        return nil, fmt.Errorf("open pool: %w", err)
      }
      return pool, nil
    }
    1. 1Keeps 1 connection ready. MinConns only sets a floor on the total.
    2. 2Keeps the connection when a context ends (panel P).
    3. 3The server stops any statement after 5 s, also when the client has died.
    4. 4A query that waits 2 s on a row lock fails, so a lock queue cannot fill the pool.
    Lookupgo
    // Lookup bounds the time it waits for a connection on its own. Query time and
    // queue time then draw on one deadline, so a full pool fails fast.
    func Lookup(ctx context.Context, db *pgxpool.Pool, email string) (
      int64, error) {
      ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)1
      defer cancel()
      var id int64
      err := db.QueryRow(ctx,
        `SELECT id FROM accounts WHERE email = $1`, email).Scan(&id)
      if err != nil {
        return 0, fmt.Errorf("lookup %s: %w", email, err)
      }
      return id, nil
    }
    1. 1One deadline covers the queue and the query. Without it, this call waits as long as its parent.
    when the pool is fullpgxpooldatabase/sql
    The callWaits, then returns ctx.ErrWaits, then returns ctx.Err
    Waits that succeededEmptyAcquireCountWaitCount, every wait
    Time spent waitingEmptyAcquireWaitTimeWaitDuration
    Waits that gave upCanceledAcquireCountInside WaitCount

    Every call carries a deadline, so a full pool gives a fast error and not a pile of waiting goroutines.

    F

    See it: a burst against a pool

    recorded: each caller holds 20 ms and waits at most 200 ms
    MaxConnscallers at once

    at once 2

    waited, then served 18

    deadline in the queue 44

    median wait 111.2 ms

    longest wait 200.2 ms

    burst finished in 221 ms

    Solid: served at once. Tint: waited in the queue. Red: context deadline in the queue.

    • Queue wait grows with callers divided by pool size. Each extra caller waits for all the callers ahead of it.
    • With 2 connections and 64 callers, 44 callers hit the deadline and 20 finished.
    • A deadline protects the process. It cannot add capacity, so alert on the wait before callers fail.

    A small pool delays a burst up to the deadline, and past that callers fail. I graph wait time, because it moves before errors do.

    G

    A transaction helper

    tested: commit, error, panic, cancel
    WithTxgo
    // WithTx runs fn in a transaction. It commits when fn returns nil. It rolls
    // back on an error, on a panic, and when the context ends.
    func WithTx(ctx context.Context, db *pgxpool.Pool, opts pgx.TxOptions,
      fn func(pgx.Tx) error) (err error) {
      tx, err := db.BeginTx(ctx, opts)
      if err != nil {
        return fmt.Errorf("begin: %w", err)
      }
      defer func() {1
        c, cancel := context.WithTimeout(context.WithoutCancel(ctx)2,
          rollbackTimeout)
        defer cancel()
        rerr := tx.Rollback(c)
        if rerr != nil && !errors.Is(rerr, pgx.ErrTxClosed3) {
          err = errors.Join(err,4 fmt.Errorf("rollback: %w", rerr))
        }
      }()
      if err := fn(tx); err != nil {
        return err
      }
      if err := tx.Commit(ctx); err != nil {
        return fmt.Errorf("commit: %w", err)
      }
      return nil
    }
    1. 1Runs on every exit: a nil return, an error and a panic.
    2. 2A canceled ctx must not stop the rollback. A new timeout bounds it instead.
    3. 3The normal result after a commit, so it is not an error.
    4. 4Keeps the real failure and adds the rollback failure.
    what fn doesresultrows kept
    Returns nilCommit1
    Returns an errorRollback, error returned0
    PanicsRollback, panic continues0
    Context endsCommit fails, error returned0
    Hides a statement errorCommit returns ErrTxCommitRollback0
    • Each row is a test, and each test also checks that no connection stays held.
    • pgx.BeginTxFunc does the same work. Its rollback uses the caller's ctx, so write your own when you want the timeout above.
    • Do no network calls in fn. It holds a connection, and a retry would repeat them.

    WithTx is 15 lines. Callers cannot forget the rollback, and the deferred rollback is safe after a commit.

    H

    Isolation levels, and a real 40001

    recorded from SHOW transaction_isolation
    asked forpgx.TxOptionssql.TxOptions
    defaultread committedread committed
    read uncommittedread uncommittedread uncommitted
    read committedread committedread committed
    repeatable readrepeatable readrepeatable read
    serializableserializableserializable
    snapshotno such levelrepeatable read
    linearizableno such levelerror: unsupported isolation: 7
    write skew, a real runresult
    on call2
    on call2
    updates<nil> <nil>
    commit a<nil>
    commit bERROR: could not serialize access due to read/write dependencies among transactions (SQLSTATE 40001)
    • Postgres accepts read uncommitted and runs it as read committed. See T2 for each anomaly.
    • Both updates succeed here. The failure arrives at the second commit, so check Commit's error.
    • Fix the rule with serializable, or use the lock-based options on T5.
    WithRetrygo
    // Retryable reports a failure that a fresh run of the same work can avoid:
    // 40001 serialization_failure, or 40P01 deadlock_detected.
    func Retryable(err error) bool {
      pgErr, ok := errors.AsType[*pgconn.PgError](err)1
      return ok && (pgErr.Code == "40001" || pgErr.Code == "40P01"2)
    }
    
    // WithRetry runs fn in a SERIALIZABLE transaction. After a retryable failure
    // it runs fn again from the start. It returns the number of retries.
    func WithRetry(ctx context.Context, db *pgxpool.Pool, attempts int,
      fn func(pgx.Tx) error) (int, error) {
      opts := pgx.TxOptions{IsoLevel: pgx.Serializable}
      for attempt := 1; ; attempt++ {
        err := WithTx(ctx, db, opts, fn)3
        if err == nil {
          return attempt - 1, nil
        }
        if !Retryable(err) || attempt == attempts {
          return attempt - 1, fmt.Errorf("attempt %d: %w", attempt, err)
        }
        wait := rand.N(time.Duration(attempt) * 5 * time.Millisecond)4
        select {
        case <-time.After(wait):
        case <-ctx.Done():5
          return attempt - 1, context.Cause(ctx)
        }
      }
    }
    1. 1Go 1.26: the generic errors.As. It needs no target variable.
    2. 2A deadlock victim can also retry.
    3. 3A new transaction each time, because the failed one is gone.
    4. 4A random wait, so 2 callers do not collide again at once.
    5. 5The wait stops with the request.

    I catch 40001 with errors.AsType, wait a random time, and run the whole function again. The anomaly itself is on sheet T2.

    I

    A job queue: FOR UPDATE SKIP LOCKED

    measured: 8 workers, 120 jobs of 5 ms
    RunOnego
    // RunOne claims one ready job, does the work, and marks it done. The row
    // lock lives for the transaction, so a crash in work releases the job.
    func RunOne(ctx context.Context, db *pgxpool.Pool, worker string,
      work func(context.Context, int64) error) error {
      return WithTx(ctx, db, pgx.TxOptions{}, func(tx pgx.Tx) error {
        q := dbq.New(tx)1
        id, err := q.ClaimJob(ctx)2
        if errors.Is(err, pgx.ErrNoRows)3 {
          return ErrNoJob
        }
        if err != nil {
          return fmt.Errorf("claim: %w", err)
        }
        if err := work(ctx, id)4; err != nil {
          return fmt.Errorf("job %d: %w", id, err)
        }
        return q.FinishJob(ctx, dbq.FinishJobParams{
          ID: id, WorkedBy: &worker,
        })
      })
    }
    1. 1The generated queries run on the transaction.
    2. 2SELECT with FOR UPDATE SKIP LOCKED. It ignores rows that other workers hold.
    3. 3No free job. The caller sleeps or waits for a NOTIFY (panel O).
    4. 4The lock lasts as long as the work, so keep the work short.
    clausewhen a row is lockeddrain timestatus
    FOR UPDATEWaits for the holder889 msOne row, many writers
    FOR UPDATE SKIP LOCKEDTakes the next free row120 msQueues
    FOR UPDATE NOWAITFails with 55P03Not measuredWhen a retry is better than a wait
    Plain SELECT, then UPDATETwo workers can read one rowNot measuredDouble claim
    • Plain FOR UPDATE takes about 7 times as long here: all 8 workers line up on one row, so they run in series.
    • A test with 8 workers and 40 jobs ran each job exactly once.
    • Lock modes are on T4.

    SKIP LOCKED lets each worker take a different row. A crash releases the row, because the lock ends with the transaction.

    J

    sqlc: SQL in, typed Go out

    generated code, committed
    sqlc.yamlyaml
    version: "2"
    sql:
      - engine: postgresql
        schema: migrations1
        queries: queries.sql
        gen:
          go:
            package: dbq
            out: dbq
            sql_package: pgx/v52
            emit_pointers_for_null_types: true3
            emit_methods_with_db_argument: false
            emit_empty_slices: true
    1. 1sqlc reads the goose files, so the schema has one source.
    2. 2Generates against native pgx.
    3. 3A nullable column becomes *string, not pgtype.Text.
    queries.sqlsql
    -- name: ClaimJob :one
    SELECT id FROM jobs
    WHERE state = 'ready'
    ORDER BY id
    LIMIT 1
    FOR UPDATE SKIP LOCKED;
    generatedgo
    func (q *Queries) ClaimJob(ctx context.Context) (int64, error)1 {
      row := q.db.QueryRow(ctx, claimJob)
      var id int64
      err := row.Scan(&id)
      return id, err
    }
    1. 1The return type comes from the column type in the schema.
    generatedgo
    type DBTX interface1 {
      Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
      Query(context.Context, string, ...interface{}) (pgx.Rows, error)
      QueryRow(context.Context, string, ...interface{}) pgx.Row
      CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
      SendBatch(context.Context, *pgx.Batch) pgx.BatchResults
    }
    1. 1A pool and a transaction both satisfy this. This is how one query runs in either place.
    Opengo
    // Open creates an account and its first order in one transaction. Passing tx
    // to dbq.New moves every generated query onto the transaction's connection.
    func Open(ctx context.Context, db *pgxpool.Pool, email string, cents int64) (
      int64, error) {
      var id int64
      err := WithTx(ctx, db, pgx.TxOptions{}, func(tx pgx.Tx) error {
        q := dbq.New(tx)1
        var err error
        id, err = q.CreateAccount(ctx, dbq.CreateAccountParams{Email: email})
        if err != nil {
          return fmt.Errorf("create account: %w", err)
        }
        _, err = q.CopyOrders2(ctx, []dbq.CopyOrdersParams{
          {AccountID: id, TotalCents: cents},
        })
        if err != nil {
          return fmt.Errorf("first order: %w", err)
        }
        return nil
      })
      return id, err
    }
    1. 1The trap from panel A cannot happen: q has no route to the pool.
    2. 2A :copyfrom query. sqlc also generates :batchexec and :many.

    sqlc cannot express a query whose shape changes at run time. For an optional filter, use sqlc.narg with COALESCE, or write that one query by hand. Schema design is on D3.

    I write SQL and sqlc writes the Go. The compiler then checks each query against the schema, which an ORM does at run time.

    K

    Migrations in the binary

    tested: 4 replicas start at once
    Migratego
    // Migrate applies every pending migration. Replicas may call it at the
    // same start: an advisory lock lets one run, and the rest wait.
    func Migrate(ctx context.Context, pool *pgxpool.Pool) (int, error) {
      db := stdlib.OpenDBFromPool(pool)1
      defer closeDB(db)
    
      locker, err := lock.NewPostgresSessionLocker()2
      if err != nil {
        return 0, fmt.Errorf("session locker: %w", err)
      }
      dir, err := fs.Sub(embedded, "migrations")
      if err != nil {
        return 0, fmt.Errorf("migrations folder: %w", err)
      }
      p, err := goose.NewProvider3(goose.DialectPostgres, db, dir,
        goose.WithSessionLocker(locker))
      if err != nil {
        return 0, fmt.Errorf("goose provider: %w", err)
      }
      done, err := p.Up(ctx)
      if err != nil {
        return len(done), fmt.Errorf("migrate up: %w", err)
      }
      return len(done), nil
    }
    1. 1goose needs a *sql.DB. This wraps the same pool.
    2. 2A session advisory lock. In the test, 4 concurrent callers applied the 3 files once in total.
    3. 3The provider API takes an fs.FS, so go:embed ships the files in the binary.
    00002_orders_account_idx.sqlsql
    -- +goose NO TRANSACTION1
    
    -- +goose Up
    CREATE INDEX CONCURRENTLY IF NOT EXISTS2 orders_account_id_idx
      ON orders (account_id);
    
    -- +goose Down
    DROP INDEX CONCURRENTLY IF EXISTS orders_account_id_idx;
    1. 1CREATE INDEX CONCURRENTLY cannot run in a transaction.
    2. 2With no transaction, a failed run can leave a partial state. The file must be safe to run twice.
    rulestatus
    One change per file, reviewed like codeApproved
    Change a file that has runAdd a new file
    Run a long backfill in a migrationIt blocks deploys

    Expand and contract, and online index builds, are on O4.

    Migrations are SQL files in the binary. An advisory lock lets one replica apply them, and the others wait.

    L

    NULLs

    recorded: each cell scanned a real NULL
    Go typescan NULL, pgxscan NULL, database/sqlJSON of NULLJSON of "x"status
    stringcan't scan into dest[0] (col: text): cannot scan NULL into *stringsql: Scan error on column index 0, name "text": converting NULL to string is unsupported"""x"Fails on NULL
    *stringreads as nullreads as nullnull"x"Default choice
    sql.NullStringreads as nullreads as null{"String":"","Valid":false}{"String":"x","Valid":true}Not in JSON structs
    sql.Null[string]reads as nullreads as null{"V":"","Valid":false}{"V":"x","Valid":true}Not in JSON structs
    pgtype.Textreads as nullreads as nullnull"x"pgx only

    sql.Null[T] is new in Go 1.22 and works for any type. For a column that is never NULL, say NOT NULL in the schema and use the plain type. COALESCE in the query is another way out.

    I use a pointer for a nullable column. It reads NULL on both drivers and encodes to JSON null with no extra code.

    M

    Bulk writes, measured

    5,000 rows, median of 5 interleaved rounds
    rows per second, loopback1k10k100kINSERT, one transaction each: 5,472 rows/sINSERT, one transaction each5,472INSERT, all in one transaction: 14,310 rows/sINSERT, all in one transaction14,310pgx.Batch: 50,795 rows/spgx.Batch50,795multi-row VALUES: 117,498 rows/smulti-row VALUES117,498unnest arrays: 134,895 rows/sunnest arrays134,895CopyFrom: 120,378 rows/sCopyFrom120,378rows/s, log scale
    methodtimerateone failure means
    INSERT, one transaction each914 ms5.5k rows/sEarlier rows stay
    INSERT, all in one transaction349 ms14.3k rows/sAll rows roll back
    pgx.Batch98.4 ms50.8k rows/sAll rows roll back
    multi-row VALUES42.6 ms117.5k rows/sAll rows roll back
    unnest arrays37.1 ms134.9k rows/sAll rows roll back
    CopyFrom41.5 ms120.4k rows/sAll rows roll back
    three bulk pathsgo
    // loadBatch queues every statement and sends them in one round trip.
    func loadBatch(ctx context.Context, db *pgxpool.Pool, rows []Row) error {
      b := &pgx.Batch{}1
      for _, r := range rows {
        b.Queue(insertOrder, r.Account, r.Cents)
      }
      return db.SendBatch(ctx, b).Close()
    }
    
    // loadUnnest sends one statement with two array parameters.
    func loadUnnest(ctx context.Context, db *pgxpool.Pool, rows []Row) error {
      ids := make([]int64, len(rows))
      cents := make([]int64, len(rows))
      for i, r := range rows {
        ids[i], cents[i] = r.Account, r.Cents
      }
      _, err := db.Exec(ctx, `
        INSERT INTO orders (account_id, total_cents)
        SELECT * FROM unnest($1::bigint[], $2::bigint[])2`, ids, cents)
      return err
    }
    
    // LoadCopy streams rows through the COPY protocol. Each row is binary.
    func LoadCopy(ctx context.Context, db *pgxpool.Pool, rows []Row) error {
      n, err := db.CopyFrom(ctx,3
        pgx.Identifier{"orders"},
        []string{"account_id", "total_cents"},
        pgx.CopyFromSlice(len(rows), func(i int) ([]any, error) {
          return []any{rows[i].Account, rows[i].Cents}, nil
        }))
      if err != nil {
        return fmt.Errorf("copy after %d rows: %w", n, err)
      }
      return nil
    }
    1. 1Many statements in 1 round trip. Use it when the statements differ.
    2. 2One statement and 2 parameters. It can add ON CONFLICT and RETURNING, which COPY cannot.
    3. 3The binary COPY protocol. It has no ON CONFLICT, so load into a temporary table first when rows can clash.

    Multi-row VALUES has a limit: the protocol carries at most 65,535 parameters, so 3 columns allow 21,845 rows. A test confirms the limit. The commit cost depends on the disk, so the first bar moves most between machines.

    For a bulk load I use CopyFrom. It wrote about 22 times as fast as one transaction per row on this machine.

    N

    The N+1 query

    100 accounts, 3 orders each
    two reportsgo
    // ReportN1 runs one query for the accounts and one more per account.
    func ReportN1(ctx context.Context, q *dbq.Queries) ([]Report, error) {
      accounts, err := q.ListAccounts(ctx)
      if err != nil {
        return nil, fmt.Errorf("accounts: %w", err)
      }
      out := make([]Report, 0, len(accounts))
      for _, a := range accounts {
        orders, err := q.OrdersByAccount(ctx, a.ID)1
        if err != nil {
          return nil, fmt.Errorf("orders of %d: %w", a.ID, err)
        }
        out = append(out, Report{a, orders})
      }
      return out, nil
    }
    
    // ReportAny runs 2 queries, however many accounts exist. A sorted result
    // and one pass over it replace the loop of queries.
    func ReportAny(ctx context.Context, q *dbq.Queries) ([]Report, error) {
      accounts, err := q.ListAccounts(ctx)
      if err != nil {
        return nil, fmt.Errorf("accounts: %w", err)
      }
      ids := make([]int64, len(accounts))
      out := make([]Report, len(accounts))
      at := make(map[int64]int, len(accounts))
      for i, a := range accounts {
        ids[i], out[i].Account, at[a.ID] = a.ID, a, i
      }
      orders, err := q.OrdersByAccounts(ctx, ids)2
      if err != nil {
        return nil, fmt.Errorf("orders: %w", err)
      }
      for _, o := range orders {
        r := &out[at[o.AccountID]]
        r.Orders = append(r.Orders, o)
      }
      return out, nil
    }
    1. 1One query per account, inside the loop.
    2. 2One query for all accounts: WHERE account_id = ANY($1).
    methodstatementsround tripsloopbackat 1 ms per trip
    N+1 loop1011016.4 ms+101 ms
    pgx.Batch10121.3 ms+2 ms
    = ANY($1)220.4 ms+2 ms
    JOIN110.3 ms+1 ms
    • Counts are exact, from a pgx tracer on the connection. A test fails if they change.
    • The last column is derived: round trips times 1 ms, the order of a network hop between hosts.
    • pgx.Batch keeps 101 statements and saves round trips. The server still runs each one.
    • Use JOIN for one report. Use ANY when the two rows have different shapes or a child table is large.

    An N+1 shows as statement count and not as an error. I count statements in a test, so it fails when a loop adds a query.

    O

    LISTEN and NOTIFY

    tested: the listener is killed mid-run
    Listengo
    // Listen calls wake once on each connect and once per notification. A
    // connection owns its LISTEN, so this holds one outside the pool. A
    // notification sent during a reconnect is lost, so wake must read the table.
    func Listen(ctx context.Context, url, channel string,
      wake func(ctx context.Context, payload string) error) error {
      for {
        err := listenOnce(ctx, url, channel, wake)
        if ctx.Err() != nil {
          return context.Cause(ctx)
        }
        if _, fatal := errors.AsType[*wakeError](err); fatal {
          return err
        }
        select {
        case <-time.After(reconnectWait):
        case <-ctx.Done():
          return context.Cause(ctx)
        }
      }
    }
    
    func listenOnce(ctx context.Context, url, channel string,
      wake func(context.Context, string) error) error {
      conn, err := pgx.Connect(ctx, url)1
      if err != nil {
        return fmt.Errorf("connect: %w", err)
      }
      defer closeConn(conn)
      id := pgx.Identifier{channel}.Sanitize()
      if _, err := conn.Exec(ctx, "LISTEN "+id); err != nil {
        return fmt.Errorf("listen: %w", err)
      }
      if err := wake(ctx, "")2; err != nil {
        return &wakeError{err}
      }
      for {
        n, err := conn.WaitForNotification(ctx)3
        if err != nil {
          return fmt.Errorf("wait: %w", err)
        }
        if err := wake(ctx, n.Payload); err != nil {
          return &wakeError{err}
        }
      }
    }
    1. 1A dedicated connection. A pooled one goes back to the pool, and its LISTEN goes with it.
    2. 2Runs after each connect, so rows written during the gap are found here.
    3. 3Blocks until a notification or until ctx ends. The connection does nothing else.
    factresult
    NOTIFY in a transaction that rolls backNothing is sent
    Same payload twice in one transactionOne delivery
    Listener offlineLost: Postgres keeps nothing for it
    Payload sizeUnder 8,000 bytes (PostgreSQL docs). Send an ID.
    Transaction-mode connection poolerLISTEN needs a direct connection
    • Use it to wake workers at once, with a poll as the fallback.
    • The test killed the backend with pg_terminate_backend, wrote a job, and the reconnect found it.

    NOTIFY is a wake-up, not a queue. It is lost during a reconnect, so the listener reads the table after every connect.

    P

    Cancel mid-query

    recorded: a 3 s query, 100 ms deadline
    cancelOnServergo
    // cancelOnServer makes a canceled context stop the query, not the connection.
    // pgx sends a cancel request at once. The server replies with 57014, and the
    // connection stays usable. After 2 s with no reply, pgx falls back to a
    // deadline on the socket.
    func cancelOnServer(c *pgconn.PgConn) ctxwatch.Handler {
      return &pgconn.CancelRequestContextWatcherHandler{
        Conn:               c,
        CancelRequestDelay: 01,
        DeadlineDelay:      2 * time.Second2,
      }
    }
    1. 1Send the cancel request as soon as ctx ends.
    2. 2If the server never answers, a socket deadline ends the wait.
    handlererrorconnectionbackend afterreturn
    defaulttimeout: context deadline exceededClosedgone101 ms
    cancel requestERROR: canceling statement due to user request (SQLSTATE 57014)Keptidle207 ms
    • The default returns at the deadline and stops the backend too, at the cost of a new connection.
    • The cancel request returns when the server answers. That took 207 ms here.
    • At scale, a burst of timeouts with the default closes many connections, and the pool must rebuild them.
    • database/sql with the pgx driver takes the same setting through the connection config.

    By default pgx closes the connection on cancel. I set the cancel request handler, so the pool keeps the connection and I get 57014.

    Q

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.21context.WithoutCancel.A rollback survives a canceled request.
    1.22sql.Null[T], for any column type.No more one wrapper type per column type.
    1.23Errors from a driver.Valuer are wrapped in database/sql calls.errors.Is and errors.As see them.
    1.26errors.AsType, the generic form of errors.As.One line to read a SQLSTATE. It is type-safe and faster.
    1.27sql.ConvertAssign and driver.RowsColumnScanner.Drivers can use the conversions of Rows.Scan, and scan directly into your variables.
    R

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildThe store is in memory, behind an interface.Say which methods become one transaction. That choice shapes the interface.
    buildTwo writes must succeed together.In memory, hold the mutex across both. Name WithTx as the production version.
    talk"Move this store to Postgres."Show the schema, then WithTx, then pass tx through a DBTX. Mention the trap in panel A.
    talk"What if two requests update one row?"Choose: a row lock (T4), serializable with retry (T2), or an atomic UPDATE. Say which fits.
    talk"The API gets slow under load."Check acquire wait first. A full pool looks like slow SQL from the handler.
    talk"How do you run background jobs?"SKIP LOCKED in a transaction, with a NOTIFY to wake workers and a poll as the fallback.
    talk"How do you deploy schema changes?"Embedded goose files, one advisory lock, and expand and contract for anything a running version reads.

    I keep SQL in sqlc, transactions in one helper, and I can say which connection each query uses.

    S

    Drill

    each answer is the output of a real run

    0 of 12 known

    1. Predict the output. The pool has 1 connection, and the program reads one row.

      package main
      
      import (
        "context"
        "fmt"
        "os"
        "time"
      
        "github.com/jackc/pgx/v5/pgxpool"
      )
      
      func main() {
        ctx := context.Background()
        url := os.Getenv("DATABASE_URL") + "&pool_max_conns=1"
        pool, err := pgxpool.New(ctx, url)
        if err != nil {
          panic(err)
        }
        defer pool.Close()
      
        rows, err := pool.Query(ctx, "SELECT generate_series(1, 3)")
        if err != nil {
          panic(err)
        }
        rows.Next()
      
        short, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
        defer cancel()
        var n int
        err = pool.QueryRow(short, "SELECT 7").Scan(&n)
        fmt.Println("before Close:", n, err)
      
        rows.Close()
        err = pool.QueryRow(ctx, "SELECT 7").Scan(&n)
        fmt.Println("after Close:", n, err)
      }
    2. Predict the output. The loop stops early. Why?

      package main
      
      import (
        "context"
        "fmt"
        "os"
      
        "github.com/jackc/pgx/v5"
      )
      
      func main() {
        ctx := context.Background()
        conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
        if err != nil {
          panic(err)
        }
        defer conn.Close(ctx)
      
        rows, err := conn.Query(ctx,
          "SELECT 10 / (3 - g) FROM generate_series(1, 5) g")
        fmt.Println("Query:", err)
        defer rows.Close()
        for rows.Next() {
          var v int
          if err := rows.Scan(&v); err != nil {
            panic(err)
          }
          fmt.Println(v)
        }
        fmt.Println("Err:", rows.Err())
      }
    3. Predict the output. The first error is not handled.

      package main
      
      import (
        "context"
        "fmt"
        "os"
      
        "github.com/jackc/pgx/v5"
      )
      
      func main() {
        ctx := context.Background()
        conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
        if err != nil {
          panic(err)
        }
        defer conn.Close(ctx)
      
        tx, err := conn.Begin(ctx)
        if err != nil {
          panic(err)
        }
        _, err = tx.Exec(ctx, "SELECT 1 / 0")
        fmt.Println("first:", err)
        _, err = tx.Exec(ctx, "SELECT 1")
        fmt.Println("second:", err)
        fmt.Println("commit:", tx.Commit(ctx))
      }
    4. Predict the output.

      package main
      
      import (
        "context"
        "fmt"
        "os"
      
        "github.com/jackc/pgx/v5"
      )
      
      func main() {
        ctx := context.Background()
        conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
        if err != nil {
          panic(err)
        }
        defer conn.Close(ctx)
      
        tx, err := conn.Begin(ctx)
        if err != nil {
          panic(err)
        }
        fmt.Println("commit:", tx.Commit(ctx))
        fmt.Println("rollback:", tx.Rollback(ctx))
      }
    5. Predict the output.

      package main
      
      import (
        "context"
        "database/sql"
        "fmt"
        "os"
      
        "github.com/jackc/pgx/v5"
      )
      
      func main() {
        ctx := context.Background()
        conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
        if err != nil {
          panic(err)
        }
        defer conn.Close(ctx)
      
        var s string
        err = conn.QueryRow(ctx, "SELECT NULL::text").Scan(&s)
        fmt.Println("string:", err)
      
        var p *string
        err = conn.QueryRow(ctx, "SELECT NULL::text").Scan(&p)
        fmt.Println("*string:", p == nil, err)
      
        var n sql.Null[string]
        err = conn.QueryRow(ctx, "SELECT NULL::text").Scan(&n)
        fmt.Println("sql.Null:", n.Valid, err)
      }
    6. Predict the output.

      package main
      
      import (
        "database/sql"
        "encoding/json"
        "fmt"
      
        "github.com/jackc/pgx/v5/pgtype"
      )
      
      func main() {
        v := struct {
          A sql.NullString
          B sql.Null[string]
          C *string
          D pgtype.Text
        }{}
        out, err := json.Marshal(v)
        if err != nil {
          panic(err)
        }
        fmt.Println(string(out))
      }
    7. Predict the output. No row matches any statement.

      package main
      
      import (
        "context"
        "database/sql"
        "errors"
        "fmt"
        "os"
      
        "github.com/jackc/pgx/v5"
      )
      
      func main() {
        ctx := context.Background()
        conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
        if err != nil {
          panic(err)
        }
        defer conn.Close(ctx)
      
        none := "SELECT 1 WHERE false"
        var n int
        err = conn.QueryRow(ctx, none).Scan(&n)
        fmt.Println("QueryRow:", err)
        fmt.Println("is pgx.ErrNoRows:", errors.Is(err, pgx.ErrNoRows))
        fmt.Println("is sql.ErrNoRows:", errors.Is(err, sql.ErrNoRows))
      
        rows, err := conn.Query(ctx, none)
        fmt.Println("Query:", err)
        rows.Close()
      
        tag, err := conn.Exec(ctx,
          "DELETE FROM accounts WHERE email = 'nobody'")
        fmt.Println("Exec:", tag.RowsAffected(), err)
      }
    8. Predict the output.

      package main
      
      import (
        "context"
        "fmt"
        "os"
      
        "github.com/jackc/pgx/v5"
      )
      
      func main() {
        ctx := context.Background()
        conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
        if err != nil {
          panic(err)
        }
        defer conn.Close(ctx)
      
        ids := []int{2, 4}
        var n int
        in := "SELECT count(*) FROM generate_series(1, 5) g WHERE g IN ($1)"
        err = conn.QueryRow(ctx, in, ids).Scan(&n)
        fmt.Println("IN:", n, err)
      
        anyOf := "SELECT count(*) FROM generate_series(1, 5) g WHERE g = ANY($1)"
        err = conn.QueryRow(ctx, anyOf, ids).Scan(&n)
        fmt.Println("ANY:", n, err)
      }
    9. Predict the output. The batch has no transaction around it.

      package main
      
      import (
        "context"
        "fmt"
        "os"
      
        "github.com/jackc/pgx/v5"
      )
      
      func main() {
        ctx := context.Background()
        conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
        if err != nil {
          panic(err)
        }
        defer conn.Close(ctx)
      
        _, err = conn.Exec(ctx, "CREATE TEMP TABLE t (id int PRIMARY KEY)")
        if err != nil {
          panic(err)
        }
        b := &pgx.Batch{}
        b.Queue("INSERT INTO t VALUES (1)")
        b.Queue("INSERT INTO t VALUES (2)")
        b.Queue("INSERT INTO t VALUES (2)")
        fmt.Println("close:", conn.SendBatch(ctx, b).Close())
      
        var count int
        err = conn.QueryRow(ctx, "SELECT count(*) FROM t").Scan(&count)
        fmt.Println("rows in t:", count, err)
      }
    10. Predict the output. Row 3 is a duplicate.

      package main
      
      import (
        "context"
        "errors"
        "fmt"
        "os"
      
        "github.com/jackc/pgx/v5"
        "github.com/jackc/pgx/v5/pgconn"
      )
      
      func main() {
        ctx := context.Background()
        conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
        if err != nil {
          panic(err)
        }
        defer conn.Close(ctx)
      
        _, err = conn.Exec(ctx, "CREATE TEMP TABLE t (id int PRIMARY KEY)")
        if err != nil {
          panic(err)
        }
        rows := [][]any{{1}, {2}, {2}, {3}}
        n, err := conn.CopyFrom(ctx, pgx.Identifier{"t"}, []string{"id"},
          pgx.CopyFromRows(rows))
        pgErr, ok := errors.AsType[*pgconn.PgError](err)
        if !ok {
          panic(err)
        }
        fmt.Println("copied:", n, pgErr.Code)
      
        var count int
        err = conn.QueryRow(ctx, "SELECT count(*) FROM t").Scan(&count)
        fmt.Println("rows in t:", count, err)
      }
    11. Predict the output. The first transaction rolls back, and the second sends x, x, y.

      package main
      
      import (
        "context"
        "fmt"
        "os"
        "time"
      
        "github.com/jackc/pgx/v5"
      )
      
      func main() {
        ctx := context.Background()
        url := os.Getenv("DATABASE_URL")
        a, err := pgx.Connect(ctx, url)
        if err != nil {
          panic(err)
        }
        defer a.Close(ctx)
        b, err := pgx.Connect(ctx, url)
        if err != nil {
          panic(err)
        }
        defer b.Close(ctx)
      
        if _, err := a.Exec(ctx, "LISTEN jobs"); err != nil {
          panic(err)
        }
        send := func(end string, payloads ...string) {
          tx := `BEGIN;`
          for _, p := range payloads {
            tx += ` NOTIFY jobs, '` + p + `';`
          }
          if _, err := b.Exec(ctx, tx+end); err != nil {
            panic(err)
          }
        }
        send("ROLLBACK", "lost")
        send("COMMIT", "x", "x", "y")
      
        for {
          wait, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
          n, err := a.WaitForNotification(wait)
          cancel()
          if err != nil {
            fmt.Println("no more")
            return
          }
          fmt.Println("got:", n.Payload)
        }
      }
    12. Predict the output. This connection uses the pgx default.

      package main
      
      import (
        "context"
        "fmt"
        "os"
        "time"
      
        "github.com/jackc/pgx/v5"
      )
      
      func main() {
        ctx := context.Background()
        conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
        if err != nil {
          panic(err)
        }
        defer conn.Close(ctx)
      
        short, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
        defer cancel()
        _, err = conn.Exec(short, "SELECT pg_sleep(1)")
        fmt.Println("err:", err)
        fmt.Println("closed:", conn.IsClosed())
      }
    T

    Numbers to say

    measured
    one query
    49 µs on pgx over loopback.
    database/sql
    34 allocs against 11 per query.
    COPY
    120.4k rows/s, about 22 times a commit per row.
    SKIP LOCKED
    7 times the plain FOR UPDATE rate with 8 workers.
    N+1
    101 statements against 1; 6.4 ms against 0.3 ms.
    parameters
    At most 65,535 per statement.

    Go 1.27.3, Postgres 16.14 on the same host, 8-core Intel i9 laptop, GOMAXPROCS 16, medians, on a busy machine. Use these as orders of magnitude.