deferd 0.0.1__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.
Files changed (190) hide show
  1. deferd-0.0.1/.github/workflows/ci.yml +18 -0
  2. deferd-0.0.1/.github/workflows/e2e.yml +38 -0
  3. deferd-0.0.1/.gitignore +12 -0
  4. deferd-0.0.1/.python-version +1 -0
  5. deferd-0.0.1/CHANGELOG.md +59 -0
  6. deferd-0.0.1/LICENSE +21 -0
  7. deferd-0.0.1/PKG-INFO +348 -0
  8. deferd-0.0.1/README.md +317 -0
  9. deferd-0.0.1/benchmarks/README.md +76 -0
  10. deferd-0.0.1/benchmarks/__init__.py +1 -0
  11. deferd-0.0.1/benchmarks/__main__.py +60 -0
  12. deferd-0.0.1/benchmarks/_common.py +196 -0
  13. deferd-0.0.1/benchmarks/app.py +28 -0
  14. deferd-0.0.1/benchmarks/bench_failover.py +87 -0
  15. deferd-0.0.1/benchmarks/bench_lateness.py +75 -0
  16. deferd-0.0.1/benchmarks/bench_memory.py +219 -0
  17. deferd-0.0.1/benchmarks/bench_throughput.py +114 -0
  18. deferd-0.0.1/benchmarks/results.json +126 -0
  19. deferd-0.0.1/deploy/compose/Dockerfile +15 -0
  20. deferd-0.0.1/deploy/compose/README.md +55 -0
  21. deferd-0.0.1/deploy/compose/docker-compose.yml +42 -0
  22. deferd-0.0.1/deploy/kind/Dockerfile +18 -0
  23. deferd-0.0.1/deploy/kind/Dockerfile.dockerignore +12 -0
  24. deferd-0.0.1/deploy/kind/e2eapp/__init__.py +0 -0
  25. deferd-0.0.1/deploy/kind/e2eapp/jobs.py +160 -0
  26. deferd-0.0.1/deploy/kind/e2eapp/loadgen.py +158 -0
  27. deferd-0.0.1/deploy/kind/e2eapp/schedule.py +39 -0
  28. deferd-0.0.1/deploy/kind/e2eapp/sink.py +133 -0
  29. deferd-0.0.1/deploy/kind/e2eapp/web.py +91 -0
  30. deferd-0.0.1/deploy/kind/kind-config.yaml +13 -0
  31. deferd-0.0.1/deploy/kind/kustomization.yaml +118 -0
  32. deferd-0.0.1/deploy/kind/node-reader.yaml +23 -0
  33. deferd-0.0.1/deploy/kind/redis.yaml +53 -0
  34. deferd-0.0.1/deploy/kind/sink.yaml +51 -0
  35. deferd-0.0.1/deploy/kubernetes/README.md +113 -0
  36. deferd-0.0.1/deploy/kubernetes/deployment.yaml +104 -0
  37. deferd-0.0.1/deploy/kubernetes/kustomization.yaml +11 -0
  38. deferd-0.0.1/deploy/kubernetes/networkpolicy.yaml +31 -0
  39. deferd-0.0.1/deploy/kubernetes/pdb.yaml +12 -0
  40. deferd-0.0.1/deploy/kubernetes/rbac.yaml +55 -0
  41. deferd-0.0.1/deploy/kubernetes/secret.example.yaml +16 -0
  42. deferd-0.0.1/deploy/kubernetes/service.yaml +16 -0
  43. deferd-0.0.1/examples/consumer/README.md +55 -0
  44. deferd-0.0.1/examples/consumer/consumer.py +75 -0
  45. deferd-0.0.1/examples/fastapi_embedded/README.md +43 -0
  46. deferd-0.0.1/examples/fastapi_embedded/app.py +29 -0
  47. deferd-0.0.1/examples/fastapi_embedded/jobs.py +28 -0
  48. deferd-0.0.1/examples/fastapi_gunicorn/README.md +46 -0
  49. deferd-0.0.1/examples/fastapi_gunicorn/app.py +23 -0
  50. deferd-0.0.1/examples/fastapi_gunicorn/jobs.py +31 -0
  51. deferd-0.0.1/pyproject.toml +116 -0
  52. deferd-0.0.1/src/deferd/__init__.py +40 -0
  53. deferd-0.0.1/src/deferd/__main__.py +8 -0
  54. deferd-0.0.1/src/deferd/admin.py +194 -0
  55. deferd-0.0.1/src/deferd/cli.py +177 -0
  56. deferd-0.0.1/src/deferd/clock.py +32 -0
  57. deferd-0.0.1/src/deferd/cluster/__init__.py +1 -0
  58. deferd-0.0.1/src/deferd/cluster/discovery/__init__.py +0 -0
  59. deferd-0.0.1/src/deferd/cluster/discovery/base.py +38 -0
  60. deferd-0.0.1/src/deferd/cluster/discovery/kubernetes.py +461 -0
  61. deferd-0.0.1/src/deferd/cluster/discovery/static.py +41 -0
  62. deferd-0.0.1/src/deferd/cluster/member.py +47 -0
  63. deferd-0.0.1/src/deferd/cluster/membership.py +512 -0
  64. deferd-0.0.1/src/deferd/cluster/network/__init__.py +0 -0
  65. deferd-0.0.1/src/deferd/cluster/network/base.py +58 -0
  66. deferd-0.0.1/src/deferd/cluster/network/tcp.py +460 -0
  67. deferd-0.0.1/src/deferd/cluster/network/wire.py +229 -0
  68. deferd-0.0.1/src/deferd/config.py +411 -0
  69. deferd-0.0.1/src/deferd/engine/__init__.py +1 -0
  70. deferd-0.0.1/src/deferd/engine/engine.py +452 -0
  71. deferd-0.0.1/src/deferd/engine/executor.py +117 -0
  72. deferd-0.0.1/src/deferd/engine/handlers.py +53 -0
  73. deferd-0.0.1/src/deferd/engine/timer.py +64 -0
  74. deferd-0.0.1/src/deferd/engine/watchdog.py +66 -0
  75. deferd-0.0.1/src/deferd/errors.py +41 -0
  76. deferd-0.0.1/src/deferd/jobs/__init__.py +7 -0
  77. deferd-0.0.1/src/deferd/jobs/durability.py +116 -0
  78. deferd-0.0.1/src/deferd/jobs/job.py +201 -0
  79. deferd-0.0.1/src/deferd/jobs/payload.py +53 -0
  80. deferd-0.0.1/src/deferd/jobs/retry.py +38 -0
  81. deferd-0.0.1/src/deferd/local.py +444 -0
  82. deferd-0.0.1/src/deferd/log.py +35 -0
  83. deferd-0.0.1/src/deferd/metrics.py +86 -0
  84. deferd-0.0.1/src/deferd/node.py +775 -0
  85. deferd-0.0.1/src/deferd/persistence.py +357 -0
  86. deferd-0.0.1/src/deferd/py.typed +0 -0
  87. deferd-0.0.1/src/deferd/replication/__init__.py +1 -0
  88. deferd-0.0.1/src/deferd/replication/backup.py +431 -0
  89. deferd-0.0.1/src/deferd/replication/handoff.py +172 -0
  90. deferd-0.0.1/src/deferd/replication/messages.py +151 -0
  91. deferd-0.0.1/src/deferd/replication/owner.py +663 -0
  92. deferd-0.0.1/src/deferd/replication/placement.py +70 -0
  93. deferd-0.0.1/src/deferd/replication/replication.py +447 -0
  94. deferd-0.0.1/src/deferd/scheduler.py +203 -0
  95. deferd-0.0.1/src/deferd/stores/__init__.py +1 -0
  96. deferd-0.0.1/src/deferd/stores/base.py +139 -0
  97. deferd-0.0.1/src/deferd/stores/elasticsearch/__init__.py +1 -0
  98. deferd-0.0.1/src/deferd/stores/elasticsearch/store.py +468 -0
  99. deferd-0.0.1/src/deferd/stores/memory.py +133 -0
  100. deferd-0.0.1/src/deferd/stores/mongo/__init__.py +1 -0
  101. deferd-0.0.1/src/deferd/stores/mongo/indexes.py +11 -0
  102. deferd-0.0.1/src/deferd/stores/mongo/store.py +335 -0
  103. deferd-0.0.1/src/deferd/stores/mysql/__init__.py +1 -0
  104. deferd-0.0.1/src/deferd/stores/mysql/migrations/.gitkeep +0 -0
  105. deferd-0.0.1/src/deferd/stores/mysql/migrations/0001_create_jobs.sql +28 -0
  106. deferd-0.0.1/src/deferd/stores/mysql/migrations/0002_create_apps.sql +11 -0
  107. deferd-0.0.1/src/deferd/stores/mysql/schema.sql +35 -0
  108. deferd-0.0.1/src/deferd/stores/mysql/store.py +437 -0
  109. deferd-0.0.1/src/deferd/stores/redis/__init__.py +1 -0
  110. deferd-0.0.1/src/deferd/stores/redis/keys.py +36 -0
  111. deferd-0.0.1/src/deferd/stores/redis/scripts/claim_app.lua +32 -0
  112. deferd-0.0.1/src/deferd/stores/redis/scripts/claim_owner.lua +63 -0
  113. deferd-0.0.1/src/deferd/stores/redis/scripts/delete_finished.lua +15 -0
  114. deferd-0.0.1/src/deferd/stores/redis/scripts/insert_if_absent.lua +35 -0
  115. deferd-0.0.1/src/deferd/stores/redis/scripts/update_if_version.lua +51 -0
  116. deferd-0.0.1/src/deferd/stores/redis/store.py +263 -0
  117. deferd-0.0.1/src/deferd/stores/registry.py +43 -0
  118. deferd-0.0.1/src/deferd/testing/__init__.py +6 -0
  119. deferd-0.0.1/src/deferd/testing/conformance/__init__.py +1 -0
  120. deferd-0.0.1/src/deferd/testing/conformance/discovery.py +116 -0
  121. deferd-0.0.1/src/deferd/testing/conformance/store.py +435 -0
  122. deferd-0.0.1/src/deferd/testing/conformance/transport.py +245 -0
  123. deferd-0.0.1/src/deferd/testing/fake_clock.py +101 -0
  124. deferd-0.0.1/src/deferd/testing/pytest_plugin.py +120 -0
  125. deferd-0.0.1/src/deferd/testing/sim/__init__.py +31 -0
  126. deferd-0.0.1/src/deferd/testing/sim/faults.py +149 -0
  127. deferd-0.0.1/src/deferd/testing/sim/harness.py +842 -0
  128. deferd-0.0.1/src/deferd/testing/sim/invariants.py +331 -0
  129. deferd-0.0.1/src/deferd/testing/sim/network.py +346 -0
  130. deferd-0.0.1/tests/cluster/loopback.py +281 -0
  131. deferd-0.0.1/tests/cluster/test_kubernetes_discovery.py +430 -0
  132. deferd-0.0.1/tests/cluster/test_membership.py +438 -0
  133. deferd-0.0.1/tests/cluster/test_static_discovery.py +58 -0
  134. deferd-0.0.1/tests/cluster/test_tcp.py +301 -0
  135. deferd-0.0.1/tests/cluster/test_wire.py +250 -0
  136. deferd-0.0.1/tests/conftest.py +1 -0
  137. deferd-0.0.1/tests/engine/test_engine.py +286 -0
  138. deferd-0.0.1/tests/engine/test_executor.py +203 -0
  139. deferd-0.0.1/tests/engine/test_timer_catchup.py +179 -0
  140. deferd-0.0.1/tests/engine/test_watchdog.py +89 -0
  141. deferd-0.0.1/tests/helpers.py +39 -0
  142. deferd-0.0.1/tests/integration/app.py +20 -0
  143. deferd-0.0.1/tests/integration/conftest.py +9 -0
  144. deferd-0.0.1/tests/integration/test_localhost_cluster.py +235 -0
  145. deferd-0.0.1/tests/jobs/test_durability_retry_payload.py +222 -0
  146. deferd-0.0.1/tests/jobs/test_job.py +203 -0
  147. deferd-0.0.1/tests/k8s/.gitkeep +0 -0
  148. deferd-0.0.1/tests/k8s/README.md +77 -0
  149. deferd-0.0.1/tests/k8s/conftest.py +78 -0
  150. deferd-0.0.1/tests/k8s/k8s_helpers.py +597 -0
  151. deferd-0.0.1/tests/k8s/test_e2e.py +191 -0
  152. deferd-0.0.1/tests/k8s/test_load.py +346 -0
  153. deferd-0.0.1/tests/k8s/test_scenarios.py +227 -0
  154. deferd-0.0.1/tests/node/cluster.py +131 -0
  155. deferd-0.0.1/tests/node/conftest.py +49 -0
  156. deferd-0.0.1/tests/node/test_admin.py +161 -0
  157. deferd-0.0.1/tests/node/test_api.py +134 -0
  158. deferd-0.0.1/tests/node/test_cli.py +114 -0
  159. deferd-0.0.1/tests/node/test_job_host.py +186 -0
  160. deferd-0.0.1/tests/node/test_local.py +303 -0
  161. deferd-0.0.1/tests/node/test_metrics_logging.py +87 -0
  162. deferd-0.0.1/tests/node/test_node.py +187 -0
  163. deferd-0.0.1/tests/node/test_scheduler.py +495 -0
  164. deferd-0.0.1/tests/node/test_serve.py +157 -0
  165. deferd-0.0.1/tests/persistence/test_persistence.py +434 -0
  166. deferd-0.0.1/tests/persistence/test_phase2_guarantees.py +201 -0
  167. deferd-0.0.1/tests/replication/harness.py +432 -0
  168. deferd-0.0.1/tests/replication/test_backup.py +314 -0
  169. deferd-0.0.1/tests/replication/test_messages.py +103 -0
  170. deferd-0.0.1/tests/replication/test_multi_backup.py +147 -0
  171. deferd-0.0.1/tests/replication/test_placement.py +297 -0
  172. deferd-0.0.1/tests/sim/test_chaos.py +322 -0
  173. deferd-0.0.1/tests/sim/test_chaos_regressions.py +178 -0
  174. deferd-0.0.1/tests/sim/test_milestones.py +331 -0
  175. deferd-0.0.1/tests/sim/test_multi_backup.py +163 -0
  176. deferd-0.0.1/tests/sim/test_multi_backup_more.py +127 -0
  177. deferd-0.0.1/tests/sim/test_network.py +327 -0
  178. deferd-0.0.1/tests/sim/test_replication.py +134 -0
  179. deferd-0.0.1/tests/sim/test_replication_failures.py +247 -0
  180. deferd-0.0.1/tests/sim/test_replication_handoff.py +136 -0
  181. deferd-0.0.1/tests/stores/test_elasticsearch_store.py +79 -0
  182. deferd-0.0.1/tests/stores/test_memory_store.py +16 -0
  183. deferd-0.0.1/tests/stores/test_mongo_store.py +64 -0
  184. deferd-0.0.1/tests/stores/test_mysql_store.py +97 -0
  185. deferd-0.0.1/tests/stores/test_redis_store.py +110 -0
  186. deferd-0.0.1/tests/stores/test_registry.py +69 -0
  187. deferd-0.0.1/tests/test_config.py +271 -0
  188. deferd-0.0.1/tests/test_import.py +6 -0
  189. deferd-0.0.1/tests/testing/test_fake_clock.py +59 -0
  190. deferd-0.0.1/uv.lock +1992 -0
