saveAll

open suspend override fun saveAll(group: String, checkpoints: List<Checkpoint>)

The upserts save makes one by one, in one transaction and one commit, one WAL flush (in autocommit each upsert of a batch was a transaction of its own). A key saved twice keeps its furthest position, as one statement may touch a row once.

Two statements, each over the batch as three arrays in key order, no ON CONFLICT DO UPDATE:

  1. ADD inserts the rows not there yet (a subscription's first save in a partition), ON CONFLICT DO NOTHING: a row that exists is left as it is, unlocked, and nothing is written for it.

  2. MOVE moves every row that is behind with one plain update, its guard the upsert's (position < new): it locks and writes the rows it moves and no other, a row the guard refuses neither.

So the common save, every row there and behind, writes each row once, a HOT update, with no lock record. ON CONFLICT DO UPDATE locks each conflicting row and writes that lock to the WAL (41% of a checkpoint row's WAL on a busy node), a row its guard refuses too.

Each statement locks only the rows it writes: ADD the rows it inserts, in key order (its select is ordered); MOVE the rows it moves, never one the guard refuses, in the order of its plan's outer side: the arrays, in key order, for a custom plan of a large batch; the group's rows, in the table's order, for a small batch or a generic plan, which a pooled connection reaches within a few saves. So two saves of one group that each move rows the other moves too (an owner's last save beside its successor's in a hand-over, a zombie owner's) may lock them in opposite orders and deadlock; a save that is not moving rows another moves never can. The one PostgreSQL picks as the victim (40P01) has had its transaction rolled back, and saves the batch again after a backoff (DEADLOCK_BACKOFF_MILLIS, doubling), at most DEADLOCK_ATTEMPTS times in all: the other save has gone on and, its statements taking milliseconds, ended meanwhile, so the next attempt does not meet it. A save still failing then throws, as any failure: the runtime saves the batch again on its next tick, and a stop saves what it can and reports the failure. A row another save inserted between the two statements is moved by MOVE if this save is ahead, its guard checked on the latest version, and left if not.

A failed batch commits none of it, and the caller saves it again, as it saves any batch that failed: each statement only moves a position forward.