Skip to main content

slonq

slonq (from the Slavic slon, meaning elephant, + q for queue) is a reliable, lightweight PostgreSQL job queue.

This is the Python package for slonq, providing high-performance bindings to the Rust core.

Built on top of FOR UPDATE SKIP LOCKED, it provides atomic, concurrent task distribution without the need for an external message broker. It is designed for small to medium-scale projects that already use PostgreSQL and require an ‘at-least-once’ delivery guarantee without adding infrastructure complexity.

Features

  • Atomic concurrency: Utilises Postgres SKIP LOCKED to ensure multiple workers can dequeue tasks simultaneously without collisions.
  • Idempotency support: Built-in support for idempotency keys to prevent duplicate job insertion.
  • Delayed jobs: Schedule tasks to become visible at a specific time in the future.
  • Lease mechanism: Jobs are ‘leased’ to workers; if a worker crashes, the lease expires and the job becomes visible for retry.
  • High performance: Core logic implemented in Rust with Python bindings via PyO3.

Installation

pip install slonq

Quick start

The following example demonstrates the full lifecycle of a job, including enqueuing, dequeuing, heartbeat (touching), and final acknowledgement using asyncio.

import asyncio
from slonq import PgQueue

async def main():
    # 1. Initialise the connection to Postgres
    queue = await PgQueue.connect("postgres://postgres@localhost:5432/db")

    # 2. Enqueue a job with an idempotency key and a 5-minute (300s) lease
    await queue.enqueue(
        "unique-request-id-123", 
        {"type": "process_video", "path": "/uploads/vid.mp4"}, 
        300
    )

    # 3. Dequeue a batch of jobs for 'worker-01'
    # This atomically leases up to 5 jobs for 3 attempts each
    jobs = await queue.dequeue("worker-01", 5, 3)

    for job in jobs:
        lease = job.lease_key()
        if not lease:
            continue

        # 4. Extend the lease (Heartbeat)
        # If the task is taking longer than expected, 'touch' it to prevent others from picking it up
        await queue.touch(lease, 60)

        # 5. Success vs failure logic
        success = True  # Replace with actual processing logic

        if success:
            # 6. Acknowledge (mark as done)
            await queue.ack(lease)
        else:
            # 7. Negatively acknowledge (return to queue with a 10s delay)
            await queue.nack(lease, 3, delay_seconds=10.0)
    
    # 8. Batch Acknowledgement
    # If you have a list of processed jobs, you can ack them all at once
    # await queue.ack_batch(list_of_leases)

if __name__ == "__main__":
    asyncio.run(main())

How it works

slonq manages job states through a visibility-based lease system:

  1. Enqueue: A job is inserted with a visible_at timestamp.
  2. Dequeue: A worker selects a batch of jobs where visible_at <= now(). Using FOR UPDATE SKIP LOCKED, Postgres ensures no two workers grab the same job. The visible_at is then moved forward by the lease_timeout, effectively ‘locking’ the job for that worker.
  3. Heartbeat: If a job is long-running, the worker can call touch() to extend the lease.
  4. Ack/Nack:
    • Ack: Successfully processed jobs are marked as done.
    • Nack: If a worker fails, it can negatively acknowledge the job to make it visible for retry immediately (or with a delay).
  5. Recovery: If a worker crashes, the visible_at time eventually passes, and the job naturally becomes available for another worker to attempt.

Operational considerations

  • Database schema: You must run the provided migration SQL to create the necessary table and indices.
  • Visibility: Because slonq relies on now(), ensure your application servers and database server have synchronised clocks.
  • At-least-once delivery: slonq guarantees that a job will be delivered to at least one worker. Ensure your worker logic is idempotent.

Database schema

slonq requires a specific table structure and a custom ENUM type to manage job states. You can apply the following migration to your PostgreSQL instance:

-- Required ONLY for PostgreSQL versions prior to 13 to support gen_random_uuid()
CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- Define the job lifecycle states
CREATE TYPE job_status AS ENUM ('pending', 'in_progress', 'done', 'failed');

