Metadata-Version: 2.5
Name: deferd
Version: 0.0.2
Summary: Delayed jobs for Python services on Kubernetes. No broker, no polling, no new infrastructure.
Author-email: Pranav Tyagi <pranavww@gmail.com>
License-Expression: MIT
License-File: LICENSE
Requires-Python: >=3.12
Requires-Dist: msgpack>=1.0
Provides-Extra: all
Requires-Dist: aiomysql>=0.2; extra == 'all'
Requires-Dist: cryptography>=42; extra == 'all'
Requires-Dist: elasticsearch[async]<9,>=8.13; extra == 'all'
Requires-Dist: lightkube>=0.15; extra == 'all'
Requires-Dist: pymongo>=4.13; extra == 'all'
Requires-Dist: redis>=5.0; extra == 'all'
Provides-Extra: elasticsearch
Requires-Dist: elasticsearch[async]<9,>=8.13; extra == 'elasticsearch'
Provides-Extra: kubernetes
Requires-Dist: lightkube>=0.15; extra == 'kubernetes'
Provides-Extra: mongo
Requires-Dist: pymongo>=4.13; extra == 'mongo'
Provides-Extra: mysql
Requires-Dist: aiomysql>=0.2; extra == 'mysql'
Requires-Dist: cryptography>=42; extra == 'mysql'
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.25; extra == 'otel'
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == 'redis'
Description-Content-Type: text/markdown

# deferd

Delayed jobs for Python services on Kubernetes. **No broker, no polling, and no new infrastructure.**
Your pods hold the jobs and back each other up; add a database only if you want jobs to survive
everything restarting at once.

**Status:** pre-alpha. The API may still change.

---

## The problem

A request arrives at a FastAPI endpoint, or a message arrives at a consumer, and the requirement is:
*"do this 30 minutes from now."* Send a reminder, expire a hold, follow up on a payment.

Today that usually means adding Redis and Celery, or a database-backed queue that polls constantly.
That's infrastructure to run, monitor, and pay for, just to wait 30 minutes.

## How deferd works

- The pod that receives a job owns it and keeps its timer **in memory**. Timers fire at the right
  moment; nothing polls.
- Each job is copied to **backup pods on other nodes** (one by default, up to three) before
  `schedule()` returns. If every pod is on one node, the backups go on that node and the job is
  reported as weakly placed.
- If the owner dies, a backup takes over. If a pod shuts down, it hands its jobs off first.
- For jobs that must survive anything, deferd also writes them to a store you already run:
  **MySQL, MongoDB, Redis or Elasticsearch.**

## Quick start

```python
from datetime import timedelta
from deferd import Durability, JobContext, Scheduler

scheduler = Scheduler(
    app_name="orders",
    discovery="kubernetes",  # or "static" for local development
)


@scheduler.handler(timeout=timedelta(minutes=5), max_attempts=5)
async def send_reminder(payload: dict, ctx: JobContext) -> None:
    ...  # ctx.job_id is the idempotency key


@scheduler.handler(durability=Durability.MEMORY, expires_after=timedelta(minutes=10))
async def warm_cache(payload: dict, ctx: JobContext) -> None:
    ...


async with scheduler.run():  # joins the cluster; leaves gracefully on exit
    await scheduler.schedule("send_reminder", {"order_id": 123}, delay=timedelta(minutes=30))
    ...  # the rest of your service
```

Every handler receives `(payload, ctx)`. `ctx.job_id` is the same across retries and duplicate runs,
so use it as the idempotency key. Pass `delay` or `at` to `schedule()`, not both. With neither, the job
runs as soon as possible. Handlers must be `async`.

Use one `app_name` per application. Every pod of the app uses the same value, and different
applications must use different values, even in the same Kubernetes namespace or database.

To react when a job finishes, pass `on_succeeded`, `on_dead` (out of attempts) or `on_expired`
to `Scheduler`. Each is called with the job.

## Durability, chosen per job

| Preset | Copies | Survives | Cost | Needs |
|---|---|---|---|---|
| `MEMORY` | Owner only | Nothing beyond the process | Free | Nothing |
| `REPLICATED` (default) | Owner + backup pod | Pod and node failures, rolling deploys | One network round trip | A second pod |
| `PERSISTED` | Owner + store | Everything, with slower failover | One store write | A store |
| `DURABLE` | Owner + backup + store | Everything, with fast failover | Both | A store |

