sqitchcraft

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:

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.

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:

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:

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:

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 workA starting statement_timeout
Claiming queued work: one short query that should be instant1 s
Requests a person is waiting on (APIs, web pages)1–3 s
Background workers10–20 s
Reports and exports, on a replica10–30 s
-- both in milliseconds
alter role api_service set statement_timeout = 3000;
alter role api_service set idle_in_transaction_session_timeout = 1000;

Connections

Types that carry rules

Testing against PostgreSQL