Trending

World technology news

→
Protecting ownership in a SQLite job queue with leases and attempt numbers
Software Engineering · 2026
Software Engineering

Protecting ownership in a SQLite job queue with leases and attempt numbers

A local two-connection example tests job claims, lease expiry and the conditions that reject a stale worker’s completion in SQLite.

Developer's JournalPublished: Dec 5, 20266 min read
Reading progress0%
In this article
  1. How two workers can take the same queue item
  2. Acquire the write lock and release it promptly
  3. Exercise the claim with two real connections
  4. Keep a previous owner from completing the new claim
  5. Coordinate the queue with effects outside SQLite
  6. Observe contention and recovery in deployment
  7. Inspect the state during a planned stop

How two workers can take the same queue item

A local reporting application may begin with one worker and later let two processes consume work from the same SQLite file. If each worker selects a waiting row and updates it in a separate statement, both can read the same ID before either records ownership. The database might eventually show one completed row even though the application generated two reports or imported the same file twice. This example gives each claim a short write transaction. It moves expensive work outside that transaction and checks ownership when recording a result. Each row carries its ID, its completion state, the time its lease expires, and an attempt number that increases on every claim. Together these values let the worker recover abandoned work and detect results produced by a previous owner.

Acquire the write lock and release it promptly

BEGIN IMMEDIATE starts the write transaction before the worker updates the row. SQLite permits one write transaction at a time, so another connection waits for the lock or receives SQLITE_BUSY when its configured timeout expires. Within UPDATE, a subquery picks the first unfinished row whose lease is absent or expired. The same statement assigns the owner, calculates the new expiry and increments the attempt number. RETURNING gives the application the ID and attempt it acquired. The code consumes the result before executing the SQL COMMIT. An empty result means that no row met the predicate. A busy error means that the connection could not acquire the writer lock. Separating those cases makes both retry behavior and queue monitoring easier to understand.

Database access flowConceptual sketch · summary of the article's technical flow

Exercise the claim with two real connections

The example ran locally with Python 3.12.10 and SQLite 3.49.1 against a temporary database file. Connection A first holds a write transaction. Connection B tries to claim work and prints SQLITE_BUSY after its 50 millisecond timeout. A releases the lock and claims job 1 on attempt 1. At logical time 109, B finds no available row. At 110, B acquires the same job on attempt 2. At time 111, an attempt to finish under the first claim changes zero rows, while finishing under the second claim changes one. Both connections use autocommit=True and issue explicit SQL transaction statements. The lease clock is a deterministic input, so the boundary can be reproduced without waiting for a timer.

import sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory

CLAIM = """
UPDATE job SET owner = :owner, lease_until = :now + :ttl,
               attempt = attempt + 1
WHERE id = (
    SELECT id FROM job
    WHERE finished = 0 AND (lease_until IS NULL OR lease_until <= :now)
    ORDER BY id LIMIT 1
)
RETURNING id, attempt
"""

def claim(connection, owner, now, ttl):
    connection.execute("BEGIN IMMEDIATE")
    try:
        rows = connection.execute(CLAIM, dict(owner=owner, now=now, ttl=ttl)).fetchall()
        connection.execute("COMMIT")
    except BaseException:
        if connection.in_transaction:
            connection.execute("ROLLBACK")
        raise
    return rows[0] if rows else None

def finish(connection, job_id, owner, attempt, now):
    return connection.execute("""
        UPDATE job SET finished = 1
        WHERE id = ? AND owner = ? AND attempt = ?
          AND finished = 0 AND lease_until > ?
    """, (job_id, owner, attempt, now)).rowcount

with TemporaryDirectory() as folder:
    database = Path(folder) / "jobs.sqlite"
    with closing(sqlite3.connect(database, autocommit=True)) as a:
        with closing(sqlite3.connect(database, autocommit=True, timeout=0.05)) as b:
            a.execute("CREATE TABLE job(id INTEGER PRIMARY KEY, owner TEXT, lease_until INTEGER, attempt INTEGER NOT NULL DEFAULT 0, finished INTEGER NOT NULL DEFAULT 0)")
            a.execute("INSERT INTO job(id) VALUES (1)")
            a.execute("BEGIN IMMEDIATE")
            try:
                try:
                    claim(b, "worker-b", 100, 10)
                except sqlite3.OperationalError as exc:
                    assert exc.sqlite_errorcode == sqlite3.SQLITE_BUSY
                    print(exc.sqlite_errorname)
                else:
                    raise AssertionError("The second writer acquired the lock")
            finally:
                a.execute("ROLLBACK")
            first = claim(a, "worker-a", 100, 10)
            waiting = claim(b, "worker-b", 109, 10)
            second = claim(b, "worker-b", 110, 10)
            assert (first, waiting, second) == ((1, 1), None, (1, 2))
            stale = finish(a, 1, "worker-a", 1, 111)
            valid = finish(b, 1, "worker-b", 2, 111)
            assert (stale, valid, claim(a, "worker-a", 120, 10)) == (0, 1, None)
            print(first, waiting, second)
            print("stale:", stale, "completed:", valid)
            print("SQLite", sqlite3.sqlite_version)

Keep a previous owner from completing the new claim

A worker can keep running after its lease expires. Its next update must therefore carry the attempt number it received when it claimed the row. The finish statement matches the job ID, the owner, the attempt number, and a lease that remains valid. The attempt also detects stale ownership when a restarted process reuses the same worker name. A change count of zero tells the application its result is no longer eligible to complete the job. A long-running job can renew its lease using the same ownership conditions. Keeping attempt-specific temporary output in separate directories also avoids letting a recovered job and an older process write to the same destination while both are still active.

Coordinate the queue with effects outside SQLite

A queue transaction can protect its own state while a downstream service operates on a separate timeline. If a worker sends a request and then loses the connection, SQLite cannot determine whether the receiver processed the request. When the receiver supports idempotency, both the original request and retry can carry one stable key derived from the job, independent of the attempt number. A status lookup can help resolve an ambiguous outcome before an additional request goes out. If the result and queue row share a database, the application can write them in one transaction. For other cases, explicitly model unresolved delivery in the application. Holding the SQLite write lock across a network call lengthens the time other consumers spend waiting.

Observe contention and recovery in deployment

Measure claim transaction duration separately from job execution time. Track busy errors, attempts after lease expiry, and finish statements rejected because ownership changed. A short bounded retry can help with transient lock contention. Sustained delays warrant checking for file operations, network requests or computation inside a write transaction. Inspect the selection query on realistic data as completed jobs build up. A scan that is cheap with dozens of rows may become expensive in a queue with thousands of finished items. Finally, document which clock and units workers use to compare lease times. The difference between time 109 and time 110 is explicit in the test, and it should be just as clear when investigating a production retry.

Inspect the state during a planned stop

During maintenance, record which jobs still have valid leases, along with the owner and the attempt number. After restart, those values distinguish current work from a late completion sent by a worker that ran before the stop. Where the job produces a file, verify that the completed row points to an output that actually exists at its durable location. Where a separate service delivers the result, retain its delivery identifier and timestamp with the job history. These observations determine whether the operator can safely retry the existing request or needs to investigate a still-active attempt.

577 reads ✎ Write a comment

Reader discussion

Discussion prompt

What would you change first for maintainability and testing in your own project?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.