Set it per handler (`@scheduler.handler(durability=...)`), per call (`schedule(..., durability=...)`)
or for the whole app (`default_durability=`). A preset can be given as a `Durability` value or by
name (`"memory"`, `"replicated"`, ...). `PERSISTED` and `DURABLE` without a store raise
`ConfigurationError`.

`replicas` sets how many backups a job gets (0 to 3). `min_replicas` sets how many must acknowledge
before `schedule()` returns:

```python
Durability(replicas=2, min_replicas=1)   # three copies; returns once one backup acknowledges
Durability(replicas=1, min_replicas=0)   # accepted even with no other pod; backed up when one joins
```

Pods on an older deferd version can't read a policy with `min_replicas`, so upgrade every pod first.

### Persisting jobs

`PERSISTED` and `DURABLE` jobs need a store. Pass one as a URL, or set `DEFERD_STORE`:

```python
scheduler = Scheduler(app_name="orders", store="mysql://user:pass@db:3306/app")
```

| Store | URL | Extra | Notes |
|---|---|---|---|
| MySQL 8 / MariaDB 10.6+ | `mysql://user:pass@host:3306/db` | `deferd[mysql]` | Run `deferd migrate` first |
| MongoDB | `mongodb://host:27017/db` | `deferd[mongo]` | Creates its indexes on connect |
| Redis 7 / Valkey | `redis://host:6379/0` | `deferd[redis]` | Needs AOF, or deferd refuses it |
| Elasticsearch 8 | `elasticsearch://host:9200` | `deferd[elasticsearch]` | Creates its indexes on connect |

Create the MySQL schema before the first deploy, and again after upgrading deferd. Check what a
store guarantees with `deferd check`:

```bash
deferd migrate --store "mysql://user:pass@db:3306/app"
deferd check --store "mysql://user:pass@db:3306/app"
```

`deferd check` reports the store as SAFE, WEAK (a warning, such as MySQL not flushing every commit or
a single-node Elasticsearch) or UNSAFE (Redis without AOF: refused unless `allow_unsafe_store=True`).

- **Several applications, one database:** each must use its own `app_name`. With Kubernetes
  discovery, deferd refuses to start a second application under an `app_name` another one uses.
  With static or custom discovery, choosing distinct names is up to you.
- **Store down:** a pod starts anyway and logs a warning. Persisted `schedule()` calls are refused
  until the store answers; memory and replicated jobs keep working.
- **Cleanup:** finished persisted jobs are kept for 7 days (`DEFERD_FINISHED_RETENTION`). Set
  `retain_for` on a handler to change it for that handler (at least 10 minutes).

## Running on Kubernetes

Install `deferd[kubernetes]`. Pods find each other through the Kubernetes API, so your Deployment
needs a few additions. [`deploy/kubernetes/`](deploy/kubernetes/) has complete manifests to copy.

**New objects:**

| Object | Why |
|---|---|
| `ServiceAccount`, `Role`, `RoleBinding` ([`rbac.yaml`](deploy/kubernetes/rbac.yaml)) | Lets each pod `get`, `list` and `watch` pods in its namespace to find its peers |
| `Secret` with `DEFERD_SECRET` | Pods prove they belong to the app before exchanging jobs. Same value on every pod |
| `PodDisruptionBudget` with `maxUnavailable: 1` ([`pdb.yaml`](deploy/kubernetes/pdb.yaml)) | Node drains evict one pod at a time, so each hands its jobs off |
| `NetworkPolicy` ([`networkpolicy.yaml`](deploy/kubernetes/networkpolicy.yaml)) | Only if your namespace denies traffic by default: allow port 7946 between the app's pods |

**Changes to your Deployment** ([`deployment.yaml`](deploy/kubernetes/deployment.yaml)):

