Atomic Mechanism

In SQLite, INSERT ... ON CONFLICT ... DO UPDATE ... RETURNING executes as one SQL statement within a transaction. SQLite guarantees that the statement's database changes are atomic.

There are two separate concepts here:

  1. Atomicity: The insert or update either succeeds as a complete operation or its changes are rolled back.
  2. Isolation: Another connection cannot interleave a conflicting write between the conflict check and the update.

Fencing Token (version number for stale read protection on lease)

It's called a fence because it blocks things, fences block

Versions also indicate the current work that is in progress, so accepting older work items could break consistency if the new work and the old work results did not happen to be identical.

The important problem: stale leaders Atomic acquisition guarantees that only one process owns a valid lease in the database at any given moment.

It does not guarantee that only one process is actively doing work.

Consider this scenario:

  1. Process A acquires the lease with fencing token 5.
  2. Process A pauses for 40 seconds due to a long GC pause, system suspension, or network issue.
  3. Its lease expires.
  4. Process B acquires the lease with fencing token 6.
  5. Process A resumes, unaware that it lost leadership. Now both processes might attempt to perform leader-only operations.

This is why fencing tokens are useful.

If a protected resource tracks the highest accepted fencing token, it can reject operations from older leaders. Process A: token 5 → rejected Process B: token 6 → accepted

However, this only works if the resource receiving the operations enforces fencing. For example, database updates can conditionally check the leadership token. An external API that doesn't support fencing cannot automatically reject stale leaders.

Practical considerations

Lease Life Cycle

Claim lease

INSERT INTO leases (
    name, owner_id, expires_at, fencing_token
)
VALUES (
    'scheduler-leader', 'process-a',
    unixepoch() + 30, 1
)
ON CONFLICT(name) DO UPDATE SET
    owner_id = excluded.owner_id,
    expires_at = excluded.expires_at,
    fencing_token = leases.fencing_token + 1
WHERE leases.expires_at <= unixepoch()
RETURNING fencing_token;

Lease renewal

Lease owner must prove he is alive, heart beat. The chosen interval must account for network and processing latency. For example renewing a lease might take 30ms and 900ms worse case, so the lease renewal retry should allocate 3 extra seconds to avoid losing its lease due to a slow connection.

UPDATE leases
SET expires_at = unixepoch() + 30
WHERE name = 'scheduler-leader'
  AND owner_id = 'process-a'
  AND fencing_token = 5
  AND expires_at > unixepoch()
RETURNING expires_at;

Explicit lease release (because who wants to wait)

When the leader shuts down gracefully, it releases its lease:

Delete lease

DELETE FROM leases
WHERE name = 'scheduler-leader'
  AND owner_id = 'process-a'
  AND fencing_token = 5;

Notify the followers that lease is available

Worker Queue pattern

Very useful to use a database because you:

Let the database decide which work item is available, each update is performed in a transaction so its not possible for two work items to be selected by two queries executed closely together

UPDATE jobs
SET
    status = 'processing',
    worker_id = 'worker-a',
    lease_expires_at = unixepoch() + 30,
    attempt = attempt + 1
WHERE id = (
    SELECT id
    FROM jobs
    WHERE status = 'pending'
       OR (
           status = 'processing'
           AND lease_expires_at <= unixepoch()
       )
    ORDER BY id
    LIMIT 1
)
RETURNING id, payload, attempt;

Reduce everhead further by letting workers grab batches of work instead

WITH candidates AS (
    SELECT id
    FROM jobs
    WHERE status = 'pending'
       OR (
           status = 'processing'
           AND lease_expires_at <= clock_timestamp()
       )
    ORDER BY id
    LIMIT 10
    FOR UPDATE SKIP LOCKED
)
UPDATE jobs AS j
SET status = 'processing',
    worker_id = 'worker-a',
    lease_expires_at = clock_timestamp() + interval '60 seconds',
    attempt = j.attempt + 1
FROM candidates AS c
WHERE j.id = c.id
RETURNING j.id, j.payload, j.attempt;

attempt value acts as the lease fence

Postgres Optimization

SELECT id
FROM jobs
WHERE status = 'pending'
FOR UPDATE SKIP LOCKED -- avoids waiting for locked rows, transactions don't queue behind each other
LIMIT 1;

Have all contributors to the work update database directly

This reduces issues faced by distributed systems. For example a fencing token works better if we don't have to spend time communicating which fencing tokens are currently valid, the resource accepting the work can just report the work completed directly to the DB and receive the conflict when the stale fencing token is blocked.

UPDATE jobs
SET status = 'completed'
WHERE id = ?
  AND fencing_token = ?
  AND lease_expires_at > unixepoch();

Worker self monitoring (avoiding monitor process)

Have bounded life times for workers, could have lifetimes extended if your worker framework supports that, otherwise you just adhear to the contract and schedule a replacement instead. Have workers schedule their replacement process, can even schedule a delayed start to emulate backoff. Run multiple workers to address unexpected worker death, still can limp along with remaining workers. We would never want 1 worker unless waiting for the periodic reconcile happened to be ok for some reason. Will still need periodic reconcile to add any missing workers. But that process can wake up, create workers and shutoff.