Skip to main content

mongo-taskqueue

PyPI Python Versions Downloads CI Docs License

Queueing data structure on top of a MongoDB collection.

Overview

mongo-taskqueue stores tasks in a single MongoDB collection and exposes a small API for enqueueing, leasing, and completing work. It is designed for simple worker loops that need scheduling, retries, and deduplication without an extra queue service.

Features

  • Single-collection queue with priority ordering
  • Delayed enqueue and scheduled execution
  • Visibility timeouts with optional heartbeat extension
  • Retry tracking with optional exponential backoff
  • Dedupe keys (string) to avoid duplicate in-flight tasks
  • Global and per-key rate limiting
  • Dead-letter collection for discarded tasks
  • Sync and async APIs
  • CLI for common operations

Install

pip install mongo-taskqueue

Async support:

pip install "mongo-taskqueue[async]"

Quick start

from mongotq import get_task_queue

queue = get_task_queue(
    database_name="app",
    collection_name="jobs",
    host="mongodb://localhost:27017",
    ttl=-1,
)

queue.append({"job": "email", "to": "alice"})

task = queue.next()
if task:
    try:
        # do work
        queue.on_success(task)
    except Exception as exc:
        queue.on_failure(task, error_message=str(exc))

Configuration

get_task_queue(...) accepts:

  • ttl: seconds a pending task can live before being marked failed (-1 for no expiry)
  • max_retries: maximum failure count before discard
  • discard_strategy: keep or remove
  • visibility_timeout: lease duration for pending tasks
  • retry_backoff_base and retry_backoff_max: exponential backoff controls
  • dead_letter_collection: where discarded tasks are copied when using discard_strategy="remove"
  • meta_collection: metadata collection for rate limits
  • rate_limit_per_second: global and per-key dequeue limits
  • ensure_indexes: create indexes if missing

Task lifecycle

Statuses are available as constants: STATUS_NEW, STATUS_PENDING, STATUS_FAILED, STATUS_SUCCESSFUL.

Common transitions:

  • next() leases the next available task and marks it pending
  • on_success(task) marks it successful
  • on_failure(task) increments retries and may reschedule or fail
  • on_retry(task) releases a leased task back to new
  • refresh() requeues expired leases, expires pending tasks (TTL), and discards tasks over retry limits

Delayed tasks

queue.append({"job": "later"}, delay_seconds=30)
queue.append({"job": "at-time"}, scheduled_at=1710000000.0)

Dedupe keys

Dedupe keys are indexed for string values only.

queue.append({"job": "once"}, dedupe_key="job-123")

Duplicate inserts return False.

Rate limiting

Set rate_limit_per_second to throttle dequeue frequency. When a task has a rateLimitKey, the per-key limit is enforced in addition to the global limit. If a per-key limit is hit after a task is leased, the task is released and scheduled slightly in the future.

Dead-letter collection

queue = get_task_queue(
    database_name="app",
    collection_name="jobs",
    host="mongodb://localhost:27017",
    ttl=-1,
    max_retries=1,
    discard_strategy="remove",
    dead_letter_collection="jobs_dead",
)

Discarded tasks are copied to the dead-letter collection during refresh().

Async usage

from mongotq import AsyncTaskQueue

queue = AsyncTaskQueue(
    database="app",
    collection="jobs",
    host="mongodb://localhost:27017",
    ttl=-1,
)

await queue.append({"job": "async"})

task = await queue.next()
if task:
    await queue.on_success(task)

CLI

The CLI is installed as mongotq.

Environment variables:

  • MONGOTQ_HOST (or MONGO_URI)
  • MONGOTQ_DATABASE
  • MONGOTQ_COLLECTION
  • MONGOTQ_TTL

Example:

mongotq \
  --host mongodb://localhost:27017 \
  --database app \
  --collection jobs \
  append '{"job": "email"}'

Common commands:

  • append, next, pop, refresh, size, status
  • head, tail, purge, requeue-failed
  • heartbeat, dead-letter-count, resolve-anomalies

Testing

Tests are designed to run in GitHub Actions. Local runs are skipped unless GITHUB_ACTIONS=true is set.

License

MIT. See LICENSE.

Metadata

Release files for mongo-taskqueue 1.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 mongo-taskqueue 1.1.0
File Size Uploaded Provenance Actions
mongo_taskqueue-1.1.0.tar.gz 20.0 kB Without provenance Details for mongo_taskqueue-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mongo-taskqueue 1.1.0
File Interpreter ABI Platform Actions
mongo_taskqueue-1.1.0-py3-none-any.whl Python 3 none any Details for mongo_taskqueue-1.1.0-py3-none-any.whl

Total release size: 40.3 kB

Release files / mongo_taskqueue-1.1.0.tar.gz

Download URL mongo_taskqueue-1.1.0.tar.gz
Size 20.0 kB
Tags Source
SHA-256 checksum
How to use checksums
14d024248e6d03dd8a361b68ae4c03b70b6a831a419fb94e9ec069ea3c23546d
BLAKE2b-256 checksum
How to use checksums
4506fc8a58e8f9d870fc49968c8747e874bb92d64c85f3b8d768c0e8c13254a8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / mongo_taskqueue-1.1.0-py3-none-any.whl

Download URL mongo_taskqueue-1.1.0-py3-none-any.whl
Size 20.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
369f70b062750712f4f415bf0bda8f558f05223ff0ef49905b8903cece42f49b
BLAKE2b-256 checksum
How to use checksums
7da54a682a2c463d36a18ca8e62422393edb439eb8002323f0026bbe5a56bc22
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for mongo-taskqueue 1.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

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