```yaml
spec:
  strategy:
    type: RollingUpdate                          # never Recreate: it stops every pod at once
    rollingUpdate: {maxUnavailable: 0, maxSurge: 1}
  template:
    spec:
      serviceAccountName: orders-deferd
      terminationGracePeriodSeconds: 60          # time to hand jobs off and finish running ones
      containers:
        - name: orders
          ports:
            - {name: deferd, containerPort: 7946}   # pod-to-pod traffic; no Service needed
            - {name: admin, containerPort: 9090}    # /healthz, /readyz, /metrics
          env:
            - {name: DEFERD_DISCOVERY, value: kubernetes}
            - name: DEFERD_SECRET
              valueFrom: {secretKeyRef: {name: deferd-secret, key: DEFERD_SECRET}}
            # filled in by Kubernetes for each pod; copy as is
            - name: DEFERD_POD_NAME
              valueFrom: {fieldRef: {fieldPath: metadata.name}}
            - name: DEFERD_POD_NAMESPACE
              valueFrom: {fieldRef: {fieldPath: metadata.namespace}}
            - name: DEFERD_POD_IP
              valueFrom: {fieldRef: {fieldPath: status.podIP}}
            - name: DEFERD_NODE_NAME
              valueFrom: {fieldRef: {fieldPath: spec.nodeName}}
          readinessProbe:
            httpGet: {path: /readyz, port: admin}
          livenessProbe:
            httpGet: {path: /healthz, port: admin}
          lifecycle:
            preStop: {exec: {command: ["sleep", "5"]}}   # peers stop sending work first
```

Pods are peers when they share the Deployment's `app` label. Spread them over nodes with *soft* pod
anti-affinity or `topologySpreadConstraints` (`whenUnsatisfiable: ScheduleAnyway`), so a job and
its backup don't sit on the same machine. [`deploy/kubernetes/README.md`](deploy/kubernetes/README.md)
explains each rule and lists the startup errors and their fixes.

### Process modes

- **Embedded** (one process per pod, such as a queue consumer or a single-worker web app): the
  service runs `async with scheduler.run()` and is a cluster member itself.
- **Dedicated** (several web workers per pod, such as gunicorn): one `deferd run module:scheduler`
  process per pod is the member, and the workers schedule jobs through `scheduler.client()`
  (`client(sync=True)` for Flask or classic Django) over a Unix socket.

See [`examples/`](examples/): a queue consumer, FastAPI embedded, and FastAPI with gunicorn.

## Running without a store

With no store, jobs live only in pod memory. Two failures lose `REPLICATED` jobs:

1. **A job's owner and all its backups die at the same time**, for example pods on one node that
   fails.
2. **Every pod restarts at once**: the `Recreate` deploy strategy, scaling to zero, or a
   whole-cluster outage.

These losses can't be counted: every member that knew about those jobs is gone. Jobs left with a
single copy are visible (`deferd_under_replicated_jobs`). To make losses unlikely:

- Run **at least two replicas, on different nodes**, with soft anti-affinity (hard anti-affinity
  leaves pods `Pending` when there are more pods than nodes).
- Use **`RollingUpdate`**, never `Recreate`, and add a **PodDisruptionBudget**.
- Set **`terminationGracePeriodSeconds`** above the expected handoff time plus the longest job you're
  willing to wait for.
- Never scale to zero while jobs are pending.
- Keep pod clocks in sync (NTP). deferd assumes they agree within one second.

On a single pod (local development, or one replica), `REPLICATED` jobs have no second pod to back
up to, so `schedule()` raises `DurabilityNotSatisfied`. Set `default_durability="memory"` for those
environments, or use `min_replicas=0` to accept replicated jobs anyway. Those jobs have one copy
until a second pod joins, so losing that pod first loses them. deferd never downgrades a policy
silently.

## Guarantees

- **At-least-once.** A job runs at least once, unless every copy its policy keeps is lost at the
  same time.
- **Duplicates are possible** during failover, and when callers retry `schedule()`.
  **Handlers must be idempotent.** Use `ctx.job_id` as the idempotency key.
- **No silent downgrades.** If a policy can't be met (no backup available, store down),
  `schedule()` raises instead of quietly keeping fewer copies.
- **Failover time.** A pod is declared dead after 15 seconds of silence (`DEFERD_DEAD_AFTER`), then
  its backups take over. A graceful shutdown hands jobs off without that wait.

## Configuration

Every setting can be passed to `Scheduler(...)` as a keyword or set as a `DEFERD_<NAME>`
environment variable; keywords win. Durations take `30s`, `10m`, `12h` or `7d`. The ones most
deployments touch:

