Skip to main content

sqlite-workqueue

A small persistent job queue for Python programs that run on one machine. Producers enqueue JSON payloads; separate worker processes claim jobs, run a trusted handler, and acknowledge completion. It uses SQLite and has no runtime dependencies outside Python's standard library.

The first version focuses on queue correctness: atomic claims, bounded retries, and recovery when a worker exits before acknowledging its job. It is useful for local batch processing and learning how durable worker coordination works.

Try it

Requires Python 3.11 or newer. Install the sqlite-workqueue distribution from PyPI. In Python, import workqueue.

python -m pip install sqlite-workqueue

In a new directory, enqueue a job, run a worker once, and inspect the result:

workqueue --db jobs.sqlite3 enqueue '{"message":"hello"}'
workqueue --db jobs.sqlite3 worker workqueue.examples:echo --once
workqueue --db jobs.sqlite3 show JOB_ID

Use the ID printed by enqueue in place of JOB_ID. The worker prints the payload, then a JSON summary of the job's state. On PowerShell, use the Python example below to avoid shell-specific JSON quoting.

from workqueue import Queue, work_once

queue = Queue("jobs.sqlite3")
job_id = queue.enqueue({"message": "hello"}, max_attempts=3, retry_delay=2)
work_once(queue, lambda payload: print(payload["message"]))
print(queue.get(job_id).state)  # succeeded

Handlers must run synchronously. Async functions and callable instances with async __call__ methods are rejected before a job is claimed. If a synchronous wrapper returns an awaitable, the attempt fails instead of being acknowledged as successful. Run asynchronous work to completion inside a synchronous handler using an appropriate event loop adapter.

For your own worker, define a callable that accepts a decoded JSON payload:

# my_handlers.py, in your current directory
def handle(payload):
    print(payload["message"].upper())
python -m workqueue --db jobs.sqlite3 worker my_handlers:handle

Use python -m workqueue for handlers in the current directory: Python includes that directory on its module search path. The installed workqueue command supports handlers in installed packages; it does not automatically import files from the working directory. Use the same Python environment where you installed the queue. Handler modules and their imports must be trusted Python code.

Start that command in more than one terminal to run separate workers. Without --once, workers poll until interrupted. Handlers that raise an exception cause the job to retry; error text is kept on the job. A one-shot worker exits with 0 after success or when no job is available, 1 after a handler failure, and 2 for an invalid command input or a lost lease. Ctrl+C exits with 130.

For long-running handlers, enable background lease renewal:

python -m workqueue --db jobs.sqlite3 worker my_handlers:handle --lease-seconds 60 --heartbeat-interval 15

The interval must be positive and shorter than the lease duration. The Python equivalent is work_once(queue, handler, lease_seconds=60, heartbeat_interval=15). The renewal thread stops and is joined when the handler exits, including on interruption. If renewal fails, the worker propagates that error without acknowledging or retrying the job under uncertain ownership. Recovery happens through the normal lease-expiry mechanism.

Retrying producer requests

If a producer loses the response to an enqueue, retry it with a stable key:

job_id = queue.enqueue({"order": 42}, idempotency_key="order:42")
assert queue.enqueue({"order": 42}, idempotency_key="order:42") == job_id

The CLI accepts enqueue PAYLOAD --idempotency-key KEY. Keys are nonempty strings scoped to one database. Concurrent producers using the same key and request receive the same job ID. Reuse with different payload JSON or enqueue options (max_attempts, retry_delay, delay) raises ValueError (CLI exit 2). Object key order is ignored; other JSON representations remain significant.

Keys remain reserved even after success or failure. Repeating a request does not reset attempts, reschedule delayed work, or restart a job. There is no key expiry or deletion API. Calls without a key always enqueue a new job. Opening an older queue adds the key table without changing its existing jobs. Producer deduplication does not prevent repeated handler side effects; delivery still requires idempotent handlers.

Example: publish a file safely on retry

Run this from a directory containing a small UTF-8 file named input.txt:

from hashlib import sha256
from pathlib import Path

from workqueue import Queue, work_once
from workqueue.examples import write_snapshot

source = Path("input.txt").read_text(encoding="utf-8")
directory = str(Path("snapshots").resolve())
digest = sha256(source.encode("utf-8")).hexdigest()
queue = Queue("snapshots.sqlite3")
queue.enqueue({"text": source, "directory": directory},
              idempotency_key=f"snapshot:{directory}:{digest}")
work_once(queue, write_snapshot)

The producer captures the text at enqueue time. A worker writes it to a temporary file beside the destination and atomically replaces the file named by its content hash. If a worker exits after replacement but before completing the job, a retry writes the same bytes to the same path. Different content gets a different path. A hard exit before replacement can leave a temporary file; this example does not guarantee durability across power loss.

Inspect failed jobs

Run workqueue --db jobs.sqlite3 failed --limit 10 to see recent terminal failures as a JSON array, including each job's payload and last error. The default limit is 20 and the accepted range is 1 to 1000. The command only reads job state, so expired claims and jobs waiting to retry stay out of this list. In Python, use queue.failed_jobs(limit=10).

To continue, pass the last job ID in the previous batch to failed --after JOB_ID or queue.failed_jobs(after=job_id). Jobs with the same failure time are ordered by ID. Each batch reads the current queue. Start again from the first batch to see failures that appeared before your cursor while you were paging.

Opening an existing queue adds an ordering index for terminal failures without changing jobs or idempotency keys. The first open builds that index under a database write lock; allow time for this when upgrading a large queue. Later failures incur an additional index write. See the pagination benchmark for measurements, storage costs, and limits.

Claims and recovery

