django-reliable-outbox 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- django_reliable_outbox-0.1.0/.gitignore +22 -0
- django_reliable_outbox-0.1.0/CHANGELOG.md +43 -0
- django_reliable_outbox-0.1.0/LICENSE +21 -0
- django_reliable_outbox-0.1.0/PKG-INFO +428 -0
- django_reliable_outbox-0.1.0/README.md +391 -0
- django_reliable_outbox-0.1.0/pyproject.toml +120 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/__init__.py +36 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/admin.py +117 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/apps.py +19 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/backoff.py +32 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/checks.py +24 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/conf.py +205 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/destinations/__init__.py +35 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/destinations/base.py +21 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/destinations/kafka.py +61 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/destinations/local.py +24 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/destinations/redis.py +51 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/destinations/webhook.py +118 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/envelope.py +39 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/exceptions.py +8 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/handlers.py +40 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/inbox.py +75 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/jobs.py +141 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/management/__init__.py +0 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/management/commands/__init__.py +0 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/management/commands/outbox_cleanup.py +42 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/management/commands/outbox_requeue.py +43 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/management/commands/outbox_stats.py +28 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/management/commands/outbox_worker.py +77 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/migrations/0001_initial.py +105 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/migrations/0002_notify_trigger.py +29 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/migrations/0003_inbox.py +39 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/migrations/__init__.py +0 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/models.py +106 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/operations.py +141 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/publishing.py +131 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/py.typed +0 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/queries.py +190 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/shutdown.py +56 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/signals.py +17 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/waiting.py +121 -0
- django_reliable_outbox-0.1.0/src/reliable_outbox/worker.py +197 -0
- django_reliable_outbox-0.1.0/tests/__init__.py +0 -0
- django_reliable_outbox-0.1.0/tests/conftest.py +46 -0
- django_reliable_outbox-0.1.0/tests/helpers.py +63 -0
- django_reliable_outbox-0.1.0/tests/settings.py +70 -0
- django_reliable_outbox-0.1.0/tests/test_admin.py +86 -0
- django_reliable_outbox-0.1.0/tests/test_backoff.py +73 -0
- django_reliable_outbox-0.1.0/tests/test_concurrency.py +50 -0
- django_reliable_outbox-0.1.0/tests/test_conf.py +65 -0
- django_reliable_outbox-0.1.0/tests/test_dead_letter.py +86 -0
- django_reliable_outbox-0.1.0/tests/test_destinations.py +216 -0
- django_reliable_outbox-0.1.0/tests/test_inbox.py +95 -0
- django_reliable_outbox-0.1.0/tests/test_jobs.py +95 -0
- django_reliable_outbox-0.1.0/tests/test_leases.py +117 -0
- django_reliable_outbox-0.1.0/tests/test_models.py +30 -0
- django_reliable_outbox-0.1.0/tests/test_notify.py +114 -0
- django_reliable_outbox-0.1.0/tests/test_operations.py +123 -0
- django_reliable_outbox-0.1.0/tests/test_ordering.py +115 -0
- django_reliable_outbox-0.1.0/tests/test_publish.py +120 -0
- django_reliable_outbox-0.1.0/tests/test_shutdown.py +71 -0
- django_reliable_outbox-0.1.0/tests/test_worker.py +125 -0
- django_reliable_outbox-0.1.0/tests/testapp/__init__.py +0 -0
- django_reliable_outbox-0.1.0/tests/testapp/apps.py +7 -0
- django_reliable_outbox-0.1.0/tests/testapp/jobs.py +13 -0
- django_reliable_outbox-0.1.0/tests/testapp/migrations/0001_initial.py +33 -0
- django_reliable_outbox-0.1.0/tests/testapp/migrations/__init__.py +0 -0
- django_reliable_outbox-0.1.0/tests/testapp/models.py +16 -0
- django_reliable_outbox-0.1.0/tests/testapp/outbox_handlers.py +48 -0
- django_reliable_outbox-0.1.0/tests/urls.py +4 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
build/
|
|
6
|
+
dist/
|
|
7
|
+
.venv*/
|
|
8
|
+
|
|
9
|
+
# Tooling caches
|
|
10
|
+
.mypy_cache/
|
|
11
|
+
.pytest_cache/
|
|
12
|
+
.ruff_cache/
|
|
13
|
+
.coverage
|
|
14
|
+
htmlcov/
|
|
15
|
+
|
|
16
|
+
# Local environment
|
|
17
|
+
.env
|
|
18
|
+
*.sqlite3
|
|
19
|
+
|
|
20
|
+
# Editors
|
|
21
|
+
.idea/
|
|
22
|
+
.vscode/
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.0] - 2026-09-29
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `publish(event_type, payload, key=...)` writes an event in the caller's
|
|
14
|
+
transaction; a rollback publishes nothing. `REQUIRE_TRANSACTION` refuses
|
|
15
|
+
autocommit use.
|
|
16
|
+
- `@job(retries=..., backoff=...)` with `.enqueue()` and `.enqueue_with()`
|
|
17
|
+
(key, `run_at`, `delay`), sharing the outbox's guarantees.
|
|
18
|
+
- `manage.py outbox_worker`: `FOR UPDATE SKIP LOCKED` claims, fenced leases
|
|
19
|
+
(`locked_until`) so a dead worker's messages return, `--concurrency` threads,
|
|
20
|
+
`--burst` mode, graceful shutdown on SIGTERM/SIGINT/SIGBREAK.
|
|
21
|
+
- Handlers and the acknowledgement share one transaction, so a handler's own
|
|
22
|
+
database writes commit exactly when the message is marked delivered.
|
|
23
|
+
- Retries with exponential backoff and full jitter, or a fixed delay.
|
|
24
|
+
- Dead-letter state with the last error and traceback; `PermanentError` to skip
|
|
25
|
+
remaining attempts; `outbox_requeue` command and admin action.
|
|
26
|
+
- Per-key ordering across workers, with `BLOCK_KEY_ON_DEAD_LETTER` to choose
|
|
27
|
+
between strict order and letting a key move past a dead message.
|
|
28
|
+
- `run_at` / `delay` scheduling, measured on the database clock.
|
|
29
|
+
- `LISTEN/NOTIFY` wake-ups from a statement-level trigger, polling underneath.
|
|
30
|
+
- Destinations behind a `Destination` protocol: local `@handler` registry,
|
|
31
|
+
Redis Streams (`redis` extra), Kafka (`kafka` extra), HMAC-SHA256 signed
|
|
32
|
+
webhooks with `verify_signature` for receivers.
|
|
33
|
+
- Inbox pattern: `inbox.claim()` and `@inbox.idempotent()` for consumer-side
|
|
34
|
+
deduplication by `message_id`.
|
|
35
|
+
- Django admin with state filters (ready, in flight, scheduled, retrying),
|
|
36
|
+
search and requeue.
|
|
37
|
+
- `outbox_cleanup` (batched deletes of delivered, optionally dead and inbox
|
|
38
|
+
rows) and `outbox_stats`; `message_delivered`, `message_failed` and
|
|
39
|
+
`message_dead_lettered` signals for metrics.
|
|
40
|
+
- Typed, validated settings under `RELIABLE_OUTBOX`; `py.typed`.
|
|
41
|
+
|
|
42
|
+
[Unreleased]: https://github.com/CtrlAltDevelop/django-reliable-outbox/compare/v0.1.0...HEAD
|
|
43
|
+
[0.1.0]: https://github.com/CtrlAltDevelop/django-reliable-outbox/releases/tag/v0.1.0
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mohammad Zarif
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: django-reliable-outbox
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Transactional outbox and reliable background jobs for Django on PostgreSQL.
|
|
5
|
+
Project-URL: Homepage, https://github.com/CtrlAltDevelop/django-reliable-outbox
|
|
6
|
+
Project-URL: Source, https://github.com/CtrlAltDevelop/django-reliable-outbox
|
|
7
|
+
Project-URL: Changelog, https://github.com/CtrlAltDevelop/django-reliable-outbox/blob/main/CHANGELOG.md
|
|
8
|
+
Project-URL: Issues, https://github.com/CtrlAltDevelop/django-reliable-outbox/issues
|
|
9
|
+
Author-email: Mohammad Zarif <m.zarif1996@gmail.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: background-jobs,django,outbox,postgresql,queue,transactional-outbox
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Environment :: Web Environment
|
|
15
|
+
Classifier: Framework :: Django
|
|
16
|
+
Classifier: Framework :: Django :: 5.2
|
|
17
|
+
Classifier: Framework :: Django :: 6.0
|
|
18
|
+
Classifier: Intended Audience :: Developers
|
|
19
|
+
Classifier: Operating System :: OS Independent
|
|
20
|
+
Classifier: Programming Language :: Python :: 3
|
|
21
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Topic :: Database
|
|
26
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.12
|
|
29
|
+
Requires-Dist: django<6.1,>=5.2
|
|
30
|
+
Provides-Extra: kafka
|
|
31
|
+
Requires-Dist: confluent-kafka>=2.4; extra == 'kafka'
|
|
32
|
+
Provides-Extra: psycopg
|
|
33
|
+
Requires-Dist: psycopg[binary]>=3.2; extra == 'psycopg'
|
|
34
|
+
Provides-Extra: redis
|
|
35
|
+
Requires-Dist: redis>=5.0; extra == 'redis'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# django-reliable-outbox
|
|
39
|
+
|
|
40
|
+
[](https://github.com/CtrlAltDevelop/django-reliable-outbox/actions/workflows/ci.yml)
|
|
41
|
+

|
|
42
|
+

|
|
43
|
+

|
|
44
|
+
|
|
45
|
+
A transactional outbox and reliable background jobs for Django on PostgreSQL.
|
|
46
|
+
Publish an event or enqueue a job **in the same transaction** as the data it's
|
|
47
|
+
about. If the transaction commits, the work will happen, even if the process
|
|
48
|
+
dies on the next line. If it rolls back, the work never existed. There is no
|
|
49
|
+
broker to run for the simple case, and retries, backoff, dead-lettering and
|
|
50
|
+
per-key ordering come with it.
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from django.db import transaction
|
|
54
|
+
from reliable_outbox import publish, job
|
|
55
|
+
|
|
56
|
+
@job(retries=5, backoff="exponential")
|
|
57
|
+
def send_receipt(order_id: int) -> None: ...
|
|
58
|
+
|
|
59
|
+
with transaction.atomic():
|
|
60
|
+
order.save()
|
|
61
|
+
publish("order.created", {"id": order.id}, key=f"order-{order.id}")
|
|
62
|
+
send_receipt.enqueue(order.id) # runs only if this transaction commits
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## The problem: dual writes
|
|
66
|
+
|
|
67
|
+
Saving to the database and then telling another system about it is two writes
|
|
68
|
+
to two systems, and no transaction spans both:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
order.save() # 1. commits
|
|
72
|
+
broker.send("order.created", order.id) # 2. the process dies first: event lost
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Swap the lines and it fails the other way: the event goes out, the save fails,
|
|
76
|
+
and consumers act on an order that doesn't exist. `transaction.on_commit`
|
|
77
|
+
narrows the window but doesn't close it: a crash after the commit and before
|
|
78
|
+
the callback still loses the event.
|
|
79
|
+
|
|
80
|
+
The outbox pattern turns two writes into one. The event is a row in the same
|
|
81
|
+
database, written in the same transaction; a separate worker delivers it
|
|
82
|
+
afterwards and retries until it succeeds.
|
|
83
|
+
|
|
84
|
+
```mermaid
|
|
85
|
+
sequenceDiagram
|
|
86
|
+
autonumber
|
|
87
|
+
participant App as Django view
|
|
88
|
+
participant DB as PostgreSQL
|
|
89
|
+
participant W as outbox_worker
|
|
90
|
+
participant D as Handler / Redis / Kafka / webhook
|
|
91
|
+
|
|
92
|
+
App->>DB: BEGIN
|
|
93
|
+
App->>DB: INSERT order
|
|
94
|
+
App->>DB: INSERT outbox row (publish / enqueue)
|
|
95
|
+
App->>DB: COMMIT (both rows or neither)
|
|
96
|
+
DB-->>W: NOTIFY (only after commit)
|
|
97
|
+
W->>DB: claim: UPDATE ... FOR UPDATE SKIP LOCKED, set lease
|
|
98
|
+
W->>D: deliver
|
|
99
|
+
D-->>W: ok
|
|
100
|
+
W->>DB: mark delivered (fenced by lease)
|
|
101
|
+
Note over W,D: a crash before the ack means the lease expires and the message is delivered again (at-least-once)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Quickstart
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
pip install "django-reliable-outbox[psycopg]"
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
# settings.py
|
|
112
|
+
INSTALLED_APPS = [..., "reliable_outbox"]
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
python manage.py migrate
|
|
117
|
+
python manage.py outbox_worker # run it like any other process: systemd, k8s, supervisor
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Define handlers in an `outbox_handlers.py` (and jobs in a `jobs.py`) inside any
|
|
121
|
+
installed app; both are auto-discovered:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
# shop/outbox_handlers.py
|
|
125
|
+
from reliable_outbox import Envelope, handler
|
|
126
|
+
|
|
127
|
+
@handler("order.created") # exact name, or a pattern like "order.*"
|
|
128
|
+
def update_search_index(envelope: Envelope) -> None:
|
|
129
|
+
reindex(envelope.payload["id"])
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
[`example/`](example/) is a runnable project with a model, a service function,
|
|
133
|
+
a job and an idempotent handler.
|
|
134
|
+
|
|
135
|
+
## Guarantees
|
|
136
|
+
|
|
137
|
+
What is promised, and what isn't. Every promise marked *Yes* is exercised by
|
|
138
|
+
a test against a real PostgreSQL server (see [`tests/`](tests/)): rollback,
|
|
139
|
+
crash and lease expiry with a killed worker process, ten workers on ten
|
|
140
|
+
thousand messages, per-key order under concurrent workers and retries,
|
|
141
|
+
backoff, dead-lettering and requeue, webhook signatures, inbox dedup.
|
|
142
|
+
|
|
143
|
+
| | Guaranteed? | Details |
|
|
144
|
+
|---|---|---|
|
|
145
|
+
| **Delivery** | **At least once. Not exactly once.** | A committed message is delivered until it succeeds or runs out of attempts. It can be delivered **more than once**: if a worker dies after the destination accepted the message but before the acknowledgement commits, or its lease expires mid-run, the message goes out again. Consumers must be idempotent; see the [inbox](#inbox-deduplicating-on-the-consumer-side). |
|
|
146
|
+
| Rolled-back transaction publishes nothing | Yes | The row is part of your transaction. Savepoints too: a rolled-back `atomic()` block drops only its own messages. |
|
|
147
|
+
| Nothing lost once committed | Yes | The row is durable when `COMMIT` returns. A crashed worker's messages come back when its lease expires. |
|
|
148
|
+
| DB writes of local handlers and jobs happen once | Yes | Handlers and jobs run in the same transaction as the fenced acknowledgement. A failed or superseded run rolls back its writes. Covers the outbox's own database only. |
|
|
149
|
+
| External side effects happen once | **No** | An email sent or an HTTP call made before a crash is made again. Use idempotency keys (`envelope.message_id`) or the inbox. |
|
|
150
|
+
| Two workers never run one message at the same time | While the lease is valid | `SKIP LOCKED` and leases prevent it. If a handler outlives `LEASE_SECONDS`, another worker may start it; the slower run's DB writes are then rolled back by the fence, but its external effects are not. Set the lease longer than your slowest handler. |
|
|
151
|
+
| Per-key order | Yes, for messages sharing a `key` | One at a time, in insertion (`id`) order, across all workers, through retries. Different keys and unkeyed messages run in parallel. Concurrent transactions publishing the same key are ordered by id, not by commit; serialise them with a row lock on the aggregate if that matters ([ADR 0003](docs/adr/0003-per-key-ordering.md)). |
|
|
152
|
+
| A failed message doesn't block its key forever | Configurable | Retries always hold the key. A dead-lettered head holds it until requeued with `BLOCK_KEY_ON_DEAD_LETTER=True` (default), or lets later messages pass with `False`. |
|
|
153
|
+
| Global order across keys | No | Roughly FIFO by id, not guaranteed. |
|
|
154
|
+
| `run_at` / `delay` | Never early; may be late | Never claimed before it's due; picked up within one poll interval after. Measured by the database clock, not the app server's. |
|
|
155
|
+
| Latency | Best effort | NOTIFY wakes idle workers on commit. A lost notification falls back to polling. |
|
|
156
|
+
| Throughput | Bounded by commits | One commit per acknowledged message; see [benchmarks](#benchmarks). |
|
|
157
|
+
|
|
158
|
+
## Using it
|
|
159
|
+
|
|
160
|
+
### Events
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
publish(
|
|
164
|
+
"order.created", # event type, routed to a destination
|
|
165
|
+
{"id": 42}, # JSON (Django's encoder: dates, UUIDs, Decimals become strings)
|
|
166
|
+
key="order-42", # optional ordering key
|
|
167
|
+
delay=timedelta(minutes=5), # or run_at=aware_datetime
|
|
168
|
+
headers={"trace_id": "..."},
|
|
169
|
+
max_attempts=20, # default: RELIABLE_OUTBOX["MAX_ATTEMPTS"]
|
|
170
|
+
) # returns the message_id (UUID)
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`publish` outside `transaction.atomic()` still works: in autocommit mode the
|
|
174
|
+
insert is its own transaction and commits immediately, like any other write.
|
|
175
|
+
Set `REQUIRE_TRANSACTION = True` to make that an error, which catches the "I
|
|
176
|
+
thought this was in the transaction" bug.
|
|
177
|
+
|
|
178
|
+
### Jobs
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
@job(retries=5, backoff="exponential", name="billing.charge")
|
|
182
|
+
def charge(invoice_id: int, *, amount_cents: int) -> None: ...
|
|
183
|
+
|
|
184
|
+
charge.enqueue(7, amount_cents=1250)
|
|
185
|
+
charge.enqueue_with(args=[7], kwargs={"amount_cents": 1250}, key="customer-3", delay=timedelta(hours=1))
|
|
186
|
+
charge(7, amount_cents=1250) # still callable inline
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`retries=5` means up to six runs. Name jobs explicitly if you might move the
|
|
190
|
+
function while messages for it are queued; the default name is `module.qualname`.
|
|
191
|
+
|
|
192
|
+
### Failures
|
|
193
|
+
|
|
194
|
+
Any exception is a failed attempt, retried after
|
|
195
|
+
`uniform(0, min(BACKOFF_MAX_SECONDS, BACKOFF_BASE_SECONDS * 2 ** (attempt - 1)))`
|
|
196
|
+
seconds ([full jitter](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)),
|
|
197
|
+
or `BACKOFF_BASE_SECONDS` with `backoff="fixed"`. Raise
|
|
198
|
+
`reliable_outbox.PermanentError` for input that will never succeed, and the
|
|
199
|
+
message goes straight to the dead-letter state. Dead messages keep their last
|
|
200
|
+
error and traceback, and can be requeued with fresh attempts:
|
|
201
|
+
|
|
202
|
+
```bash
|
|
203
|
+
python manage.py outbox_requeue 1234 1235
|
|
204
|
+
python manage.py outbox_requeue --name billing.charge --dry-run
|
|
205
|
+
python manage.py outbox_requeue --all
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
or with the admin's *Requeue selected dead messages* action.
|
|
209
|
+
|
|
210
|
+
### Destinations
|
|
211
|
+
|
|
212
|
+
Events go to the `default` destination unless `ROUTES` says otherwise. Jobs
|
|
213
|
+
always run locally.
|
|
214
|
+
|
|
215
|
+
```python
|
|
216
|
+
RELIABLE_OUTBOX = {
|
|
217
|
+
"DESTINATIONS": {
|
|
218
|
+
"default": {"BACKEND": "reliable_outbox.destinations.local.LocalHandlers"},
|
|
219
|
+
"stream": {
|
|
220
|
+
"BACKEND": "reliable_outbox.destinations.redis.RedisStreamDestination",
|
|
221
|
+
"OPTIONS": {"url": "redis://localhost:6379/0", "stream": "events:{name}", "maxlen": 100_000},
|
|
222
|
+
},
|
|
223
|
+
"kafka": {
|
|
224
|
+
"BACKEND": "reliable_outbox.destinations.kafka.KafkaDestination",
|
|
225
|
+
"OPTIONS": {"topic": "{name}", "config": {"bootstrap.servers": "kafka:9092"}},
|
|
226
|
+
},
|
|
227
|
+
"partner": {
|
|
228
|
+
"BACKEND": "reliable_outbox.destinations.webhook.WebhookDestination",
|
|
229
|
+
"OPTIONS": {"url": "https://partner.example.com/hooks", "secret": env("PARTNER_HOOK_SECRET")},
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
"ROUTES": {"analytics.*": "stream", "order.*": "kafka", "partner.*": "partner"},
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
A destination is any class with `deliver(envelope) -> None` that returns once
|
|
237
|
+
the message is safely handed over and raises otherwise
|
|
238
|
+
(`reliable_outbox.destinations.Destination` is the protocol). Kafka and Redis
|
|
239
|
+
need the `kafka` / `redis` extras. Kafka delivery waits for the broker's ack
|
|
240
|
+
for each message and uses the message key as the record key, so per-key order
|
|
241
|
+
carries over into partition order.
|
|
242
|
+
|
|
243
|
+
**Webhooks** are signed with HMAC-SHA256 over `"{timestamp}.{body}"`, sent as
|
|
244
|
+
`X-Outbox-Signature: t=...,v1=...`. Receivers verify with:
|
|
245
|
+
|
|
246
|
+
```python
|
|
247
|
+
from reliable_outbox.destinations.webhook import verify_signature
|
|
248
|
+
|
|
249
|
+
if not verify_signature(request.body, request.headers["X-Outbox-Signature"], SECRET, tolerance=300):
|
|
250
|
+
return HttpResponse(status=400)
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
A 2xx response acknowledges. 408, 425, 429, 5xx and network errors are
|
|
254
|
+
retried; any other 4xx is treated as permanent.
|
|
255
|
+
|
|
256
|
+
If a destination is down for an hour, nothing is lost: its messages fail,
|
|
257
|
+
back off (capped at `BACKOFF_MAX_SECONDS`), and pile up as pending rows. Make
|
|
258
|
+
sure `MAX_ATTEMPTS` and the backoff cap together outlast the outages you
|
|
259
|
+
expect, or the oldest messages will be dead-lettered and need a requeue.
|
|
260
|
+
|
|
261
|
+
### Inbox: deduplicating on the consumer side
|
|
262
|
+
|
|
263
|
+
At-least-once means consumers see duplicates. Record the `message_id` in the
|
|
264
|
+
same transaction as the work, and a duplicate becomes a no-op:
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
from reliable_outbox import handler, inbox
|
|
268
|
+
|
|
269
|
+
@handler("order.created")
|
|
270
|
+
@inbox.idempotent("loyalty-points")
|
|
271
|
+
def award_points(envelope): ...
|
|
272
|
+
|
|
273
|
+
# or by hand, in any consumer (e.g. a webhook view):
|
|
274
|
+
with transaction.atomic():
|
|
275
|
+
if inbox.claim(message_id, consumer="loyalty-points"):
|
|
276
|
+
award_points_for(order_id)
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
`inbox.claim` refuses to run outside a transaction, where the record would
|
|
280
|
+
commit before the work it guards.
|
|
281
|
+
|
|
282
|
+
### Running workers
|
|
283
|
+
|
|
284
|
+
```bash
|
|
285
|
+
python manage.py outbox_worker --concurrency 4 # 4 threads, a connection each (+1 each for LISTEN)
|
|
286
|
+
python manage.py outbox_worker --burst # drain what's due and exit (cron, tests)
|
|
287
|
+
python manage.py outbox_worker --no-notify --poll-interval 5
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
Run as many worker processes as you like, on as many machines; they
|
|
291
|
+
coordinate through row locks alone. On SIGTERM or SIGINT (SIGBREAK on Windows)
|
|
292
|
+
a worker finishes the message in hand, returns the unstarted rest of its batch
|
|
293
|
+
to the queue and exits. A second signal stops it immediately; the leases of
|
|
294
|
+
anything in flight then expire and those messages are retried.
|
|
295
|
+
|
|
296
|
+
### Operations
|
|
297
|
+
|
|
298
|
+
```bash
|
|
299
|
+
python manage.py outbox_stats [--json] # ready, in flight, scheduled, retrying, dead, lag
|
|
300
|
+
python manage.py outbox_cleanup # delete delivered rows older than RETENTION_HOURS
|
|
301
|
+
python manage.py outbox_cleanup --older-than 24 --dead --inbox
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
Delivered rows are kept for `RETENTION_HOURS` so recent traffic can be
|
|
305
|
+
inspected; run `outbox_cleanup` from cron. Deletes are batched to keep locks
|
|
306
|
+
and WAL bursts short. At very high volume, partition the table by
|
|
307
|
+
`created_at` and drop old partitions instead.
|
|
308
|
+
|
|
309
|
+
For metrics, connect to `reliable_outbox.signals.message_delivered`
|
|
310
|
+
(`envelope`, `duration`, `queued_for`), `message_failed` (`envelope`, `error`,
|
|
311
|
+
`retry_in`) and `message_dead_lettered` (`envelope`, `error`), or export
|
|
312
|
+
`reliable_outbox.operations.stats()` from a scrape endpoint.
|
|
313
|
+
`oldest_ready_seconds` is the number to alert on.
|
|
314
|
+
|
|
315
|
+
The Django admin lists messages with filters for status and for derived states
|
|
316
|
+
(ready, in flight, scheduled, retrying), search by `message_id`, key, name or
|
|
317
|
+
error, and the requeue action. Rows are read-only there on purpose.
|
|
318
|
+
|
|
319
|
+
## Configuration
|
|
320
|
+
|
|
321
|
+
All keys are optional and validated at startup; unknown keys are an error.
|
|
322
|
+
|
|
323
|
+
| Key | Default | Meaning |
|
|
324
|
+
|---|---|---|
|
|
325
|
+
| `DATABASE` | `"default"` | Alias holding the outbox table. Must be the database your business data is in, or `publish` stops being atomic with it. |
|
|
326
|
+
| `REQUIRE_TRANSACTION` | `False` | Raise `NotInTransaction` when publishing or enqueueing in autocommit mode. |
|
|
327
|
+
| `BATCH_SIZE` | `10` | Messages claimed per round trip. |
|
|
328
|
+
| `LEASE_SECONDS` | `60` | How long a claim is exclusive. Must exceed your slowest handler. Also the recovery delay after a worker crash. |
|
|
329
|
+
| `POLL_INTERVAL` | `1.0` | Longest an idle worker sleeps: the latency bound when NOTIFY is off or a notification is lost, and how late a retry or scheduled message may start. |
|
|
330
|
+
| `NOTIFY` | `True` | LISTEN for inserts (needs psycopg 3; otherwise polls, with a warning). |
|
|
331
|
+
| `MAX_ATTEMPTS` | `10` | Attempts for events. Jobs use `retries + 1`. |
|
|
332
|
+
| `BACKOFF` | `"exponential"` | `"exponential"` (full jitter) or `"fixed"`, for events. Jobs set their own. |
|
|
333
|
+
| `BACKOFF_BASE_SECONDS` | `1.0` | Base of the retry delay. |
|
|
334
|
+
| `BACKOFF_MAX_SECONDS` | `3600.0` | Cap on the retry delay. |
|
|
335
|
+
| `BLOCK_KEY_ON_DEAD_LETTER` | `True` | Whether a dead message holds back later messages of its key. |
|
|
336
|
+
| `DESTINATIONS` | local handlers | Name → `{"BACKEND": "dotted.path", "OPTIONS": {...}}`. Must include `"default"`. |
|
|
337
|
+
| `ROUTES` | `{}` | `fnmatch` pattern → destination name; first match wins. |
|
|
338
|
+
| `RETENTION_HOURS` | `168` | Default age for `outbox_cleanup`. |
|
|
339
|
+
| `AUTODISCOVER` | `("jobs", "outbox_handlers")` | Modules imported from every installed app at startup. |
|
|
340
|
+
|
|
341
|
+
## Benchmarks
|
|
342
|
+
|
|
343
|
+
Measured on a 2017 laptop (i7-7700HQ, Windows 11, PostgreSQL 16 in Docker
|
|
344
|
+
Desktop with default `fsync=on`, where one durable commit took about 9 ms),
|
|
345
|
+
with worker processes and no-op handlers. Method, raw results and caveats are
|
|
346
|
+
in [`bench/`](bench/README.md); run `make bench` for numbers from your own
|
|
347
|
+
hardware.
|
|
348
|
+
|
|
349
|
+
| Workers | Messages/second |
|
|
350
|
+
|---:|---:|
|
|
351
|
+
| 1 | 104 |
|
|
352
|
+
| 4 | 242 |
|
|
353
|
+
| 16 | 840 |
|
|
354
|
+
|
|
355
|
+
| Commit → handler start | p50 | p95 | p99 |
|
|
356
|
+
|---|---:|---:|---:|
|
|
357
|
+
| Polling every 1 s | 568 ms | 1,014 ms | 1,085 ms |
|
|
358
|
+
| LISTEN/NOTIFY | 19 ms | 34 ms | 67 ms |
|
|
359
|
+
|
|
360
|
+
One worker is bound by commit latency: each message is one durable commit,
|
|
361
|
+
because the acknowledgement and the handler's writes commit together.
|
|
362
|
+
Concurrent workers share WAL flushes, so they scale, though not linearly. A
|
|
363
|
+
second run on the same machine gave 68 / 233 / 417 messages/second, so read
|
|
364
|
+
these as orders of magnitude. There is no Celery number here because a fair
|
|
365
|
+
comparison hasn't been run; a broker will beat these throughput figures
|
|
366
|
+
comfortably, and that's expected.
|
|
367
|
+
|
|
368
|
+
## How it compares
|
|
369
|
+
|
|
370
|
+
**Celery** (with Redis or RabbitMQ) is the default choice for background work
|
|
371
|
+
in Django, for good reason: it is mature, with a huge ecosystem, rate limits,
|
|
372
|
+
chords and canvases, routing across many queues, periodic tasks with beat, and
|
|
373
|
+
a broker built for throughput. It isn't transactional with your database.
|
|
374
|
+
`delay()` inside a transaction can run the task before the commit (the classic
|
|
375
|
+
"object does not exist" race) or send it for a transaction that later rolls
|
|
376
|
+
back. `delay_on_commit()` / `transaction.on_commit` fix the first problem but
|
|
377
|
+
still lose the task if the process dies between the commit and the send.
|
|
378
|
+
`acks_late` gives at-least-once *execution* once the broker has the message;
|
|
379
|
+
getting it there is the dual-write problem. If you need high throughput,
|
|
380
|
+
low-latency dispatch, workflows, or many heterogeneous queues, Celery is the
|
|
381
|
+
better tool. Put an outbox in front of it for the events that must not be lost:
|
|
382
|
+
a destination whose `deliver` calls `task.delay()` is a few lines.
|
|
383
|
+
|
|
384
|
+
**Dramatiq** is simpler than Celery, with safer defaults (acknowledge after
|
|
385
|
+
processing, retries with backoff, dead-lettering), so its reliability story is
|
|
386
|
+
better out of the box. It still needs a broker and still has the gap between
|
|
387
|
+
your transaction and the enqueue.
|
|
388
|
+
|
|
389
|
+
**django-q2** can use the Django ORM as its broker, which makes enqueueing
|
|
390
|
+
transactional when configured that way. It is a general task queue with
|
|
391
|
+
scheduling, a cluster monitor and result storage, none of which this library
|
|
392
|
+
has. As far as I can tell it doesn't offer per-key ordering, fenced leases
|
|
393
|
+
that roll back a superseded run, event destinations, or an inbox.
|
|
394
|
+
|
|
395
|
+
**This library** is narrower on purpose: it makes "this happened, so that must
|
|
396
|
+
happen" reliable, with the guarantees above. It doesn't do result backends,
|
|
397
|
+
task chaining, rate limiting, cron schedules, priorities or named queues. Its
|
|
398
|
+
throughput is bounded by PostgreSQL commits: plenty for domain events and
|
|
399
|
+
follow-up jobs, too little for a firehose. The closest relative is
|
|
400
|
+
[procrastinate](https://github.com/procrastinate-org/procrastinate), a
|
|
401
|
+
PostgreSQL task queue that also uses LISTEN/NOTIFY and has per-lock
|
|
402
|
+
serialisation. The difference here is an event-publishing API with pluggable
|
|
403
|
+
destinations, handlers that commit atomically with their acknowledgement, and
|
|
404
|
+
the inbox, as a plain Django app.
|
|
405
|
+
|
|
406
|
+
## Design notes
|
|
407
|
+
|
|
408
|
+
The decisions behind the guarantees are written up as ADRs in
|
|
409
|
+
[`docs/adr/`](docs/adr/):
|
|
410
|
+
|
|
411
|
+
- [0001: `SKIP LOCKED` over advisory locks](docs/adr/0001-skip-locked-over-advisory-locks.md)
|
|
412
|
+
- [0002: leases with a fencing token](docs/adr/0002-lease-model.md)
|
|
413
|
+
- [0003: per-key ordering](docs/adr/0003-per-key-ordering.md)
|
|
414
|
+
- [0004: at-least-once, and the inbox](docs/adr/0004-at-least-once-and-inbox.md)
|
|
415
|
+
- [0005: NOTIFY trigger with polling fallback](docs/adr/0005-notify-trigger-with-polling-fallback.md)
|
|
416
|
+
|
|
417
|
+
## Development
|
|
418
|
+
|
|
419
|
+
```bash
|
|
420
|
+
make install && make pg-up && make check
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). To report a vulnerability, see
|
|
424
|
+
[SECURITY.md](SECURITY.md).
|
|
425
|
+
|
|
426
|
+
## License
|
|
427
|
+
|
|
428
|
+
MIT © 2026 Mohammad Zarif
|