Events and replication · Engineering

Background jobs with fenced leases

A job queue built from ordinary documents: atomic claims, lease fencing, retries, and why workers must be idempotent.

NonoDB does not execute stored procedures or load job code into the daemon. Background work is done by ordinary client processes using the same API as the application.

The database stores job documents. A separate worker claims and executes them. That keeps the single-writer model, LMDB transactions, and authorization boundaries unchanged.

The model

producer ──insert/find_and_modify──▶ _jobs collection ──claim──▶ worker process
│
├── handler code
└── complete/fail

Semantics:

  • at-least-once: a worker can crash after running a handler but before recording completion;
  • single execution at a time: find_and_modify atomically moves a job from pending to running;
  • fenced leases: every claim writes a unique lease_id;
  • retries: failed jobs return to pending with exponential backoff until max_attempts, then become failed;
  • no arbitrary code from the database: the job document contains a type and parameters, while the handler code is deployed with the worker.

The job document

{
"_id": "01J...",
"type": "sync_customer",
"status": "pending",
"payload": {"tenant": "acme", "customer_id": "c1"},
"attempts": 0,
"max_attempts": 5,
"due_at": 1762800000000,
"created_at": 1762799940000,
"updated_at": 1762799940000
}

Status values are pending, running, done, and failed.

A claim adds lease_id, lease_until, worker_id, started_at, and increments attempts.

Atomic claim

The claim is a conditional update: find a pending job whose due_at has passed, then move it to running with a new lease. Because writes go through one writer, two workers cannot claim the same job.

If the lease expires, another worker can recover it. The old worker might still be running and might try to complete the job. The lease_id is the fence: completion and failure compare the current lease_id, so a stale worker cannot overwrite a recovered job.

That is why a lease is not just a timeout. It is a fencing token.

Indexes

The worker helper uses two compound indexes:

{"fields": ["status", "due_at"]}
{"fields": ["status", "lease_until"]}

Create them once with an administrative client, or start the worker with --create-indexes:

Terminal window
python3 -m nonodb_worker \
--module myjobs \
--collection _jobs \
--create-indexes

Creating an index rebuilds it, so do not run --create-indexes on every worker start in a large deployment.

The Python helper

The repository includes workers/python/nonodb_worker:

workers/python/nonodb_worker/jobs.py # JobQueue, JobRunner
workers/python/nonodb_worker/__main__.py
workers/python/examples/jobs_handlers.py
workers/python/examples/jobs_smoke.py

A handler module registers job types:

from nonodb_worker import Job
def add_numbers(job: Job):
return {"sum": int(job.payload["a"]) + int(job.payload["b"])}
def register(runner) -> None:
runner.register("add", add_numbers)

Run it:

Terminal window
PYTHONPATH=client:workers/python:workers/python/examples \
NONODB_SOCK=/run/nonodb/nonodb.sock \
python3 -m nonodb_worker \
--module jobs_handlers \
--collection _jobs \
--recover-expired

Useful options:

Option Meaning
--once Claim and run at most one job
--poll-interval Idle sleep between claims, default 1 s
--lease-seconds Lease duration, default 60
--recover-expired Requeue expired leases at startup
--create-indexes Build the job indexes first
--worker-id Stable identity in logs and job documents

Enqueueing

from nonodb import NonoDB
from nonodb_worker import JobQueue
jobs = JobQueue(NonoDB().collection("_jobs"))
jobs.enqueue(
"sync_customer",
{"tenant": "acme", "customer_id": "c1"},
job_id="sync_customer:c1",
)

Passing job_id makes enqueue idempotent: a duplicate _id is treated as already enqueued.

If the job must be written atomically with application data, use write_batch. The order and job commit together or not at all.

Failure handling

A handler exception records last_error and retries with backoff. An unknown job type is marked failed immediately. After max_attempts, the job becomes failed and is visible for inspection.

Retries are not a substitute for idempotency. A crash after the side effect but before completion replays the handler. Use an idempotency key or a natural idempotency key such as sync_customer:c1.

Scheduling

Two patterns work:

  • a long-running worker that polls for due jobs;
  • a cron or systemd timer that runs --once frequently.

A long-running worker has lower latency and keeps leases alive. A timer is simpler to supervise and naturally bounds concurrency.

What it is not

  • Not a cron daemon with a built-in expression parser.
  • Not a workflow engine with steps, compensation, and DAGs.
  • Not exactly-once execution.
  • Not isolated from the application’s auth scopes.
  • Not a reason to run handler code in the daemon.

When it fits

Use jobs when:

  • work must survive a process restart;
  • you want retries and visibility in the database;
  • the job volume is modest;
  • workers can be idempotent;
  • you want to enqueue atomically with a data change.

Use a dedicated queue or workflow engine when you need high throughput, exactly-once effects, complex fan-out, or long-running orchestration.

The background jobs guide and events guide cover the API, helper, and validation scripts.

All engineering notes →Read the docs