Jobs move from pending to running, then to succeeded or back to pending. A failed attempt at its retry limit becomes failed. max_attempts includes the first attempt. Retries after handler exceptions wait retry_delay * 2^(attempt-1) seconds, capped at one hour. enqueue(..., delay=10) defers the first attempt.

Claiming uses a short BEGIN IMMEDIATE transaction. Selecting a pending job and recording its ownership happen under the same write lock. Handler code runs outside that transaction, so a slow handler does not hold the database lock.

Each claim receives a new random lease token. Completion, failure and renewal check both that token and the lease's expiry. An old worker cannot acknowledge a claim after another worker has reclaimed it. The next claim() requeues expired jobs immediately, or marks them failed if their attempt budget is exhausted. get() is a snapshot; it does not perform lease recovery itself.

Inspect the queue without claiming jobs or recovering expired leases:

workqueue --db jobs.sqlite3 stats

The command prints JSON counts for total, pending, running, succeeded, failed, ready, delayed and expired. Python callers can use queue.stats(). ready and delayed split the pending jobs by their availability time; expired is the subset of running jobs whose leases have expired. These subsets overlap the state counts, so do not add all eight fields together. All counts come from one database snapshot. Inspection does not change job state or attempt counts; only the next claim() performs expiry recovery. Like the other CLI commands, opening a queue path still initializes its database if it does not exist.

For direct API use, queue.claim(lease_seconds=60) returns a Job or None. Use queue.complete(job), queue.fail(job, "reason") or queue.renew(job, lease_seconds=60) with that claim. These raise LeaseLost when ownership has expired or changed. Renewal sets expiry relative to the renewal time; choose an interval that keeps the lease alive.

Limits

  • Delivery is at least once, not exactly once. A handler can finish a side effect and crash before acknowledging it. Make handlers idempotent. Lease tokens protect queue state, not side effects in another system.
  • All workers must use a local database on the same host. Do not put the SQLite WAL database on a network filesystem or file-sync folder. SQLite serializes writers; this is not a replacement for a multi-host broker.
  • Heartbeats are opt-in. Without them, set a lease longer than your handler's expected runtime, or use the direct API to renew it. A heartbeat cannot interrupt a handler that has already started or guarantee renewal during a process pause. An expired handler may overlap a new attempt, even though it can no longer acknowledge the job.
  • Scheduling uses the host wall clock. Significant clock changes can affect delays and lease expiry.
  • Handlers are trusted local Python code, not a sandbox. Database payloads and error messages are stored in plaintext. Do not enqueue credentials or private records into a shared database.
  • There is no cancellation, periodic scheduling, schema migration system, result storage or HTTP service. Database lock waits time out after five seconds. Concurrent first-open WAL setup retries transient busy errors for up to five seconds before propagating the error. Reliability evidence comes from the tests described below.

Maintenance status

Feature development for the current scope is complete. This project is maintained for reproducible bugs, security issues, compatibility breakage affecting supported use, and explicitly requested changes. New features are outside the current maintenance scope.

Report reproducible problems on the issue tracker.

Development

python -m pip install -e .
python -m unittest discover -s tests -v

Tests cover persistence, delayed availability, retries, lease fencing, lease renewal, handler failures, an abrupt worker process exit, competing worker processes and the CLI. The CI workflow runs these on Linux and Windows with CPython 3.11 through 3.15.

The design follows SQLite's transaction documentation and WAL constraints.

Releasing a maintenance fix

  1. Update the version in pyproject.toml and add its notes to the changelog. Merge the release PR after CI passes.
  2. Check that the version is unused on PyPI and that the GitHub tag and release are new. Tag the passing commit on main with the matching vX.Y.Z tag and push the tag.
  3. On GitHub Actions, run Release from main with that tag. The workflow tests the tagged commit, builds and checks both distributions, publishes to PyPI through the pypi environment, verifies the PyPI installation, and creates the GitHub release with the same files and SHA-256 checksums.
  4. Check that both public release pages show the intended version and files. If the workflow stops after uploading, keep its validated artifacts, compare them with the public files, and resume the failed step without re-uploading files that are already public.

Provenance and license

MIT licensed. See LICENSE.

Metadata

Release files for sqlite-workqueue 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sqlite-workqueue 0.1.0
File Size Uploaded Provenance Actions
sqlite_workqueue-0.1.0.tar.gz 20.6 kB With provenance Details for sqlite_workqueue-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sqlite-workqueue 0.1.0
File Interpreter ABI Platform Actions
sqlite_workqueue-0.1.0-py3-none-any.whl Python 3 none any Details for sqlite_workqueue-0.1.0-py3-none-any.whl

Total release size: 34.7 kB

Release files / sqlite_workqueue-0.1.0.tar.gz

Download URL sqlite_workqueue-0.1.0.tar.gz
Size 20.6 kB
Tags Source
SHA-256 checksum
How to use checksums
8121e759560cf2483c049f6b93acf2b5043d75f7b4f987950774457a7a050f45
BLAKE2b-256 checksum
How to use checksums
2db61d4d18b7ace20bab2de3dc0487c5bb85a9efc68c03c7d67425549886fab2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / sqlite_workqueue-0.1.0-py3-none-any.whl

Download URL sqlite_workqueue-0.1.0-py3-none-any.whl
Size 14.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7b09f8445c1a530cd0d013b3a6e232bcb3bbb52c8b6e0fe23914f3d99d1782c7
BLAKE2b-256 checksum
How to use checksums
db96e4f92895529fc85de5f5436780dea3413e596c091c0361eed287e8142104
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for sqlite-workqueue 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for sqlite_workqueue-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page