idempotency-asgi 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.
- idempotency_asgi-0.1.0/.github/workflows/ci.yml +62 -0
- idempotency_asgi-0.1.0/.github/workflows/publish.yml +31 -0
- idempotency_asgi-0.1.0/.gitignore +10 -0
- idempotency_asgi-0.1.0/.pre-commit-config.yaml +19 -0
- idempotency_asgi-0.1.0/.python-version +1 -0
- idempotency_asgi-0.1.0/LICENSE +0 -0
- idempotency_asgi-0.1.0/PKG-INFO +206 -0
- idempotency_asgi-0.1.0/README.md +179 -0
- idempotency_asgi-0.1.0/benchmarks/bench.py +92 -0
- idempotency_asgi-0.1.0/docker-compose.yml +28 -0
- idempotency_asgi-0.1.0/docs/design.md +43 -0
- idempotency_asgi-0.1.0/examples/__init__.py +0 -0
- idempotency_asgi-0.1.0/examples/demo_app/__init__.py +0 -0
- idempotency_asgi-0.1.0/examples/demo_app/main.py +94 -0
- idempotency_asgi-0.1.0/pyproject.toml +80 -0
- idempotency_asgi-0.1.0/src/idempotency_asgi/__init__.py +4 -0
- idempotency_asgi-0.1.0/src/idempotency_asgi/_types.py +8 -0
- idempotency_asgi-0.1.0/src/idempotency_asgi/cleanup.py +39 -0
- idempotency_asgi-0.1.0/src/idempotency_asgi/middleware.py +218 -0
- idempotency_asgi-0.1.0/src/idempotency_asgi/postgres.py +136 -0
- idempotency_asgi-0.1.0/src/idempotency_asgi/py.typed +0 -0
- idempotency_asgi-0.1.0/src/idempotency_asgi/redis_storage.py +113 -0
- idempotency_asgi-0.1.0/src/idempotency_asgi/storage.py +41 -0
- idempotency_asgi-0.1.0/tests/__init__.py +0 -0
- idempotency_asgi-0.1.0/tests/chaos_app.py +46 -0
- idempotency_asgi-0.1.0/tests/conftest.py +43 -0
- idempotency_asgi-0.1.0/tests/test_chaos.py +73 -0
- idempotency_asgi-0.1.0/tests/test_cleanup.py +34 -0
- idempotency_asgi-0.1.0/tests/test_middleware.py +223 -0
- idempotency_asgi-0.1.0/tests/test_postgres_storage.py +56 -0
- idempotency_asgi-0.1.0/tests/test_smoke.py +22 -0
- idempotency_asgi-0.1.0/tests/test_state_machine.py +98 -0
- idempotency_asgi-0.1.0/tests/test_storage.py +57 -0
- idempotency_asgi-0.1.0/uv.lock +1425 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
workflow_dispatch:
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
test:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
services:
|
|
13
|
+
postgres:
|
|
14
|
+
image: postgres:16
|
|
15
|
+
env:
|
|
16
|
+
POSTGRES_USER: idem
|
|
17
|
+
POSTGRES_PASSWORD: idem
|
|
18
|
+
POSTGRES_DB: idem
|
|
19
|
+
ports:
|
|
20
|
+
- 5432:5432
|
|
21
|
+
options: >-
|
|
22
|
+
--health-cmd "pg_isready -U idem -d idem"
|
|
23
|
+
--health-interval 2s
|
|
24
|
+
--health-timeout 3s
|
|
25
|
+
--health-retries 15
|
|
26
|
+
redis:
|
|
27
|
+
image: redis:7
|
|
28
|
+
ports:
|
|
29
|
+
- 6379:6379
|
|
30
|
+
options: >-
|
|
31
|
+
--health-cmd "redis-cli ping"
|
|
32
|
+
--health-interval 2s
|
|
33
|
+
--health-timeout 3s
|
|
34
|
+
--health-retries 15
|
|
35
|
+
env:
|
|
36
|
+
DATABASE_URL: postgresql://idem:idem@localhost:5432/idem
|
|
37
|
+
REDIS_URL: redis://localhost:6379/0
|
|
38
|
+
strategy:
|
|
39
|
+
fail-fast: false
|
|
40
|
+
matrix:
|
|
41
|
+
python-version: ["3.11", "3.12", "3.13"]
|
|
42
|
+
steps:
|
|
43
|
+
- uses: actions/checkout@v4
|
|
44
|
+
|
|
45
|
+
- uses: astral-sh/setup-uv@v5
|
|
46
|
+
with:
|
|
47
|
+
enable-cache: true
|
|
48
|
+
|
|
49
|
+
- name: Install dependencies
|
|
50
|
+
run: uv sync --python ${{ matrix.python-version }}
|
|
51
|
+
|
|
52
|
+
- name: Ruff (lint)
|
|
53
|
+
run: uv run ruff check .
|
|
54
|
+
|
|
55
|
+
- name: Ruff (format)
|
|
56
|
+
run: uv run ruff format --check .
|
|
57
|
+
|
|
58
|
+
- name: Mypy
|
|
59
|
+
run: uv run mypy
|
|
60
|
+
|
|
61
|
+
- name: Tests
|
|
62
|
+
run: uv run pytest
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
name: Publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
build:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
steps:
|
|
11
|
+
- uses: actions/checkout@v4
|
|
12
|
+
- uses: astral-sh/setup-uv@v5
|
|
13
|
+
- name: Build
|
|
14
|
+
run: uv build
|
|
15
|
+
- uses: actions/upload-artifact@v4
|
|
16
|
+
with:
|
|
17
|
+
name: dist
|
|
18
|
+
path: dist/
|
|
19
|
+
|
|
20
|
+
publish:
|
|
21
|
+
needs: build
|
|
22
|
+
runs-on: ubuntu-latest
|
|
23
|
+
environment: pypi
|
|
24
|
+
permissions:
|
|
25
|
+
id-token: write
|
|
26
|
+
steps:
|
|
27
|
+
- uses: actions/download-artifact@v4
|
|
28
|
+
with:
|
|
29
|
+
name: dist
|
|
30
|
+
path: dist/
|
|
31
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
repos:
|
|
2
|
+
- repo: local
|
|
3
|
+
hooks:
|
|
4
|
+
- id: ruff-check
|
|
5
|
+
name: ruff check
|
|
6
|
+
entry: uv run ruff check --fix
|
|
7
|
+
language: system
|
|
8
|
+
types: [python]
|
|
9
|
+
- id: ruff-format
|
|
10
|
+
name: ruff format
|
|
11
|
+
entry: uv run ruff format
|
|
12
|
+
language: system
|
|
13
|
+
types: [python]
|
|
14
|
+
- id: mypy
|
|
15
|
+
name: mypy
|
|
16
|
+
entry: uv run mypy
|
|
17
|
+
language: system
|
|
18
|
+
types: [python]
|
|
19
|
+
pass_filenames: false
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.12
|
|
File without changes
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: idempotency-asgi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Idempotency-Key middleware for ASGI apps (FastAPI/Starlette)
|
|
5
|
+
Project-URL: Repository, https://github.com/adsetsuko0/idempotency-asgi
|
|
6
|
+
Project-URL: Issues, https://github.com/adsetsuko0/idempotency-asgi/issues
|
|
7
|
+
Author: Anna Ermak
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: asgi,fastapi,idempotency,middleware,starlette
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Framework :: FastAPI
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Provides-Extra: postgres
|
|
23
|
+
Requires-Dist: asyncpg>=0.29; extra == 'postgres'
|
|
24
|
+
Provides-Extra: redis
|
|
25
|
+
Requires-Dist: redis>=5.0; extra == 'redis'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# idempotency-asgi
|
|
29
|
+
|
|
30
|
+
[](https://github.com/adsetsuko0/idempotency-asgi/actions/workflows/ci.yml)
|
|
31
|
+

|
|
32
|
+

|
|
33
|
+
|
|
34
|
+
`Idempotency-Key` middleware for ASGI apps (FastAPI, Starlette). It makes `POST` and `PATCH` requests safe to retry: the handler runs once per key, and every retry gets the stored response.
|
|
35
|
+
|
|
36
|
+
- Pure ASGI, no dependency on FastAPI or Starlette in the core
|
|
37
|
+
- Two interchangeable backends: **PostgreSQL** and **Redis** (atomic Lua scripts)
|
|
38
|
+
- Handles concurrent duplicates, changed request bodies, and crashed processes
|
|
39
|
+
- Fully typed (`mypy --strict`), tested on Python 3.11, 3.12 and 3.13
|
|
40
|
+
|
|
41
|
+
## The problem
|
|
42
|
+
|
|
43
|
+
A client sends `POST /payments`, the network hangs, and the client retries. Without protection the server charges the customer twice.
|
|
44
|
+
|
|
45
|
+
With this middleware the client attaches a unique `Idempotency-Key` header. The first request runs normally and its response is stored. Any retry with the same key gets the stored response back, and the handler is not called again.
|
|
46
|
+
|
|
47
|
+
## Quickstart
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install "idempotency-asgi[redis]" # or [postgres]
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import redis.asyncio as aioredis
|
|
55
|
+
from fastapi import FastAPI
|
|
56
|
+
from idempotency_asgi import IdempotencyMiddleware
|
|
57
|
+
from idempotency_asgi.redis_storage import RedisStorage
|
|
58
|
+
|
|
59
|
+
app = FastAPI()
|
|
60
|
+
app.add_middleware(
|
|
61
|
+
IdempotencyMiddleware, storage=RedisStorage(aioredis.from_url("redis://localhost:6379/0"))
|
|
62
|
+
)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Try it:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
curl -X POST http://localhost:8000/payments \
|
|
69
|
+
-H "Idempotency-Key: pay-1" -H "Content-Type: application/json" \
|
|
70
|
+
-d '{"amount": 100}'
|
|
71
|
+
# repeat the same command: same response, plus "Idempotency-Replayed: true"
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### PostgreSQL backend
|
|
75
|
+
|
|
76
|
+
The connection pool must be created in an async context, so create it at startup, call `create_schema()` once, and (optionally) run the background cleanup of expired keys:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
pool = await asyncpg.create_pool("postgresql://user:pass@host/db")
|
|
80
|
+
storage = PostgresStorage(pool)
|
|
81
|
+
await storage.create_schema()
|
|
82
|
+
async with cleanup_task(storage, interval_seconds=300):
|
|
83
|
+
...
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
A complete working example, including a lazy storage wrapper (because middleware is built before the pool exists), is in [`examples/demo_app/main.py`](examples/demo_app/main.py). Run the databases with `docker compose up -d`.
|
|
87
|
+
|
|
88
|
+
### Configuration
|
|
89
|
+
|
|
90
|
+
| Parameter | Default | Meaning |
|
|
91
|
+
|---|---|---|
|
|
92
|
+
| `storage` | required | `PostgresStorage` or `RedisStorage` (any object implementing the `Storage` protocol) |
|
|
93
|
+
| `scope_getter` | returns `"global"` | Function `scope -> str` that decides who owns a key (user, tenant). Keys are unique per `(scope, key)` |
|
|
94
|
+
| `lock_seconds` | 30 | How long a running request holds its key |
|
|
95
|
+
| `ttl_seconds` | 86400 | How long a stored response is kept (24 h) |
|
|
96
|
+
| `max_body_bytes` | 1 000 000 | Larger request bodies get `413` |
|
|
97
|
+
| `max_response_bytes` | 1 000 000 | Larger responses are returned but not stored |
|
|
98
|
+
| `require_key` | `False` | If `True`, `POST`/`PATCH` without the header get `400` |
|
|
99
|
+
|
|
100
|
+
## Behavior
|
|
101
|
+
|
|
102
|
+
Only `POST` and `PATCH` requests with an `Idempotency-Key` header are handled. Everything else passes through untouched.
|
|
103
|
+
|
|
104
|
+
| Situation | Result |
|
|
105
|
+
|---|---|
|
|
106
|
+
| New key | Handler runs, response is stored |
|
|
107
|
+
| Same key, same request, already completed | Stored response is returned with `Idempotency-Replayed: true`, handler is not called |
|
|
108
|
+
| Same key, request still running | `409 Conflict` with `Retry-After` |
|
|
109
|
+
| Same key, different request (method, path, query or body) | `422 Unprocessable Entity` |
|
|
110
|
+
| Handler returns `5xx` or raises | Nothing is stored, the key is released, the client may retry |
|
|
111
|
+
| Lock expired (process crashed) | Next request takes over the key and runs the handler |
|
|
112
|
+
| Streaming or oversized response | Delivered to the client, not stored, key is released |
|
|
113
|
+
| Header missing and `require_key=True` | `400 Bad Request` |
|
|
114
|
+
| Request body above `max_body_bytes` | `413 Payload Too Large` |
|
|
115
|
+
|
|
116
|
+
```mermaid
|
|
117
|
+
stateDiagram-v2
|
|
118
|
+
[*] --> in_progress: claim (new key)
|
|
119
|
+
in_progress --> completed: handler finished, response stored
|
|
120
|
+
in_progress --> [*]: handler failed (5xx / exception), key released
|
|
121
|
+
in_progress --> in_progress: lock expired, another request takes over
|
|
122
|
+
completed --> [*]: TTL expired
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
The request fingerprint is a SHA-256 of the method, path, sorted query parameters and body. Sensitive headers (`authorization`, `cookie`, `set-cookie`, `proxy-authenticate`) are never written to the storage. The client still receives them in the first response.
|
|
126
|
+
|
|
127
|
+
## What breaks and how I verified it
|
|
128
|
+
|
|
129
|
+
| Failure | How it is handled | How it is tested |
|
|
130
|
+
|---|---|---|
|
|
131
|
+
| 50 identical requests at the same moment | Atomic claim: exactly one wins, the rest get `409` | `test_fifty_parallel_requests_run_handler_once` (middleware), `test_concurrent_claims_only_one_wins` (storage) |
|
|
132
|
+
| Client retries with a different body | `422`, handler not called | `test_different_body_returns_422` |
|
|
133
|
+
| Handler fails with `5xx` | Key is released so the retry can succeed | `test_5xx_releases_key_so_client_can_retry` |
|
|
134
|
+
| Process dies mid-request | Lock expires, next request takes the key over | `test_expired_lock_is_taken_over_after_crash` |
|
|
135
|
+
| Process is killed with no cleanup | Same recovery, with a real server process killed | `test_key_recovers_after_process_is_killed` (chaos test) |
|
|
136
|
+
| Two users pick the same key | Keys are isolated by scope | `test_scopes_are_isolated` |
|
|
137
|
+
| Streaming or huge response | Not stored, not replayed from storage | `test_streaming_response_is_not_stored`, `test_oversized_response_is_not_stored` |
|
|
138
|
+
| Secrets in stored responses | Sensitive headers are dropped | `test_sensitive_headers_are_not_replayed` |
|
|
139
|
+
| Unbounded table growth | Expired keys are purged in the background (Postgres), `EXPIRE` (Redis) | `tests/test_cleanup.py` |
|
|
140
|
+
| Unexpected sequences of operations | Random sequences are compared with a reference model | Hypothesis state machine (40 examples, 30 steps each) |
|
|
141
|
+
|
|
142
|
+
The same storage and middleware tests run against **both** backends through a parametrized pytest fixture, so the `Storage` protocol is exercised for real. The full suite has 57 tests and runs in CI against real PostgreSQL 16 and Redis 7 service containers.
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
docker compose up -d
|
|
146
|
+
uv sync
|
|
147
|
+
uv run pytest
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Design decisions
|
|
151
|
+
|
|
152
|
+
- **Pure ASGI instead of `BaseHTTPMiddleware`.** `BaseHTTPMiddleware` is awkward with request bodies and streaming. A plain ASGI middleware gives full control over what is read and sent.
|
|
153
|
+
- **Atomicity comes from the database.** A "check, then write" sequence breaks under concurrent requests. PostgreSQL uses `INSERT ... ON CONFLICT (scope, key) DO NOTHING`; Redis uses a Lua script, which runs as one uninterruptible unit.
|
|
154
|
+
- **`locked_until` instead of a permanent lock.** If a process dies, its key must not stay busy forever. After the lock expires, another request takes the key over atomically (`UPDATE ... WHERE locked_until < now()` in Postgres, the same check inside the Lua script in Redis).
|
|
155
|
+
- **Server-side time.** Lock expiry and TTL are computed with the database clock (`now()` in Postgres, `TIME` in Redis), so several app servers cannot disagree about time.
|
|
156
|
+
- **Failures are not cached.** A `5xx` response is not stored, so a temporary error does not become permanent for that key. The trade-off: a handler that failed after a side effect may run again.
|
|
157
|
+
- **Last response message is held until it is stored.** The client receives the final chunk only after the response is saved, so an immediate retry does not hit a false `409`.
|
|
158
|
+
- **Core has no dependencies.** Backends are optional extras (`[postgres]`, `[redis]`), and the `Storage` protocol allows adding more.
|
|
159
|
+
|
|
160
|
+
## Benchmarks
|
|
161
|
+
|
|
162
|
+
Overhead for a request with a **new key** (the most expensive path: `claim`, handler, `complete`). 2000 requests per configuration, 20 concurrent, three runs, median shown.
|
|
163
|
+
|
|
164
|
+
| Configuration | req/s | p50, ms | p95, ms | p99, ms |
|
|
165
|
+
|---|---|---|---|---|
|
|
166
|
+
| No middleware | 783 | 1.05 | 2.18 | 3.04 |
|
|
167
|
+
| Middleware + PostgreSQL | 443 | 39.04 | 65.82 | 78.35 |
|
|
168
|
+
| Middleware + Redis | 542 | 29.72 | 52.92 | 61.29 |
|
|
169
|
+
|
|
170
|
+
Redis is roughly 25% faster than PostgreSQL at p50 and about 20% faster at p99 in this setup.
|
|
171
|
+
|
|
172
|
+
Caveats:
|
|
173
|
+
- Local measurement: app, PostgreSQL and Redis run on one Windows machine, with the databases in Docker. A Linux server will likely show different numbers.
|
|
174
|
+
- Requests go through `httpx.ASGITransport`, with no network and no uvicorn, so this measures the library and storage cost only.
|
|
175
|
+
- Each request makes two storage calls and 20 requests compete for connections, so latency includes queueing. Throughput is the more meaningful number.
|
|
176
|
+
- Run-to-run spread is noticeable (PostgreSQL p50 ranged from 39 to 46 ms).
|
|
177
|
+
- Replay latency (retries of a completed key) was not measured.
|
|
178
|
+
|
|
179
|
+
Reproduce: `uv run python benchmarks/bench.py`
|
|
180
|
+
|
|
181
|
+
## Limitations
|
|
182
|
+
|
|
183
|
+
- If a handler runs longer than `lock_seconds`, another request can take over the key and run the handler a second time. Set `lock_seconds` above your slowest handler.
|
|
184
|
+
- The middleware sees only HTTP. Side effects such as sending an email or calling an external API are not made idempotent by it. Use the same idempotency key downstream, or commit the key in the same database transaction as your business data.
|
|
185
|
+
- Streaming and oversized responses are not stored, so retries of those requests are **not** protected.
|
|
186
|
+
- If storing the response fails after the handler succeeded, the client still gets the response and the key is released, so a retry would run the handler again.
|
|
187
|
+
- The default scope is `"global"`: all clients share one key space. In real applications pass `scope_getter` (for example, the authenticated user id).
|
|
188
|
+
- Redis durability depends on your Redis persistence settings. For payments-grade guarantees prefer PostgreSQL.
|
|
189
|
+
- The Hypothesis state machine and the chaos test run against the PostgreSQL backend only.
|
|
190
|
+
|
|
191
|
+
## Development
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
uv sync # create the environment
|
|
195
|
+
docker compose up -d # PostgreSQL 16 and Redis 7
|
|
196
|
+
uv run pytest # tests
|
|
197
|
+
uv run ruff check . # lint
|
|
198
|
+
uv run ruff format . # format
|
|
199
|
+
uv run mypy # strict type checking
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
Pre-commit hooks (ruff, ruff format, mypy) run on every commit. The design notes are in [`docs/design.md`](docs/design.md).
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
MIT
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# idempotency-asgi
|
|
2
|
+
|
|
3
|
+
[](https://github.com/adsetsuko0/idempotency-asgi/actions/workflows/ci.yml)
|
|
4
|
+

|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
`Idempotency-Key` middleware for ASGI apps (FastAPI, Starlette). It makes `POST` and `PATCH` requests safe to retry: the handler runs once per key, and every retry gets the stored response.
|
|
8
|
+
|
|
9
|
+
- Pure ASGI, no dependency on FastAPI or Starlette in the core
|
|
10
|
+
- Two interchangeable backends: **PostgreSQL** and **Redis** (atomic Lua scripts)
|
|
11
|
+
- Handles concurrent duplicates, changed request bodies, and crashed processes
|
|
12
|
+
- Fully typed (`mypy --strict`), tested on Python 3.11, 3.12 and 3.13
|
|
13
|
+
|
|
14
|
+
## The problem
|
|
15
|
+
|
|
16
|
+
A client sends `POST /payments`, the network hangs, and the client retries. Without protection the server charges the customer twice.
|
|
17
|
+
|
|
18
|
+
With this middleware the client attaches a unique `Idempotency-Key` header. The first request runs normally and its response is stored. Any retry with the same key gets the stored response back, and the handler is not called again.
|
|
19
|
+
|
|
20
|
+
## Quickstart
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install "idempotency-asgi[redis]" # or [postgres]
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import redis.asyncio as aioredis
|
|
28
|
+
from fastapi import FastAPI
|
|
29
|
+
from idempotency_asgi import IdempotencyMiddleware
|
|
30
|
+
from idempotency_asgi.redis_storage import RedisStorage
|
|
31
|
+
|
|
32
|
+
app = FastAPI()
|
|
33
|
+
app.add_middleware(
|
|
34
|
+
IdempotencyMiddleware, storage=RedisStorage(aioredis.from_url("redis://localhost:6379/0"))
|
|
35
|
+
)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Try it:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
curl -X POST http://localhost:8000/payments \
|
|
42
|
+
-H "Idempotency-Key: pay-1" -H "Content-Type: application/json" \
|
|
43
|
+
-d '{"amount": 100}'
|
|
44
|
+
# repeat the same command: same response, plus "Idempotency-Replayed: true"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### PostgreSQL backend
|
|
48
|
+
|
|
49
|
+
The connection pool must be created in an async context, so create it at startup, call `create_schema()` once, and (optionally) run the background cleanup of expired keys:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
pool = await asyncpg.create_pool("postgresql://user:pass@host/db")
|
|
53
|
+
storage = PostgresStorage(pool)
|
|
54
|
+
await storage.create_schema()
|
|
55
|
+
async with cleanup_task(storage, interval_seconds=300):
|
|
56
|
+
...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
A complete working example, including a lazy storage wrapper (because middleware is built before the pool exists), is in [`examples/demo_app/main.py`](examples/demo_app/main.py). Run the databases with `docker compose up -d`.
|
|
60
|
+
|
|
61
|
+
### Configuration
|
|
62
|
+
|
|
63
|
+
| Parameter | Default | Meaning |
|
|
64
|
+
|---|---|---|
|
|
65
|
+
| `storage` | required | `PostgresStorage` or `RedisStorage` (any object implementing the `Storage` protocol) |
|
|
66
|
+
| `scope_getter` | returns `"global"` | Function `scope -> str` that decides who owns a key (user, tenant). Keys are unique per `(scope, key)` |
|
|
67
|
+
| `lock_seconds` | 30 | How long a running request holds its key |
|
|
68
|
+
| `ttl_seconds` | 86400 | How long a stored response is kept (24 h) |
|
|
69
|
+
| `max_body_bytes` | 1 000 000 | Larger request bodies get `413` |
|
|
70
|
+
| `max_response_bytes` | 1 000 000 | Larger responses are returned but not stored |
|
|
71
|
+
| `require_key` | `False` | If `True`, `POST`/`PATCH` without the header get `400` |
|
|
72
|
+
|
|
73
|
+
## Behavior
|
|
74
|
+
|
|
75
|
+
Only `POST` and `PATCH` requests with an `Idempotency-Key` header are handled. Everything else passes through untouched.
|
|
76
|
+
|
|
77
|
+
| Situation | Result |
|
|
78
|
+
|---|---|
|
|
79
|
+
| New key | Handler runs, response is stored |
|
|
80
|
+
| Same key, same request, already completed | Stored response is returned with `Idempotency-Replayed: true`, handler is not called |
|
|
81
|
+
| Same key, request still running | `409 Conflict` with `Retry-After` |
|
|
82
|
+
| Same key, different request (method, path, query or body) | `422 Unprocessable Entity` |
|
|
83
|
+
| Handler returns `5xx` or raises | Nothing is stored, the key is released, the client may retry |
|
|
84
|
+
| Lock expired (process crashed) | Next request takes over the key and runs the handler |
|
|
85
|
+
| Streaming or oversized response | Delivered to the client, not stored, key is released |
|
|
86
|
+
| Header missing and `require_key=True` | `400 Bad Request` |
|
|
87
|
+
| Request body above `max_body_bytes` | `413 Payload Too Large` |
|
|
88
|
+
|
|
89
|
+
```mermaid
|
|
90
|
+
stateDiagram-v2
|
|
91
|
+
[*] --> in_progress: claim (new key)
|
|
92
|
+
in_progress --> completed: handler finished, response stored
|
|
93
|
+
in_progress --> [*]: handler failed (5xx / exception), key released
|
|
94
|
+
in_progress --> in_progress: lock expired, another request takes over
|
|
95
|
+
completed --> [*]: TTL expired
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The request fingerprint is a SHA-256 of the method, path, sorted query parameters and body. Sensitive headers (`authorization`, `cookie`, `set-cookie`, `proxy-authenticate`) are never written to the storage. The client still receives them in the first response.
|
|
99
|
+
|
|
100
|
+
## What breaks and how I verified it
|
|
101
|
+
|
|
102
|
+
| Failure | How it is handled | How it is tested |
|
|
103
|
+
|---|---|---|
|
|
104
|
+
| 50 identical requests at the same moment | Atomic claim: exactly one wins, the rest get `409` | `test_fifty_parallel_requests_run_handler_once` (middleware), `test_concurrent_claims_only_one_wins` (storage) |
|
|
105
|
+
| Client retries with a different body | `422`, handler not called | `test_different_body_returns_422` |
|
|
106
|
+
| Handler fails with `5xx` | Key is released so the retry can succeed | `test_5xx_releases_key_so_client_can_retry` |
|
|
107
|
+
| Process dies mid-request | Lock expires, next request takes the key over | `test_expired_lock_is_taken_over_after_crash` |
|
|
108
|
+
| Process is killed with no cleanup | Same recovery, with a real server process killed | `test_key_recovers_after_process_is_killed` (chaos test) |
|
|
109
|
+
| Two users pick the same key | Keys are isolated by scope | `test_scopes_are_isolated` |
|
|
110
|
+
| Streaming or huge response | Not stored, not replayed from storage | `test_streaming_response_is_not_stored`, `test_oversized_response_is_not_stored` |
|
|
111
|
+
| Secrets in stored responses | Sensitive headers are dropped | `test_sensitive_headers_are_not_replayed` |
|
|
112
|
+
| Unbounded table growth | Expired keys are purged in the background (Postgres), `EXPIRE` (Redis) | `tests/test_cleanup.py` |
|
|
113
|
+
| Unexpected sequences of operations | Random sequences are compared with a reference model | Hypothesis state machine (40 examples, 30 steps each) |
|
|
114
|
+
|
|
115
|
+
The same storage and middleware tests run against **both** backends through a parametrized pytest fixture, so the `Storage` protocol is exercised for real. The full suite has 57 tests and runs in CI against real PostgreSQL 16 and Redis 7 service containers.
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
docker compose up -d
|
|
119
|
+
uv sync
|
|
120
|
+
uv run pytest
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Design decisions
|
|
124
|
+
|
|
125
|
+
- **Pure ASGI instead of `BaseHTTPMiddleware`.** `BaseHTTPMiddleware` is awkward with request bodies and streaming. A plain ASGI middleware gives full control over what is read and sent.
|
|
126
|
+
- **Atomicity comes from the database.** A "check, then write" sequence breaks under concurrent requests. PostgreSQL uses `INSERT ... ON CONFLICT (scope, key) DO NOTHING`; Redis uses a Lua script, which runs as one uninterruptible unit.
|
|
127
|
+
- **`locked_until` instead of a permanent lock.** If a process dies, its key must not stay busy forever. After the lock expires, another request takes the key over atomically (`UPDATE ... WHERE locked_until < now()` in Postgres, the same check inside the Lua script in Redis).
|
|
128
|
+
- **Server-side time.** Lock expiry and TTL are computed with the database clock (`now()` in Postgres, `TIME` in Redis), so several app servers cannot disagree about time.
|
|
129
|
+
- **Failures are not cached.** A `5xx` response is not stored, so a temporary error does not become permanent for that key. The trade-off: a handler that failed after a side effect may run again.
|
|
130
|
+
- **Last response message is held until it is stored.** The client receives the final chunk only after the response is saved, so an immediate retry does not hit a false `409`.
|
|
131
|
+
- **Core has no dependencies.** Backends are optional extras (`[postgres]`, `[redis]`), and the `Storage` protocol allows adding more.
|
|
132
|
+
|
|
133
|
+
## Benchmarks
|
|
134
|
+
|
|
135
|
+
Overhead for a request with a **new key** (the most expensive path: `claim`, handler, `complete`). 2000 requests per configuration, 20 concurrent, three runs, median shown.
|
|
136
|
+
|
|
137
|
+
| Configuration | req/s | p50, ms | p95, ms | p99, ms |
|
|
138
|
+
|---|---|---|---|---|
|
|
139
|
+
| No middleware | 783 | 1.05 | 2.18 | 3.04 |
|
|
140
|
+
| Middleware + PostgreSQL | 443 | 39.04 | 65.82 | 78.35 |
|
|
141
|
+
| Middleware + Redis | 542 | 29.72 | 52.92 | 61.29 |
|
|
142
|
+
|
|
143
|
+
Redis is roughly 25% faster than PostgreSQL at p50 and about 20% faster at p99 in this setup.
|
|
144
|
+
|
|
145
|
+
Caveats:
|
|
146
|
+
- Local measurement: app, PostgreSQL and Redis run on one Windows machine, with the databases in Docker. A Linux server will likely show different numbers.
|
|
147
|
+
- Requests go through `httpx.ASGITransport`, with no network and no uvicorn, so this measures the library and storage cost only.
|
|
148
|
+
- Each request makes two storage calls and 20 requests compete for connections, so latency includes queueing. Throughput is the more meaningful number.
|
|
149
|
+
- Run-to-run spread is noticeable (PostgreSQL p50 ranged from 39 to 46 ms).
|
|
150
|
+
- Replay latency (retries of a completed key) was not measured.
|
|
151
|
+
|
|
152
|
+
Reproduce: `uv run python benchmarks/bench.py`
|
|
153
|
+
|
|
154
|
+
## Limitations
|
|
155
|
+
|
|
156
|
+
- If a handler runs longer than `lock_seconds`, another request can take over the key and run the handler a second time. Set `lock_seconds` above your slowest handler.
|
|
157
|
+
- The middleware sees only HTTP. Side effects such as sending an email or calling an external API are not made idempotent by it. Use the same idempotency key downstream, or commit the key in the same database transaction as your business data.
|
|
158
|
+
- Streaming and oversized responses are not stored, so retries of those requests are **not** protected.
|
|
159
|
+
- If storing the response fails after the handler succeeded, the client still gets the response and the key is released, so a retry would run the handler again.
|
|
160
|
+
- The default scope is `"global"`: all clients share one key space. In real applications pass `scope_getter` (for example, the authenticated user id).
|
|
161
|
+
- Redis durability depends on your Redis persistence settings. For payments-grade guarantees prefer PostgreSQL.
|
|
162
|
+
- The Hypothesis state machine and the chaos test run against the PostgreSQL backend only.
|
|
163
|
+
|
|
164
|
+
## Development
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
uv sync # create the environment
|
|
168
|
+
docker compose up -d # PostgreSQL 16 and Redis 7
|
|
169
|
+
uv run pytest # tests
|
|
170
|
+
uv run ruff check . # lint
|
|
171
|
+
uv run ruff format . # format
|
|
172
|
+
uv run mypy # strict type checking
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Pre-commit hooks (ruff, ruff format, mypy) run on every commit. The design notes are in [`docs/design.md`](docs/design.md).
|
|
176
|
+
|
|
177
|
+
## License
|
|
178
|
+
|
|
179
|
+
MIT
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import os
|
|
3
|
+
import statistics
|
|
4
|
+
import time
|
|
5
|
+
import uuid
|
|
6
|
+
|
|
7
|
+
import asyncpg
|
|
8
|
+
import httpx
|
|
9
|
+
import redis.asyncio as aioredis
|
|
10
|
+
from fastapi import FastAPI
|
|
11
|
+
|
|
12
|
+
from idempotency_asgi import IdempotencyMiddleware
|
|
13
|
+
from idempotency_asgi.postgres import PostgresStorage
|
|
14
|
+
from idempotency_asgi.redis_storage import RedisStorage
|
|
15
|
+
from idempotency_asgi.storage import Storage
|
|
16
|
+
|
|
17
|
+
DSN = os.environ.get("DATABASE_URL", "postgresql://idem:idem@localhost:5432/idem")
|
|
18
|
+
REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/0")
|
|
19
|
+
N = 2000 # запросов на конфигурацию
|
|
20
|
+
WARMUP = 100
|
|
21
|
+
CONCURRENCY = 20
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def make_app(storage: Storage | None) -> FastAPI:
|
|
25
|
+
app = FastAPI()
|
|
26
|
+
|
|
27
|
+
@app.post("/pay")
|
|
28
|
+
async def pay(payload: dict[str, int]) -> dict[str, int]:
|
|
29
|
+
return payload
|
|
30
|
+
|
|
31
|
+
if storage is not None:
|
|
32
|
+
app.add_middleware(IdempotencyMiddleware, storage=storage)
|
|
33
|
+
return app
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
async def measure(app: FastAPI) -> list[float]:
|
|
37
|
+
latencies: list[float] = []
|
|
38
|
+
transport = httpx.ASGITransport(app=app)
|
|
39
|
+
sem = asyncio.Semaphore(CONCURRENCY)
|
|
40
|
+
|
|
41
|
+
async with httpx.AsyncClient(transport=transport, base_url="http://bench") as client:
|
|
42
|
+
|
|
43
|
+
async def one(i: int, record: bool) -> None:
|
|
44
|
+
headers = {"Idempotency-Key": uuid.uuid4().hex}
|
|
45
|
+
async with sem:
|
|
46
|
+
start = time.perf_counter()
|
|
47
|
+
response = await client.post("/pay", json={"amount": i}, headers=headers)
|
|
48
|
+
elapsed = (time.perf_counter() - start) * 1000
|
|
49
|
+
if response.status_code != 200:
|
|
50
|
+
raise RuntimeError(f"Unexpected status code: {response.status_code}")
|
|
51
|
+
if record:
|
|
52
|
+
latencies.append(elapsed)
|
|
53
|
+
|
|
54
|
+
await asyncio.gather(*(one(i, False) for i in range(WARMUP)))
|
|
55
|
+
t0 = time.perf_counter()
|
|
56
|
+
await asyncio.gather(*(one(i, True) for i in range(N)))
|
|
57
|
+
total = time.perf_counter() - t0
|
|
58
|
+
print(f" throughput: {N / total:.0f} req/s")
|
|
59
|
+
return latencies
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def report(name: str, latencies: list[float]) -> None:
|
|
63
|
+
q = statistics.quantiles(latencies, n=100)
|
|
64
|
+
print(f" p50 = {q[49]:.2f} ms, p95 = {q[94]:.2f} ms, p99 = {q[98]:.2f} ms")
|
|
65
|
+
print(f"[{name}] done\n")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def main() -> None:
|
|
69
|
+
print(f"requests per config: {N}, concurrency: {CONCURRENCY}\n")
|
|
70
|
+
|
|
71
|
+
print("[no middleware]")
|
|
72
|
+
report("no middleware", await measure(make_app(None)))
|
|
73
|
+
|
|
74
|
+
pool = await asyncpg.create_pool(DSN, min_size=5, max_size=20)
|
|
75
|
+
if pool is None:
|
|
76
|
+
raise RuntimeError("no pool")
|
|
77
|
+
pg = PostgresStorage(pool)
|
|
78
|
+
await pg.create_schema()
|
|
79
|
+
await pool.execute("TRUNCATE idempotency_keys")
|
|
80
|
+
print("[middleware + postgres]")
|
|
81
|
+
report("postgres", await measure(make_app(pg)))
|
|
82
|
+
await pool.close()
|
|
83
|
+
|
|
84
|
+
client = aioredis.from_url(REDIS_URL)
|
|
85
|
+
await client.flushdb()
|
|
86
|
+
print("[middleware + redis]")
|
|
87
|
+
report("redis", await measure(make_app(RedisStorage(client))))
|
|
88
|
+
await client.aclose()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
services:
|
|
2
|
+
postgres:
|
|
3
|
+
image: postgres:16
|
|
4
|
+
environment:
|
|
5
|
+
POSTGRES_USER: idem
|
|
6
|
+
POSTGRES_PASSWORD: idem
|
|
7
|
+
POSTGRES_DB: idem
|
|
8
|
+
ports:
|
|
9
|
+
- "5432:5432"
|
|
10
|
+
volumes:
|
|
11
|
+
- pgdata:/var/lib/postgresql/data
|
|
12
|
+
healthcheck:
|
|
13
|
+
test: ["CMD-SHELL", "pg_isready -U idem -d idem"]
|
|
14
|
+
interval: 2s
|
|
15
|
+
timeout: 3s
|
|
16
|
+
retries: 15
|
|
17
|
+
redis:
|
|
18
|
+
image: redis:7
|
|
19
|
+
ports:
|
|
20
|
+
- "6379:6379"
|
|
21
|
+
healthcheck:
|
|
22
|
+
test: ["CMD", "redis-cli", "ping"]
|
|
23
|
+
interval: 2s
|
|
24
|
+
timeout: 3s
|
|
25
|
+
retries: 15
|
|
26
|
+
|
|
27
|
+
volumes:
|
|
28
|
+
pgdata:
|