Skip to main content

idempotency-kit

Production-ready idempotency library for async Python applications.

PyPI Python License CI codecov Docs

Ensure operations execute exactly once, even when called multiple times with the same idempotency key. Built for production microservices with graceful degradation, collision handling, and observability.

Features

  • Clean Architecture — core domain separated from infrastructure
  • Protocol-Based — easy to swap storage backends (Redis, custom)
  • Type-Safe — full type hints with Pydantic validation
  • Async First — built for asyncio applications
  • Graceful Degradation — high availability over strict exactly-once
  • In-flight Reservation — a retry that arrives while the original is still running waits for its result or gets a 409; the action runs once
  • Request Fingerprints — name the parameters that identify a request, and a key reused for a different one is refused instead of replayed
  • Observability — built-in metrics (hits, misses, collisions, latency)
  • Bulk Operations — efficient get_many, save_many, delete_many
  • Redis Cluster Compatible — non-transactional pipelines
  • Decorator Pattern — @async_idempotent for zero-boilerplate integration

Installation

pip install idempotency-kit

# With Redis support (recommended)
pip install idempotency-kit[redis]

# With Dishka DI
pip install idempotency-kit[dishka,redis]

Requirements: Python 3.11+, Redis 6+

Quick start

from idempotency_kit import AsyncIdempotencyCoordinator, PydanticResultAdapter, async_idempotent

class CreateOrderUseCase:
    def __init__(self, uow: AsyncUnitOfWork, coordinator: AsyncIdempotencyCoordinator):
        self._uow = uow
        self.coordinator = coordinator

    @async_idempotent(
        operation="order.create",
        adapter=PydanticResultAdapter(OrderDTO),
    )
    async def execute(
        self,
        dto: CreateOrderDTO,
        idempotency_key: str | None = None,
    ) -> OrderDTO:
        """Create order - idempotency handled automatically."""
        async with self._uow.transaction() as tx:
            # Your business logic - no idempotency code needed!
            order = await tx.orders.create(dto.items, dto.total)
            await tx.outbox.create(OrderCreatedEvent(order_id=order.id))
            
            return OrderDTO.from_entity(order)

Pass idempotency_key to downstream services for distributed idempotency:

# Orchestrate multiple services with same key
await identity_service.create_user(..., idempotency_key=idempotency_key)
await payment_service.charge(..., idempotency_key=idempotency_key)

How it works

1. Client provides key

POST /api/orders
Idempotency-Key: abc-123-def

2. Server checks cache

cached = await repo.get("order.create", "abc-123-def")
if cached:
    return cached.result  # Return immediately ✅

3. Server executes (if not cached)

order = await create_order(dto)
await repo.save(record)  # Cache result for future requests
return order

4. Concurrent requests handled

If two requests arrive while the first is still executing:

  • First request: reserves the key → execute → write the result over the reservation ✅
  • Second request: finds the reservation → waits for the first result → return ✅ (or a 409 with in_flight="raise")

Both requests get the same result, and the business logic ran once.

Use cases

  • HTTP APIs — ensure POST/PUT requests are idempotent
  • Background Jobs — prevent duplicate processing on retries
  • Event Consumers — handle duplicate events gracefully
  • Message Queues — at-most-once message processing

Documentation

📚 Full Documentation

Development

make install          # uv sync --group dev
make check            # ruff + mypy
make test-unit        # unit tests (no Docker)
make test-integration # integration tests (Docker required)
make test             # all tests with coverage
make docs-serve       # local docs preview

See CONTRIBUTING.md for the full guide.

License

Apache 2.0

Metadata

Release files for idempotency-kit 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for idempotency-kit 0.5.0
File Size Uploaded Provenance Actions
idempotency_kit-0.5.0.tar.gz 34.7 kB Without provenance Details for idempotency_kit-0.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for idempotency-kit 0.5.0
File Interpreter ABI Platform Actions
idempotency_kit-0.5.0-py3-none-any.whl Python 3 none any Details for idempotency_kit-0.5.0-py3-none-any.whl

Total release size: 80.3 kB

Release files / idempotency_kit-0.5.0.tar.gz

Download URL idempotency_kit-0.5.0.tar.gz
Size 34.7 kB
Tags Source
SHA-256 checksum
How to use checksums
3c8f49b8f6606133724cf71019a27db1f1538c58e984d1b33287ea09281bfdf3
BLAKE2b-256 checksum
How to use checksums
b63ad7703184fa0a6852adf8dc2411d10641e3d7e92772129d424c5253bbbdf4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / idempotency_kit-0.5.0-py3-none-any.whl

Download URL idempotency_kit-0.5.0-py3-none-any.whl
Size 45.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a38862004a2481fc4e4d37e88738d35258ea0bd6e3660b146d0c369186aeed39
BLAKE2b-256 checksum
How to use checksums
67fc5fd5c98fd60d33a106b8b7a00853b939197b5c2a22277f2b6fb65113a29b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for idempotency-kit 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page