CREATE TABLE jobs
(
   id                    BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
   idempotency_key       TEXT UNIQUE NOT NULL,
   status                job_status  NOT NULL DEFAULT 'pending',
   payload               JSONB       NOT NULL,

   -- 'Next eligible time' logic:
   -- Pending: When the job becomes available for its first attempt.
   -- In_progress: When the current lease is set to expire.
   visible_at            TIMESTAMPTZ NOT NULL DEFAULT now(),

   -- Tracks attempts to manage retry logic and dead-lettering
   attempt_count         INT         NOT NULL DEFAULT 0,

   -- Per-job lease duration (in seconds)
   lease_timeout_seconds INT         NOT NULL DEFAULT 60 CHECK (lease_timeout_seconds > 0),

   -- Unique lease identifier (regenerated on each dequeue)
   lease_id              UUID NULL,
   leased_by             TEXT NULL,

   created_at            TIMESTAMPTZ NOT NULL DEFAULT now(),
   updated_at            TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Index for the dequeue operation (FOR UPDATE SKIP LOCKED)
CREATE INDEX idx_jobs_dequeue
   ON jobs (visible_at) WHERE status IN ('pending', 'in_progress');

License

This project is licensed under the MIT License.

Metadata

Release files for slonq 0.0.0

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

Built distributions (wheels)

Table of built distributions (wheels) for slonq 0.0.0
File
slonq-0.0.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl PyPy 3.11 PyPy 3.11 7.3 Linux glibc 2.17+ x86-64 Details
slonq-0.0.0-pp311-pypy311_pp73-manylinux_2_17_i686.manylinux2014_i686.whl PyPy 3.11 PyPy 3.11 7.3 Linux glibc 2.17+ x86-32 Details
slonq-0.0.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.8 abi3 Linux glibc 2.17+ x86-64 Details
slonq-0.0.0-cp38-abi3-manylinux_2_17_i686.manylinux2014_i686.whl CPython 3.8 abi3 Linux glibc 2.17+ x86-32 Details
slonq-0.0.0-cp38-abi3-macosx_11_0_arm64.whl CPython 3.8 abi3 macOS 11.0+ ARM64 Details
slonq-0.0.0-cp38-abi3-macosx_10_12_x86_64.whl CPython 3.8 abi3 macOS 10.12+ x86-64 Details

Total release size: 6.5 MB

Release files / slonq-0.0.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL slonq-0.0.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 1.1 MB
Tags Linux glibc 2.17+ x86-64 PyPy 3.11 PyPy 3.11 7.3
SHA-256 checksum
How to use checksums
e02aca620998cde8bd77152273075d81723472dd90bfe506f240c32c612f9ce8
BLAKE2b-256 checksum
How to use checksums
6ddaf9855f57f18105be910b4baee63762023e46455c7307716b1bbb31094e52
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / slonq-0.0.0-pp311-pypy311_pp73-manylinux_2_17_i686.manylinux2014_i686.whl

Download URL slonq-0.0.0-pp311-pypy311_pp73-manylinux_2_17_i686.manylinux2014_i686.whl
Size 1.2 MB
Tags Linux glibc 2.17+ x86-32 PyPy 3.11 PyPy 3.11 7.3
SHA-256 checksum
How to use checksums
6ecb2acad4c2f24b39124abb71c53eda1fcc27a9a394116b978cbaa0cf85d491
BLAKE2b-256 checksum
How to use checksums
9ce170589ac636c4ad2f3195b14a047bd19813acb0f44dcc4681a33baa8b82ad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / slonq-0.0.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL slonq-0.0.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 1.1 MB
Tags CPython 3.8 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
5cd0e75e145d81cd41ec77ffce1510279d4f8c82548dd287cbba4f4df8d24a2b
BLAKE2b-256 checksum
How to use checksums
41b8a59e826abcb11dd7da2786653493997e5e0a00d30f20484dd06631403356
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / slonq-0.0.0-cp38-abi3-manylinux_2_17_i686.manylinux2014_i686.whl

Download URL slonq-0.0.0-cp38-abi3-manylinux_2_17_i686.manylinux2014_i686.whl
Size 1.2 MB
Tags CPython 3.8 Linux glibc 2.17+ x86-32 abi3
SHA-256 checksum
How to use checksums
c4d39ee0af2f45e68b4356416b1753058bd39c784d8203057a7cead6892e7335
BLAKE2b-256 checksum
How to use checksums
4d54613cf42bb66aa64fd45b825b2a67f9b49d28e9002d7dc023b48ea73e0f35
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / slonq-0.0.0-cp38-abi3-macosx_11_0_arm64.whl

Download URL slonq-0.0.0-cp38-abi3-macosx_11_0_arm64.whl
Size 981.3 kB
Tags CPython 3.8 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
6c760d48802fcc02d7e8328e689e8eca1f1361e97371746e6d870299d5fc54d5
BLAKE2b-256 checksum
How to use checksums
b8f8ff111220e60c6909dc8b35fed98a6b2dc833b12e24e25960b738ac6bae55
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / slonq-0.0.0-cp38-abi3-macosx_10_12_x86_64.whl

Download URL slonq-0.0.0-cp38-abi3-macosx_10_12_x86_64.whl
Size 1.0 MB
Tags CPython 3.8 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
d6afa8f4aa00e133a5355f962fb487be8473aafe8f1d6685a591b6a58652d5e5
BLAKE2b-256 checksum
How to use checksums
1531bbdfa3bc19a772e8971fdb28a9d8b90d2696f58bc3a53f11f5282de66bc8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release history Release notifications | RSS feed

This release

0.0.0 This release

6 release files

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