| Variable | Default | What |
|---|---|---|
| `DEFERD_APP_NAME` | (required) | The application's name; the same on every pod |
| `DEFERD_DISCOVERY` | `static` | `kubernetes`, or `static` with `DEFERD_SELF_ID` and `DEFERD_PEERS` |
| `DEFERD_SECRET` | (required, except alone or on loopback) | Shared secret for pod-to-pod connections |
| `DEFERD_STORE` | none | Store URL for `PERSISTED` and `DURABLE` jobs |
| `DEFERD_DEFAULT_DURABILITY` | `replicated` | Policy for jobs that don't set one |
| `DEFERD_FINISHED_RETENTION` | `7d` | How long finished persisted jobs are kept |
| `DEFERD_MAX_CONCURRENCY` | `100` | Handlers running at once per pod |
| `DEFERD_MAX_PENDING_JOBS` | `200000` | Pending jobs a pod accepts before `CapacityExceeded` |
| `DEFERD_SHUTDOWN_GRACE` | `30s` | Time allowed for handoff on shutdown; keep below the pod's grace period |
| `DEFERD_ADMIN_PORT` | `9090` | Health, metrics and debug endpoints; `0` turns them off |
| `DEFERD_LOG_JSON` | `false` | JSON logs |

The full list, with comments, is the `Settings` class in
[`src/deferd/config.py`](src/deferd/config.py).

## Monitoring

The admin server (port 9090) serves:

| Path | What |
|---|---|
| `/healthz` | Liveness: fails only when the event loop is stuck |
| `/readyz` | Readiness: the pod has joined the cluster |
| `/metrics` | Prometheus metrics, such as `deferd_jobs_pending`, `deferd_job_lateness_seconds`, `deferd_under_replicated_jobs`, `deferd_takeovers_total`, `deferd_store_up` |
| `/debug/members` | This pod's view of the cluster |
| `/debug/jobs`, `/debug/jobs/<id>` | Jobs this pod owns, and where one job is |

From a shell in a pod, `deferd inspect members` and `deferd inspect job <id>` print the same.

## Performance

Measured on one laptop, everything on localhost (`benchmarks/results.json`). Real pod-to-pod
networks add their round-trip time to `REPLICATED` calls.

| What | Result |
|---|---|
| `schedule()`, `MEMORY`, one process | about 56,000 jobs/s, p99 0.03 ms |
| `schedule()`, `REPLICATED`, three processes | about 3,700 jobs/s, p50 16 ms, p99 46 ms |
| Memory per pending job | about 0.9 KB on the owner, 1.9 KB per backup copy |
| 10,000 jobs due at the same moment | all started within 1 s (p99 0.8 s) |
| Owner killed just before a job is due | job ran 1.8 s late with `dead_after=2s`; with the default 15 s, expect about 15 s |

Run them yourself with `uv run python -m benchmarks` (see [`benchmarks/README.md`](benchmarks/README.md)).

## When not to use deferd (yet)

- Your jobs must survive every pod restarting at once, and you can't run a store for them.
- You need to cancel or deduplicate scheduled jobs (planned).
- Your handlers are sync or CPU-heavy (only async handlers are supported).
- You need exactly-once execution and can't make handlers idempotent. No system can give you that
  over a network.

## Install

```bash
pip install deferd                   # core: memory and replicated jobs
pip install "deferd[kubernetes]"     # Kubernetes discovery (uses lightkube)
pip install "deferd[mysql]"          # or [mongo], [redis], [elasticsearch]: persisted jobs
```

Requires Python 3.12+.

## Development

Requires [uv](https://docs.astral.sh/uv/).

```bash
uv sync --all-extras    # install everything
uv run pytest           # all local tests (store tests need Docker; the kind suite skips itself)
DEFERD_E2E=1 uv run pytest tests/k8s -v   # end to end on kind (needs Docker and kind)
uv run ruff check .     # lint
uv run ruff format .    # format
uv run pyright          # type check
uv run lint-imports     # architecture rules
```

`deferd.testing` ships a fake clock, a pytest plugin and a simulated cluster for testing your own
handlers, plus conformance suites for writing a store or discovery plugin.

## License

[MIT](LICENSE)