@@ -0,0 +1,18 @@
1
+ name: ci
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ jobs:
8
+ check:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ - uses: astral-sh/setup-uv@v6
13
+ - run: uv sync --all-extras
14
+ - run: uv run ruff check .
15
+ - run: uv run ruff format --check .
16
+ - run: uv run pyright
17
+ - run: uv run lint-imports
18
+ - run: uv run pytest
@@ -0,0 +1,38 @@
1
+ name: e2e
2
+
3
+ # Kubernetes end-to-end suite on kind. Slow (about 10-20 minutes), so not on every PR.
4
+ on:
5
+ workflow_dispatch:
6
+ push:
7
+ branches: [main]
8
+
9
+ concurrency:
10
+ group: e2e-${{ github.ref }}
11
+ cancel-in-progress: true
12
+
13
+ jobs:
14
+ kind:
15
+ runs-on: ubuntu-latest
16
+ timeout-minutes: 60
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+ - uses: astral-sh/setup-uv@v6
20
+ - uses: helm/kind-action@v1
21
+ with:
22
+ version: v0.24.0
23
+ install_only: true # the test suite creates its own 1+3 node cluster
24
+ - run: uv sync --all-extras
25
+ - name: Run the Kubernetes e2e suite
26
+ env:
27
+ DEFERD_E2E: "1"
28
+ DEFERD_E2E_ARTIFACTS: ${{ github.workspace }}/build/e2e-artifacts
29
+ run: uv run pytest tests/k8s -v -s
30
+ - name: Upload kubectl logs
31
+ if: failure()
32
+ uses: actions/upload-artifact@v4
33
+ with:
34
+ name: e2e-artifacts
35
+ path: |
36
+ build/e2e-artifacts
37
+ build/e2e-logs
38
+ if-no-files-found: ignore
@@ -0,0 +1,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ .coverage
10
+ htmlcov/
11
+ docs/
12
+ .import_linter_cache/
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,59 @@
1
+ # Changelog
2
+
3
+ All notable changes are recorded here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.0.1] - 2026-11-29
8
+
9
+ ### Added
10
+ - `Durability(min_replicas=...)`: `schedule()` waits for that many backups. With `min_replicas=0`,
11
+ a replicated job is accepted with no backup when no other pod is free, and
12
+ `deferd_accepted_without_backup_total` counts those jobs.
13
+ - Up to three backups per job with `Durability(replicas=...)`, placed on different nodes where
14
+ possible.
15
+ - Ranked takeover: the first backup takes over at once, and each later one waits
16
+ `takeover_stagger` (10 s) more. If two backups take over at the same version, the lower member
17
+ id keeps the job.
18
+ - Settings `takeover_stagger` and `max_backup_copies` (400,000 copies a pod holds for others).
19
+ - Simulation chaos tests for jobs with several backups.
20
+ - Persistence. `Scheduler(store=...)` (or `DEFERD_STORE`) takes a MySQL (`mysql://`), MongoDB
21
+ (`mongodb://`), Redis (`redis://`) or in-memory (`memory://`) store. The URL can carry
22
+ `?app_name=` (defaults to the scheduler's `app_name`), and MySQL also takes `?table=`.
23
+ - Elasticsearch store (`elasticsearch://`, extra `deferd[elasticsearch]`), with conditional writes on
24
+ `if_seq_no` and `if_primary_term`.
25
+ - `PERSISTED` and `DURABLE` policies. The store insert is the commit point, and for `DURABLE` the
26
+ backup follows it. Every state change of a persisted job is a conditional write on its version
27
+ and owner, so the store settles any ownership race.
28
+ - Recovery of persisted jobs: a pod claims the jobs of owners that are gone when it starts, then
29
+ every 10 seconds. A takeover claims a persisted job in the store before it adopts it.
30
+ - While the store is unreachable, `schedule()` of a persisted job raises `DurabilityNotSatisfied`,
31
+ running jobs continue, and `/readyz` reports "ready (store unreachable)".
32
+ - Cleanup of finished jobs, kept for the handler's `retain_for`, else `finished_retention` (default
33
+ 7 days, at least 10 minutes).
34
+ - A pod starts while the store is unreachable. Persisted jobs are refused until the store connects,
35
+ and the pod recovers its jobs then.
36
+ - One application per `app_name` in a store. With Kubernetes discovery, a second application under
37
+ the same name is refused at startup. Settings `app_name_takeover` and `app_stale_after` control
38
+ replacement.
39
+ - `deferd migrate --store URL` creates the MySQL schema (numbered migrations) and MongoDB indexes.
40
+ `deferd check --store URL` prints the store's health, safety and notes.
41
+ - Metrics `deferd_store_pending_writes`, `deferd_store_up` and `deferd_store_claimed_total`.
42
+ - Settings `store`, `finished_retention`, `recovery_interval`, `cleanup_interval`,
43
+ `store_claim_batch` and `allow_unsafe_store`. A store that is UNSAFE, such as Redis without AOF,
44
+ is refused at startup unless `allow_unsafe_store` is set.
45
+
46
+ - A pod without permission to read pods stops at startup with a message that names the service
47
+ account and the RBAC to add (`deploy/kubernetes/rbac.yaml`), instead of the bare API error.
48
+
49
+ ### Changed
50
+ - `namespace` is renamed to `app_name`: `Scheduler(app_name=...)`, env `DEFERD_APP_NAME`, and the store
51
+ URL option `?app_name=`. It names the application, not the Kubernetes namespace.
52
+ - Rewrote the package for readability: `jobs/`, `engine/`, `cluster/` (membership, discovery,
53
+ network), `replication/`, plus `node.py`, `scheduler.py`, `local.py` and `admin.py`. The
54
+ public API (`deferd.Scheduler`, `Durability`, errors, `deferd.testing`) is unchanged.
55
+ - The web-worker client moved to `deferd.local` (`LocalClient`, `SyncLocalClient`).
56
+ - Metrics are always served as Prometheus text from an in-memory registry; the `prometheus`
57
+ extra is gone.
58
+ - Failure detection is part of membership; Kubernetes node readiness comes from discovery
59
+ instead of a second pod watch.
deferd-0.0.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pranav Tyagi
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.
deferd-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,348 @@
1
+ Metadata-Version: 2.5
2
+ Name: deferd
3
+ Version: 0.0.1
4
+ Summary: Delayed jobs for Python services on Kubernetes. No broker, no polling, no new infrastructure.
5
+ Author-email: Pranav Tyagi <pranavww@gmail.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: msgpack>=1.0
10
+ Provides-Extra: all
11
+ Requires-Dist: aiomysql>=0.2; extra == 'all'
12
+ Requires-Dist: cryptography>=42; extra == 'all'
13
+ Requires-Dist: elasticsearch[async]<9,>=8.13; extra == 'all'
14
+ Requires-Dist: lightkube>=0.15; extra == 'all'
15
+ Requires-Dist: pymongo>=4.13; extra == 'all'
16
+ Requires-Dist: redis>=5.0; extra == 'all'
17
+ Provides-Extra: elasticsearch
18
+ Requires-Dist: elasticsearch[async]<9,>=8.13; extra == 'elasticsearch'
19
+ Provides-Extra: kubernetes
20
+ Requires-Dist: lightkube>=0.15; extra == 'kubernetes'
21
+ Provides-Extra: mongo
22
+ Requires-Dist: pymongo>=4.13; extra == 'mongo'
23
+ Provides-Extra: mysql
24
+ Requires-Dist: aiomysql>=0.2; extra == 'mysql'
25
+ Requires-Dist: cryptography>=42; extra == 'mysql'
26
+ Provides-Extra: otel
27
+ Requires-Dist: opentelemetry-api>=1.25; extra == 'otel'
28
+ Provides-Extra: redis
29
+ Requires-Dist: redis>=5.0; extra == 'redis'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # deferd
33
+
34
+ Delayed jobs for Python services on Kubernetes. **No broker, no polling, and no new infrastructure.**
35
+ Your pods hold the jobs and back each other up; add a database only if you want jobs to survive
36
+ everything restarting at once.
37
+
38
+ **Status:** pre-alpha. The API may still change.
39
+
40
+ ---
41
+
42
+ ## The problem
43
+
44
+ A request arrives at a FastAPI endpoint, or a message arrives at a consumer, and the requirement is:
45
+ *"do this 30 minutes from now."* Send a reminder, expire a hold, follow up on a payment.
46
+
47
+ Today that usually means adding Redis and Celery, or a database-backed queue that polls constantly.
48
+ That's infrastructure to run, monitor, and pay for, just to wait 30 minutes.
49
+
50
+ ## How deferd works
51
+
52
+ - The pod that receives a job owns it and keeps its timer **in memory**. Timers fire at the right
53
+ moment; nothing polls.
54
+ - Each job is copied to **backup pods on other nodes** (one by default, up to three) before
55
+ `schedule()` returns. If every pod is on one node, the backups go on that node and the job is
56
+ reported as weakly placed.
57
+ - If the owner dies, a backup takes over. If a pod shuts down, it hands its jobs off first.
58
+ - For jobs that must survive anything, deferd also writes them to a store you already run:
59
+ **MySQL, MongoDB, Redis or Elasticsearch.**
60
+
61
+ ## Quick start
62
+
63
+ ```python
64
+ from datetime import timedelta
65
+ from deferd import Durability, JobContext, Scheduler
66
+
67
+ scheduler = Scheduler(
68
+ app_name="orders",
69
+ discovery="kubernetes", # or "static" for local development
70
+ )
71
+
72
+
73
+ @scheduler.handler(timeout=timedelta(minutes=5), max_attempts=5)
74
+ async def send_reminder(payload: dict, ctx: JobContext) -> None:
75
+ ... # ctx.job_id is the idempotency key
76
+
77
+
78
+ @scheduler.handler(durability=Durability.MEMORY, expires_after=timedelta(minutes=10))
79
+ async def warm_cache(payload: dict, ctx: JobContext) -> None:
80
+ ...
81
+
82
+
83
+ async with scheduler.run(): # joins the cluster; leaves gracefully on exit
84
+ await scheduler.schedule("send_reminder", {"order_id": 123}, delay=timedelta(minutes=30))
85
+ ... # the rest of your service
86
+ ```
87
+
88
+ Every handler receives `(payload, ctx)`. `ctx.job_id` is the same across retries and duplicate runs,
89
+ so use it as the idempotency key. Pass `delay` or `at` to `schedule()`, not both. With neither, the job
90
+ runs as soon as possible. Handlers must be `async`.
91
+
92
+ Use one `app_name` per application. Every pod of the app uses the same value, and different
93
+ applications must use different values, even in the same Kubernetes namespace or database.
94
+
95
+ To react when a job finishes, pass `on_succeeded`, `on_dead` (out of attempts) or `on_expired`
96
+ to `Scheduler`. Each is called with the job.
97
+
98
+ ## Durability, chosen per job
99
+
100
+ | Preset | Copies | Survives | Cost | Needs |
101
+ |---|---|---|---|---|
102
+ | `MEMORY` | Owner only | Nothing beyond the process | Free | Nothing |
103
+ | `REPLICATED` (default) | Owner + backup pod | Pod and node failures, rolling deploys | One network round trip | A second pod |
104
+ | `PERSISTED` | Owner + store | Everything, with slower failover | One store write | A store |
105
+ | `DURABLE` | Owner + backup + store | Everything, with fast failover | Both | A store |
106
+
107
+ Set it per handler (`@scheduler.handler(durability=...)`), per call (`schedule(..., durability=...)`)
108
+ or for the whole app (`default_durability=`). A preset can be given as a `Durability` value or by
109
+ name (`"memory"`, `"replicated"`, ...). `PERSISTED` and `DURABLE` without a store raise
110
+ `ConfigurationError`.
111
+
112
+ `replicas` sets how many backups a job gets (0 to 3). `min_replicas` sets how many must acknowledge
113
+ before `schedule()` returns:
114
+
115
+ ```python
116
+ Durability(replicas=2, min_replicas=1) # three copies; returns once one backup acknowledges
117
+ Durability(replicas=1, min_replicas=0) # accepted even with no other pod; backed up when one joins
118
+ ```
119
+
120
+ Pods on an older deferd version can't read a policy with `min_replicas`, so upgrade every pod first.
121
+
122
+ ### Persisting jobs
123
+
124
+ `PERSISTED` and `DURABLE` jobs need a store. Pass one as a URL, or set `DEFERD_STORE`:
125
+
126
+ ```python
127
+ scheduler = Scheduler(app_name="orders", store="mysql://user:pass@db:3306/app")
128
+ ```
129
+
130
+ | Store | URL | Extra | Notes |
131
+ |---|---|---|---|
132
+ | MySQL 8 / MariaDB 10.6+ | `mysql://user:pass@host:3306/db` | `deferd[mysql]` | Run `deferd migrate` first |
133
+ | MongoDB | `mongodb://host:27017/db` | `deferd[mongo]` | Creates its indexes on connect |
134
+ | Redis 7 / Valkey | `redis://host:6379/0` | `deferd[redis]` | Needs AOF, or deferd refuses it |
135
+ | Elasticsearch 8 | `elasticsearch://host:9200` | `deferd[elasticsearch]` | Creates its indexes on connect |
136
+
137
+ Create the MySQL schema before the first deploy, and again after upgrading deferd. Check what a
138
+ store guarantees with `deferd check`:
139
+
140
+ ```bash
141
+ deferd migrate --store "mysql://user:pass@db:3306/app"
142
+ deferd check --store "mysql://user:pass@db:3306/app"
143
+ ```
144
+
145
+ `deferd check` reports the store as SAFE, WEAK (a warning, such as MySQL not flushing every commit or
146
+ a single-node Elasticsearch) or UNSAFE (Redis without AOF: refused unless `allow_unsafe_store=True`).
147
+
148
+ - **Several applications, one database:** each must use its own `app_name`. With Kubernetes
149
+ discovery, deferd refuses to start a second application under an `app_name` another one uses.
150
+ With static or custom discovery, choosing distinct names is up to you.
151
+ - **Store down:** a pod starts anyway and logs a warning. Persisted `schedule()` calls are refused
152
+ until the store answers; memory and replicated jobs keep working.
153
+ - **Cleanup:** finished persisted jobs are kept for 7 days (`DEFERD_FINISHED_RETENTION`). Set
154
+ `retain_for` on a handler to change it for that handler (at least 10 minutes).
155
+
156
+ ## Running on Kubernetes
157
+
158
+ Install `deferd[kubernetes]`. Pods find each other through the Kubernetes API, so your Deployment
159
+ needs a few additions. [`deploy/kubernetes/`](deploy/kubernetes/) has complete manifests to copy.
160
+
161
+ **New objects:**
162
+
163
+ | Object | Why |
164
+ |---|---|
165
+ | `ServiceAccount`, `Role`, `RoleBinding` ([`rbac.yaml`](deploy/kubernetes/rbac.yaml)) | Lets each pod `get`, `list` and `watch` pods in its namespace to find its peers |
166
+ | `Secret` with `DEFERD_SECRET` | Pods prove they belong to the app before exchanging jobs. Same value on every pod |
167
+ | `PodDisruptionBudget` with `maxUnavailable: 1` ([`pdb.yaml`](deploy/kubernetes/pdb.yaml)) | Node drains evict one pod at a time, so each hands its jobs off |
168
+ | `NetworkPolicy` ([`networkpolicy.yaml`](deploy/kubernetes/networkpolicy.yaml)) | Only if your namespace denies traffic by default: allow port 7946 between the app's pods |
169
+
170
+ **Changes to your Deployment** ([`deployment.yaml`](deploy/kubernetes/deployment.yaml)):
171
+
172
+ ```yaml
173
+ spec:
174
+ strategy:
175
+ type: RollingUpdate # never Recreate: it stops every pod at once
176
+ rollingUpdate: {maxUnavailable: 0, maxSurge: 1}
177
+ template:
178
+ spec:
179
+ serviceAccountName: orders-deferd
180
+ terminationGracePeriodSeconds: 60 # time to hand jobs off and finish running ones
181
+ containers:
182
+ - name: orders
183
+ ports:
184
+ - {name: deferd, containerPort: 7946} # pod-to-pod traffic; no Service needed
185
+ - {name: admin, containerPort: 9090} # /healthz, /readyz, /metrics
186
+ env:
187
+ - {name: DEFERD_DISCOVERY, value: kubernetes}
188
+ - name: DEFERD_SECRET
189
+ valueFrom: {secretKeyRef: {name: deferd-secret, key: DEFERD_SECRET}}
190
+ # filled in by Kubernetes for each pod; copy as is
191
+ - name: DEFERD_POD_NAME
192
+ valueFrom: {fieldRef: {fieldPath: metadata.name}}
193
+ - name: DEFERD_POD_NAMESPACE
194
+ valueFrom: {fieldRef: {fieldPath: metadata.namespace}}
195
+ - name: DEFERD_POD_IP
196
+ valueFrom: {fieldRef: {fieldPath: status.podIP}}
197
+ - name: DEFERD_NODE_NAME
198
+ valueFrom: {fieldRef: {fieldPath: spec.nodeName}}
199
+ readinessProbe:
200
+ httpGet: {path: /readyz, port: admin}
201
+ livenessProbe:
202
+ httpGet: {path: /healthz, port: admin}
203
+ lifecycle:
204
+ preStop: {exec: {command: ["sleep", "5"]}} # peers stop sending work first
205
+ ```
206
+
207
+ Pods are peers when they share the Deployment's `app` label. Spread them over nodes with *soft* pod
208
+ anti-affinity or `topologySpreadConstraints` (`whenUnsatisfiable: ScheduleAnyway`), so a job and
209
+ its backup don't sit on the same machine. [`deploy/kubernetes/README.md`](deploy/kubernetes/README.md)
210
+ explains each rule and lists the startup errors and their fixes.
211
+
212
+ ### Process modes
213
+
214
+ - **Embedded** (one process per pod, such as a queue consumer or a single-worker web app): the
215
+ service runs `async with scheduler.run()` and is a cluster member itself.
216
+ - **Dedicated** (several web workers per pod, such as gunicorn): one `deferd run module:scheduler`
217
+ process per pod is the member, and the workers schedule jobs through `scheduler.client()`
218
+ (`client(sync=True)` for Flask or classic Django) over a Unix socket.
219
+
220
+ See [`examples/`](examples/): a queue consumer, FastAPI embedded, and FastAPI with gunicorn.
221
+
222
+ ## Running without a store
223
+
224
+ With no store, jobs live only in pod memory. Two failures lose `REPLICATED` jobs:
225
+
226
+ 1. **A job's owner and all its backups die at the same time**, for example pods on one node that
227
+ fails.
228
+ 2. **Every pod restarts at once**: the `Recreate` deploy strategy, scaling to zero, or a
229
+ whole-cluster outage.
230
+
231
+ These losses can't be counted: every member that knew about those jobs is gone. Jobs left with a
232
+ single copy are visible (`deferd_under_replicated_jobs`). To make losses unlikely:
233
+
234
+ - Run **at least two replicas, on different nodes**, with soft anti-affinity (hard anti-affinity
235
+ leaves pods `Pending` when there are more pods than nodes).
236
+ - Use **`RollingUpdate`**, never `Recreate`, and add a **PodDisruptionBudget**.
237
+ - Set **`terminationGracePeriodSeconds`** above the expected handoff time plus the longest job you're
238
+ willing to wait for.
239
+ - Never scale to zero while jobs are pending.
240
+ - Keep pod clocks in sync (NTP). deferd assumes they agree within one second.
241
+
242
+ On a single pod (local development, or one replica), `REPLICATED` jobs have no second pod to back
243
+ up to, so `schedule()` raises `DurabilityNotSatisfied`. Set `default_durability="memory"` for those
244
+ environments, or use `min_replicas=0` to accept replicated jobs anyway. Those jobs have one copy
245
+ until a second pod joins, so losing that pod first loses them. deferd never downgrades a policy
246
+ silently.
247
+
248
+ ## Guarantees
249
+
250
+ - **At-least-once.** A job runs at least once, unless every copy its policy keeps is lost at the
251
+ same time.
252
+ - **Duplicates are possible** during failover, and when callers retry `schedule()`.
253
+ **Handlers must be idempotent.** Use `ctx.job_id` as the idempotency key.
254
+ - **No silent downgrades.** If a policy can't be met (no backup available, store down),
255
+ `schedule()` raises instead of quietly keeping fewer copies.
256
+ - **Failover time.** A pod is declared dead after 15 seconds of silence (`DEFERD_DEAD_AFTER`), then
257
+ its backups take over. A graceful shutdown hands jobs off without that wait.
258
+
259
+ ## Configuration
260
+
261
+ Every setting can be passed to `Scheduler(...)` as a keyword or set as a `DEFERD_<NAME>`
262
+ environment variable; keywords win. Durations take `30s`, `10m`, `12h` or `7d`. The ones most
263
+ deployments touch:
264
+
265
+ | Variable | Default | What |
266
+ |---|---|---|
267
+ | `DEFERD_APP_NAME` | (required) | The application's name; the same on every pod |
268
+ | `DEFERD_DISCOVERY` | `static` | `kubernetes`, or `static` with `DEFERD_SELF_ID` and `DEFERD_PEERS` |
269
+ | `DEFERD_SECRET` | (required, except alone or on loopback) | Shared secret for pod-to-pod connections |
270
+ | `DEFERD_STORE` | none | Store URL for `PERSISTED` and `DURABLE` jobs |
271
+ | `DEFERD_DEFAULT_DURABILITY` | `replicated` | Policy for jobs that don't set one |
272
+ | `DEFERD_FINISHED_RETENTION` | `7d` | How long finished persisted jobs are kept |
273
+ | `DEFERD_MAX_CONCURRENCY` | `100` | Handlers running at once per pod |
274
+ | `DEFERD_MAX_PENDING_JOBS` | `200000` | Pending jobs a pod accepts before `CapacityExceeded` |
275
+ | `DEFERD_SHUTDOWN_GRACE` | `30s` | Time allowed for handoff on shutdown; keep below the pod's grace period |
276
+ | `DEFERD_ADMIN_PORT` | `9090` | Health, metrics and debug endpoints; `0` turns them off |
277
+ | `DEFERD_LOG_JSON` | `false` | JSON logs |
278
+
279
+ The full list, with comments, is the `Settings` class in
280
+ [`src/deferd/config.py`](src/deferd/config.py).
281
+
282
+ ## Monitoring
283
+
284
+ The admin server (port 9090) serves:
285
+
286
+ | Path | What |
287
+ |---|---|
288
+ | `/healthz` | Liveness: fails only when the event loop is stuck |
289
+ | `/readyz` | Readiness: the pod has joined the cluster |
290
+ | `/metrics` | Prometheus metrics, such as `deferd_jobs_pending`, `deferd_job_lateness_seconds`, `deferd_under_replicated_jobs`, `deferd_takeovers_total`, `deferd_store_up` |
291
+ | `/debug/members` | This pod's view of the cluster |
292
+ | `/debug/jobs`, `/debug/jobs/<id>` | Jobs this pod owns, and where one job is |
293
+
294
+ From a shell in a pod, `deferd inspect members` and `deferd inspect job <id>` print the same.
295
+
296
+ ## Performance
297
+
298
+ Measured on one laptop, everything on localhost (`benchmarks/results.json`). Real pod-to-pod
299
+ networks add their round-trip time to `REPLICATED` calls.
300
+
301
+ | What | Result |
302
+ |---|---|
303
+ | `schedule()`, `MEMORY`, one process | about 56,000 jobs/s, p99 0.03 ms |
304
+ | `schedule()`, `REPLICATED`, three processes | about 3,700 jobs/s, p50 16 ms, p99 46 ms |
305
+ | Memory per pending job | about 0.9 KB on the owner, 1.9 KB per backup copy |
306
+ | 10,000 jobs due at the same moment | all started within 1 s (p99 0.8 s) |
307
+ | 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 |
308
+
309
+ Run them yourself with `uv run python -m benchmarks` (see [`benchmarks/README.md`](benchmarks/README.md)).
310
+
311
+ ## When not to use deferd (yet)
312
+
313
+ - Your jobs must survive every pod restarting at once, and you can't run a store for them.
314
+ - You need to cancel or deduplicate scheduled jobs (planned).
315
+ - Your handlers are sync or CPU-heavy (only async handlers are supported).
316
+ - You need exactly-once execution and can't make handlers idempotent. No system can give you that
317
+ over a network.
318
+
319
+ ## Install
320
+
321
+ ```bash
322
+ pip install deferd # core: memory and replicated jobs
323
+ pip install "deferd[kubernetes]" # Kubernetes discovery (uses lightkube)
324
+ pip install "deferd[mysql]" # or [mongo], [redis], [elasticsearch]: persisted jobs
325
+ ```
326
+
327
+ Requires Python 3.12+.
328
+
329
+ ## Development
330
+
331
+ Requires [uv](https://docs.astral.sh/uv/).
332
+
333
+ ```bash
334
+ uv sync --all-extras # install everything
335
+ uv run pytest # all local tests (store tests need Docker; the kind suite skips itself)
336
+ DEFERD_E2E=1 uv run pytest tests/k8s -v # end to end on kind (needs Docker and kind)
337
+ uv run ruff check . # lint
338
+ uv run ruff format . # format
339
+ uv run pyright # type check
340
+ uv run lint-imports # architecture rules
341
+ ```
342
+
343
+ `deferd.testing` ships a fake clock, a pytest plugin and a simulated cluster for testing your own
344
+ handlers, plus conformance suites for writing a store or discovery plugin.
345
+
346
+ ## License
347
+
348
+ [MIT](LICENSE)