Practices
These are the habits Kronor follows to keep a busy PostgreSQL database fast under load and keep the code around it simple. Most of them are enforced somewhere, in a type, a role setting, a template or a CI check, rather than left to memory.
Logic in the database
Put rules where every writer has to pass through them. Constraints, domains, generated columns, views, functions, triggers and statecharts hold the business logic; services call a narrow set of functions and read views. A rule in one service is a rule every other service can break, and a rule in the database is checked in the same transaction as the write it guards. Database design sets out the order to prefer them in.
Write SQL function bodies in SQL-standard form where the body is plain SQL. A begin atomic body is parsed when the function is created, so a missing column fails the deploy instead of the first call, and PostgreSQL records what the function depends on:
create or replace function billing.invoice_total(invoice_id bigint)
returns numeric
language sql stable
begin atomic
select sum(amount)
from billing.invoice_line l
where l.invoice_id = invoice_total.invoice_id;
end;
Serializable, always
Every transaction that writes runs at SERIALIZABLE. It is what makes read-modify-write logic correct without anyone having to think about it: two transactions that would interleave badly cannot both commit. Code that would otherwise take an advisory lock or a select … for update to protect a check-then-write relies on the isolation level instead, and a reviewer does not have to reason about every possible interleaving.
Set it in the one function every write goes through, so no call site can choose differently. A role default is a useful backstop for anything that connects without that function, such as psql:
alter role app set default_transaction_isolation = 'serializable';
Two kinds of transaction are better off at a lower level. Make each one a separate, named function, and say why in its documentation, so it is never picked by accident:
- Backfill batches run at
READ COMMITTED. A thousand-rowupdateatSERIALIZABLEtakes a thousand predicate locks. Pastmax_pred_locks_per_transaction, PostgreSQL turns them into page and relation locks, and unrelated production transactions on the same table start failing. A batch is safe without serializable because each one owns its key range and is idempotent. - Reads from a hot standby run at
REPEATABLE READ, because a standby refusesSERIALIZABLE.
Raise max_pred_locks_per_transaction well above its default of 64, to 1024 for example, so ordinary transactions do not reach that escalation.
Retry what lost a race
Retry a transaction that fails with SQLSTATE 40001 (serialization failure) or 40P01 (deadlock), automatically, in the same function that set the isolation level. Both mean the transaction lost a race and nothing it did survived, so running it again is safe. Callers never see them.
retrying :: Transaction a -> Session a
retrying transaction = attempt 0
where
attempt n =
catchError (run transaction) \err ->
case sqlState err of
Just code | code `elem` ["40001", "40P01"] -> do
liftIO do
logWarning (retryMessage (n + 1) code)
threadDelay =<< randomRIO (0, maxDelay n)
attempt (n + 1)
_ -> throwError err
-- microseconds: uniform in [0, min 30 ms (3 ms * 2^n)]
maxDelay n = min 30_000 (3_000 * 2 ^ min 4 n)
In Haskell, hasql-transaction does this for you: its transaction session retries on 40001 and 40P01 until the transaction commits. It retries at once, though, without waiting between attempts. To add the randomized wait and the log line, wrap transactionNoRetry, which runs the transaction once, as above.
- Randomize the wait. A fixed backoff puts the two transactions that just conflicted back in step, and they conflict again.
- Do not cap the attempts. The work has to happen; the request's own timeout is the bound.
- Log every retry, but do not alert on it. The warning makes contention visible on a dashboard. An alert on
40001fires on something that already healed. - Retry infrastructure errors separately and more carefully. A dropped connection or a failover may have happened after the commit, so only writes that are safe to replay, or carry an idempotency key, retry those, a few times with jitter. An exhausted pool is not retried: waiting longer would only make it worse.
No side effects in a transaction
Never call another system from application code while a transaction is open. No HTTP request, no email, no message to an external broker. There are three reasons:
- The retry above runs the transaction body again, so a side effect inside it happens twice.
- If the transaction rolls back, the call cannot be taken back: the provider charged the card, but the database has no payment.
- While the call waits on the network, the transaction holds its row locks and its snapshot, so other writers queue behind it and vacuum cannot clean up.
Make it impossible rather than discouraged. In Haskell, write transactions as values of hasql's Transaction type, which cannot perform IO, so an HTTP call inside one does not compile. In other languages, keep the transaction in a function that takes only the database handle.
Instead, the transaction records what has to happen, and something else does it after the commit:
- Enqueue a job in the same transaction as the data it is about (below). A request that starts a payment writes the payment and its job, commits, and returns; a worker calls the provider.
- Queue messages in the database, in a table or a pgmq queue, and let a worker deliver them. Statechart callbacks work this way: they run inside the transaction, so they only ever queue.
- When the database must hold a reference to something written elsewhere, write the external side first, idempotently, then commit the reference. A crash in between leaves an unused item outside, which is harmless, rather than a reference to nothing.
Work queues
Keep the job queue in PostgreSQL, so a job commits or rolls back with the data that caused it. Three habits make it safe to run many workers:
- Claim with
for update skip locked. Each worker takes rows nobody else holds, without waiting:with available as ( select id from job_queue.payload order by priority desc for update skip locked limit 10 ) delete from job_queue.payload p using available a where p.id = a.id returning p.*; - Wake workers with
LISTEN/NOTIFYinstead of polling: a statement-level trigger on the queue table callspg_notify('job_created', null), once per insert statement rather than once per row. - Retry failed jobs with backoff and a maximum number of attempts, recorded on the job. A job that needs to run alone takes
pg_try_advisory_xact_lockon its key and gives way if it cannot.
Queue tables churn: every job is inserted and deleted. Vacuum them on a row count rather than a fraction of the table:
alter table job_queue.payload set (
autovacuum_vacuum_scale_factor = 0,
autovacuum_vacuum_threshold = 1000,
autovacuum_vacuum_insert_threshold = 1000
);
Idempotent writes
Every write a client may retry carries an idempotency key. The write's transaction reserves the key first:
create table idempotency (
key text primary key,
response jsonb,
created_at timestamptz not null default now()
);
-- first statement of the write's transaction
insert into idempotency (key) values ('req-1')
on conflict (key) do nothing
returning key;
-- a row came back: do the write, then keep its response
update idempotency set response = '{"payment_id": 42}' where key = 'req-1';
-- no row came back: the key was used before, so replay
select response from idempotency where key = 'req-1';
A duplicate sent while the first request is still running waits on the insert, fails with 40001 when the first commits, and its retry finds the stored response.
Insert first and read only on a conflict. At SERIALIZABLE, a lookup before the insert locks the index page where the key would go, and concurrent requests with different keys abort each other.
A timeout on everything
Each service connects as its own role, and each role has a statement_timeout that fits its work. A query that runs past it is cancelled, instead of holding a connection, locks and a snapshot while everything behind it waits. Pick the shortest value the role's slowest legitimate query fits under, and raise it when a real query needs more:
| Kind of work | A starting statement_timeout |
|---|---|
| Claiming queued work: one short query that should be instant | 1 s |
| Requests a person is waiting on (APIs, web pages) | 1–3 s |
| Background workers | 10–20 s |
| Reports and exports, on a replica | 10–30 s |
-- both in milliseconds alter role api_service set statement_timeout = 3000; alter role api_service set idle_in_transaction_session_timeout = 1000;
idle_in_transaction_session_timeoutof about a second for services ends a session that opened a transaction and stopped talking. The transaction it was holding open would otherwise keep its locks, and stop vacuum from cleaning up rows.lock_timeoutof 50 ms in every migration (why), and in any function or trigger that takes a strong lock:set local lock_timeout to '50ms'. Waiting for a lock is how one slow transaction stalls everything queued behind it; giving up and retrying is cheaper.
Connections
- Pool with pgbouncer in transaction mode, with a pool size per role. Give a service separate pools for separate kinds of work, such as listening, claiming jobs, writing and reading from a replica, so a burst of one cannot take the connections another needs.
- Turn prepared statements off in one place for every pool behind a transaction-mode pgbouncer, rather than at each call site.
- Read from a replica for exports and reports, at
REPEATABLE READ. - Give each kind of work its own role with only the grants it needs (roles per duty). A layer that only reads, such as a GraphQL API, connects as a read-only role.
- Pin
search_pathon everysecurity definerfunction:set search_path = pg_catalog, public. Otherwise a caller can put its own schema first and change what the function calls. - Use row-level security where a table holds data that must never cross tenants, such as one customer's records in a shared table, with a policy on a setting the transaction sets.
Types that carry rules
- Bounded text is a domain (
text_100), so a limit is declared once and every column that uses it agrees. - Timestamps are
timestamptz, defaulting toclock_timestamp(). - A set of values that changes is a lookup table with a foreign key, not an enum. Removing or renaming an enum value is a migration of every table that uses it.
- Every table and column has a
comment on, required by the table template, so it is never skipped (why).
Testing against PostgreSQL
- Test against a real PostgreSQL, never a mock: integration tests run the services against a database deployed from the plan, and database functions have pgTAP tests run with
pg_prove. - Test races on purpose. A test that runs two requests for the same row at once is the only way to see that serializable and the retry actually hold.
- Prepare every query against the new schema in CI, from both the code being merged and the code running in production (hasql-check), and lint every migration (sqint). Shipping safely has the whole pipeline.