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:
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:
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.
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 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;
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
Very useful to use a database because you:
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;
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;
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();
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.