Skip to content

About

Durable single-host Python job queue: transactional idempotency, fenced worker leases, retries, and failure recovery

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

LeaseQueue

A small durable job queue that makes worker ownership and failure recovery explicit.

LeaseQueue is a Python engineering reference for background jobs on a single host. SQLite transactions serialize claims; expiring, random lease tokens prevent workers from acknowledging a job after ownership has changed. It has no runtime dependencies beyond Python's standard library.

Try it

Python 3.11 or newer:

python -m pip install -e .
leasequeue --db jobs.sqlite enqueue invoice-42 '{"invoice_id":42}'
leasequeue --db jobs.sqlite claim --seconds 30
# Copy job_id and token from the lease response:
leasequeue --db jobs.sqlite complete JOB_ID TOKEN
leasequeue --db jobs.sqlite inspect JOB_ID

The CLI returns JSON and exits nonzero on rejected operations. Claim tokens are worker capabilities: keep them private. The database stores payloads unencrypted, so use an application-owned directory with restrictive filesystem permissions.

Run the deterministic recovery demo:

python examples/recovery.py
python -m unittest discover -s tests -v

State transitions

stateDiagram-v2
    [*] --> pending: enqueue
    pending --> running: claim / increment attempt
    running --> done: complete with live token
    running --> pending: fail / delayed retry
    running --> running: expired lease / reclaim with new token
    running --> dead: fail or reclaim scan / budget exhausted
Loading

An enqueue key is unique for the lifetime of the database. Reusing it with the same canonical JSON payload and attempt limit returns the original job ID; changing either raises IdempotencyConflict. Completed/dead jobs retain their keys. A crash after enqueue commits can therefore be retried safely by the producer.

Each claim increments the attempt counter, including crash recovery. The final expired attempt becomes dead on the next claim scan. Dead-letter transitions are driven by queue operations, not a timer service. inspect is a snapshot and does not perform recovery.

Guarantees and boundaries

Property Behavior
Claim exclusivity BEGIN IMMEDIATE selects and updates ownership in one write transaction
Stale-worker protection Completion and failure require matching token, running state, and unexpired lease
Crash recovery Another claim can acquire an expired job while retry budget remains
Persistence File-backed SQLite with WAL; success is returned after commit
Handler delivery At-least-once execution is possible; external side effects require application idempotency
Scale One local database file, many local worker processes; one writer at a time

A lease fences queue state, not a remote payment or HTTP side effect. A handler can perform a side effect and crash before acknowledgment. Design consumers with their own idempotency keys or transactional outbox. There is no exactly-once claim about external effects.

Do not place the SQLite database on a network filesystem. Durability depends on the host filesystem, SQLite, and hardware behavior; this project does not simulate power loss. Wall-clock adjustments affect lease expiry. Long tasks need a sufficient initial lease: heartbeat renewal, cancellation, scheduling priorities, pruning, schema migrations, metrics export, and multi-host operation are not implemented.

Python API

from leasequeue import Queue

queue = Queue("jobs.sqlite")
job_id = queue.enqueue("email:welcome:123", {"user_id": 123})
lease = queue.claim(lease_seconds=30)
if lease:
    # Perform an application-owned, idempotent operation here.
    queue.complete(lease)
print(queue.inspect(job_id))

For retryable handler failures, call queue.fail(lease, retry_delay=5). A lost lease raises LeaseLost; the old worker must stop treating itself as owner. Payloads must be JSON objects with finite numeric values. Attempt limits are positive integers, durations finite positive numbers, and retry delays may be zero.

Verification

The suite tests concurrent threads, independent spawned worker processes, producer idempotency, conflicting payloads, expiration boundaries, stale completion/failure, delayed retries, process-reopen persistence, exhausted budgets, and invalid input. No benchmark or throughput claim is made. See design decisions for trade-offs and failure analysis.

About

Durable single-host Python job queue: transactional idempotency, fenced worker leases, retries, and failure recovery

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages