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.
- 1A transaction owns one connection. Inside it, every query goes through tx and never through the pool.
- 2WithTx ends every path: commit on nil, rollback on an error, a panic or a canceled context.
- 3Serializable work can fail with 40001 at commit. Retry the whole function, so it needs no side effects.
- 4A pool is a queue. Set the size from max_connections, and bound the wait with a context.
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)
}- 1One connection makes the failure certain. N callers on a pool of N fail the same way.
- 2The transaction takes the only connection and keeps it until it ends.
- 3This asks the pool for another connection, and no other exists. It waits until ctx ends.
| receiver | recorded output | status |
|---|---|---|
| pool.QueryRow | n: 0 err: context deadline exceeded | Waits for itself |
| tx.QueryRow | n: 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.
- 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.
| topic | pgx | database/sql |
|---|---|---|
| One row | 49 µs, 11 allocs | 63 µs, 34 allocs |
| 1,000 rows | 370 µs, 4,008 allocs | 646 µs, 5,681 allocs |
| COPY, batches, LISTEN | Yes | Not in the API |
| Arrays, jsonb, ranges | Native types | Through the driver |
| Portable to other databases | No | Yes |
| Libraries that need *sql.DB | stdlib.OpenDBFromPool | Yes |
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.
| setting | pgxpool default | database/sql default | what to do |
|---|---|---|---|
| Largest pool | MaxConns: the greater of 4 and NumCPU | SetMaxOpenConns: 0, no limit | Never leave database/sql unlimited One burst can use all of max_connections. |
| Idle connections kept | MinConns: 0, MinIdleConns: 0 | SetMaxIdleConns: 2 | Set it near the usual load, or each burst pays for new connections. |
| Oldest connection | MaxConnLifetime: 1 h | SetConnMaxLifetime: 0, forever | Set 30 to 60 min. This moves traffic after a failover and frees server memory. |
| Reconnect spread | MaxConnLifetimeJitter: 0 | None | Set about 10% of the lifetime, so connections do not all end together. |
| Longest idle time | MaxConnIdleTime: 30 min | SetConnMaxIdleTime: 0, forever | Set 5 min when replicas scale up and down. |
| Background check | HealthCheckPeriod: 1 min | None | Keep 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.
// 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
}- 1Keeps 1 connection ready. MinConns only sets a floor on the total.
- 2Keeps the connection when a context ends (panel P).
- 3The server stops any statement after 5 s, also when the client has died.
- 4A query that waits 2 s on a row lock fails, so a lock queue cannot fill the pool.
// 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
}- 1One deadline covers the queue and the query. Without it, this call waits as long as its parent.
| when the pool is full | pgxpool | database/sql |
|---|---|---|
| The call | Waits, then returns ctx.Err | Waits, then returns ctx.Err |
| Waits that succeeded | EmptyAcquireCount | WaitCount, every wait |
| Time spent waiting | EmptyAcquireWaitTime | WaitDuration |
| Waits that gave up | CanceledAcquireCount | Inside WaitCount |
Every call carries a deadline, so a full pool gives a fast error and not a pile of waiting goroutines.
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.
// 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
}- 1Runs on every exit: a nil return, an error and a panic.
- 2A canceled ctx must not stop the rollback. A new timeout bounds it instead.
- 3The normal result after a commit, so it is not an error.
- 4Keeps the real failure and adds the rollback failure.
| what fn does | result | rows kept |
|---|---|---|
| Returns nil | Commit | 1 |
| Returns an error | Rollback, error returned | 0 |
| Panics | Rollback, panic continues | 0 |
| Context ends | Commit fails, error returned | 0 |
| Hides a statement error | Commit returns ErrTxCommitRollback | 0 |
- 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.
| asked for | pgx.TxOptions | sql.TxOptions |
|---|---|---|
| default | read committed | read committed |
| read uncommitted | read uncommitted | read uncommitted |
| read committed | read committed | read committed |
| repeatable read | repeatable read | repeatable read |
| serializable | serializable | serializable |
| snapshot | no such level | repeatable read |
| linearizable | no such level | error: unsupported isolation: 7 |
| write skew, a real run | result |
|---|---|
| on call | 2 |
| on call | 2 |
| updates | <nil> <nil> |
| commit a | <nil> |
| commit b | ERROR: could not serialize access due to read/write dependencies among transactions (SQLSTATE 40001) |
// 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)
}
}
}- 1Go 1.26: the generic errors.As. It needs no target variable.
- 2A deadlock victim can also retry.
- 3A new transaction each time, because the failed one is gone.
- 4A random wait, so 2 callers do not collide again at once.
- 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.
// 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,
})
})
}- 1The generated queries run on the transaction.
- 2SELECT with FOR UPDATE SKIP LOCKED. It ignores rows that other workers hold.
- 3No free job. The caller sleeps or waits for a NOTIFY (panel O).
- 4The lock lasts as long as the work, so keep the work short.
| clause | when a row is locked | drain time | status |
|---|---|---|---|
| FOR UPDATE | Waits for the holder | 889 ms | One row, many writers |
| FOR UPDATE SKIP LOCKED | Takes the next free row | 120 ms | Queues |
| FOR UPDATE NOWAIT | Fails with 55P03 | Not measured | When a retry is better than a wait |
| Plain SELECT, then UPDATE | Two workers can read one row | Not measured | Double 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.
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- 1sqlc reads the goose files, so the schema has one source.
- 2Generates against native pgx.
- 3A nullable column becomes *string, not pgtype.Text.
-- name: ClaimJob :one
SELECT id FROM jobs
WHERE state = 'ready'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;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
}- 1The return type comes from the column type in the schema.
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
}- 1A pool and a transaction both satisfy this. This is how one query runs in either place.
// 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
}- 1The trap from panel A cannot happen: q has no route to the pool.
- 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.
// 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
}- 1goose needs a *sql.DB. This wraps the same pool.
- 2A session advisory lock. In the test, 4 concurrent callers applied the 3 files once in total.
- 3The provider API takes an fs.FS, so go:embed ships the files in the binary.
-- +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;- 1CREATE INDEX CONCURRENTLY cannot run in a transaction.
- 2With no transaction, a failed run can leave a partial state. The file must be safe to run twice.
| rule | status |
|---|---|
| One change per file, reviewed like code | Approved |
| Change a file that has run | Add a new file |
| Run a long backfill in a migration | It 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.
| Go type | scan NULL, pgx | scan NULL, database/sql | JSON of NULL | JSON of "x" | status |
|---|---|---|---|---|---|
| string | can't scan into dest[0] (col: text): cannot scan NULL into *string | sql: Scan error on column index 0, name "text": converting NULL to string is unsupported | "" | "x" | Fails on NULL |
| *string | reads as null | reads as null | null | "x" | Default choice |
| sql.NullString | reads as null | reads as null | {"String":"","Valid":false} | {"String":"x","Valid":true} | Not in JSON structs |
| sql.Null[string] | reads as null | reads as null | {"V":"","Valid":false} | {"V":"x","Valid":true} | Not in JSON structs |
| pgtype.Text | reads as null | reads as null | null | "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.
| method | time | rate | one failure means |
|---|---|---|---|
| INSERT, one transaction each | 914 ms | 5.5k rows/s | Earlier rows stay |
| INSERT, all in one transaction | 349 ms | 14.3k rows/s | All rows roll back |
| pgx.Batch | 98.4 ms | 50.8k rows/s | All rows roll back |
| multi-row VALUES | 42.6 ms | 117.5k rows/s | All rows roll back |
| unnest arrays | 37.1 ms | 134.9k rows/s | All rows roll back |
| CopyFrom | 41.5 ms | 120.4k rows/s | All rows roll back |
// 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
}- 1Many statements in 1 round trip. Use it when the statements differ.
- 2One statement and 2 parameters. It can add ON CONFLICT and RETURNING, which COPY cannot.
- 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.
// 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
}- 1One query per account, inside the loop.
- 2One query for all accounts: WHERE account_id = ANY($1).
| method | statements | round trips | loopback | at 1 ms per trip |
|---|---|---|---|---|
| N+1 loop | 101 | 101 | 6.4 ms | +101 ms |
| pgx.Batch | 101 | 2 | 1.3 ms | +2 ms |
| = ANY($1) | 2 | 2 | 0.4 ms | +2 ms |
| JOIN | 1 | 1 | 0.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.
// 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}
}
}
}- 1A dedicated connection. A pooled one goes back to the pool, and its LISTEN goes with it.
- 2Runs after each connect, so rows written during the gap are found here.
- 3Blocks until a notification or until ctx ends. The connection does nothing else.
| fact | result |
|---|---|
| NOTIFY in a transaction that rolls back | Nothing is sent |
| Same payload twice in one transaction | One delivery |
| Listener offline | Lost: Postgres keeps nothing for it |
| Payload size | Under 8,000 bytes (PostgreSQL docs). Send an ID. |
| Transaction-mode connection pooler | LISTEN 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.
// 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,
}
}- 1Send the cancel request as soon as ctx ends.
- 2If the server never answers, a socket deadline ends the wait.
| handler | error | connection | backend after | return |
|---|---|---|---|---|
| default | timeout: context deadline exceeded | Closed | gone | 101 ms |
| cancel request | ERROR: canceling statement due to user request (SQLSTATE 57014) | Kept | idle | 207 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.
| since | what changed | what it means here |
|---|---|---|
| 1.21 | context.WithoutCancel. | A rollback survives a canceled request. |
| 1.22 | sql.Null[T], for any column type. | No more one wrapper type per column type. |
| 1.23 | Errors from a driver.Valuer are wrapped in database/sql calls. | errors.Is and errors.As see them. |
| 1.26 | errors.AsType, the generic form of errors.As. | One line to read a SQLSTATE. It is type-safe and faster. |
| 1.27 | sql.ConvertAssign and driver.RowsColumnScanner. | Drivers can use the conversions of Rows.Scan, and scan directly into your variables. |
| when | the moment | what to do or say |
|---|---|---|
| build | The store is in memory, behind an interface. | Say which methods become one transaction. That choice shapes the interface. |
| build | Two 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.
0 of 12 known
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) }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()) }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)) }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)) }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) }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)) }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) }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) }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) }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) }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) } }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()) }
- 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.