Metadata-Version: 2.4
Name: idemgate
Version: 0.1.0
Summary: Redis-backed idempotency for async FastAPI APIs
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/empouya/idemgate
Project-URL: Repository, https://github.com/empouya/idemgate
Project-URL: Issues, https://github.com/empouya/idemgate/issues
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi<1,>=0.115
Requires-Dist: redis<8,>=5
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: httpx<1,>=0.27; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: setuptools>=77.0.3; extra == "dev"
Requires-Dist: wheel; extra == "dev"
Dynamic: license-file

# IdemGate

IdemGate adds Redis-backed idempotency to async FastAPI endpoints. A client sends an `Idempotency-Key` with a request. A successful response is stored for a configurable time, so an identical retry receives the same response without rerunning the endpoint. A concurrent retry or a key reused with different request data receives `409`.

Requires Python 3.11+, FastAPI, and Redis. IdemGate uses one shared Redis instance for request ownership across application workers.

## Install

```bash
python -m pip install idemgate uvicorn
```

Run Redis 7 or newer and make its URL available to your application. `idemgate` brings in its FastAPI and Redis Python dependencies.

## Protect an endpoint

Save this example as `app.py`:

```python
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from uuid import uuid4

from fastapi import FastAPI
from pydantic import BaseModel
from redis.asyncio import Redis

from idemgate import IdempotencyRoute, idempotent
from idemgate.redis_store import RedisAcquirer


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    redis = Redis.from_url(
        os.getenv("REDIS_URL", "redis://127.0.0.1:6379/0"),
        decode_responses=False,
    )
    app.state.idempotency_store = RedisAcquirer(redis)
    try:
        yield
    finally:
        await redis.aclose()


app = FastAPI(lifespan=lifespan)
app.router.route_class = IdempotencyRoute  # Set before adding protected routes.


class JobInput(BaseModel):
    task: str


@app.post("/jobs", status_code=201)
@idempotent(ttl=3600)
async def create_job(payload: JobInput) -> dict[str, str]:
    return {"job_id": uuid4().hex, "task": payload.task}
```

Start the app with `uvicorn app:app`. Send the same request twice:

```bash
curl -i -X POST http://127.0.0.1:8000/jobs \
  -H 'Idempotency-Key: job-123' \
  -H 'Content-Type: application/json' \
  -d '{"task":"email-report"}'
```

Both completed calls return `201` with the same `job_id` while the stored response is valid. This small example generates a value in memory; the [order example](https://github.com/empouya/idemgate/blob/main/examples/fastapi_orders.py) shows a SQLite write and authenticated caller namespace.

Use `@idempotent(config=IdempotencyConfig(...))` to set `ttl_seconds`, `processing_lease_seconds`, `renew_interval_seconds`, `max_request_bytes`, and `max_response_bytes`. Defaults are 3,600 seconds, 30 seconds, 10 seconds, 1 MiB, and 1 MiB. The `ttl=` shortcut sets only the completed response TTL. The completed TTL begins when the response is stored; retries do not extend it. After expiry, a repeated request can run again.

For authenticated or personalized endpoints, pass `namespace=` a resolver that **verifies the caller** and returns a stable caller ID before Redis lookup. A replay skips dependencies inside the protected endpoint, so endpoint dependencies alone cannot protect a stored response. Do not use raw credentials as a namespace. The [order example](https://github.com/empouya/idemgate/blob/main/examples/fastapi_orders.py) demonstrates this setup. Set `app.state.idempotency_store` and `IdempotencyRoute` for every protected route; using `@idempotent` without that route class raises a setup error.

## Request and replay behavior

The request identity combines HTTP method, concrete path, caller namespace, and key. For the same identity, query bytes, `Content-Type`, and body bytes must match exactly. JSON is compared as bytes, so equivalent JSON with different spacing counts as different data. Keys must contain 1–255 visible ASCII characters.

Successful final statuses `200`–`299` can be replayed with their captured status, body, and application headers. Non-2xx responses and handler exceptions are not cached as successes. Streaming responses, background tasks, partial content, and responses that depend on untracked request headers such as `Vary` are unsupported. See the [behavior contract](https://github.com/empouya/idemgate/blob/main/docs/contract.md) for the exact rules and limits.

| Response | Meaning |
| --- | --- |
| `400` | Missing or invalid `Idempotency-Key`. |
| `409 idempotency_in_progress` | An identical request is still running. |
| `409 idempotency_key_reused` | The key was used with different request data. |
| `413` | Request body exceeds the configured limit. |
| `503 idempotency_store_unavailable` | Redis acquisition failed before the endpoint ran. |
| `503 idempotency_outcome_unknown` | Execution may have begun, but lease renewal or completion could not be confirmed. |

Library errors have the shape `{"error":{"code":"...","message":"..."}}`. If the owner crashes, its processing lease eventually expires. If Redis fails during or after execution, the application side effect may already have happened. IdemGate cannot atomically commit an external database change with its Redis record and does not guarantee exactly-once external effects. Use an application-level unique constraint or transaction for operations that must remain unique beyond the Redis TTL or through uncertain outcomes.

## License

Licensed under the [Apache License 2.0](https://github.com/empouya/idemgate/blob/main/LICENSE).
