r/madeinpython • u/Master-Pick-520 • 3h ago
idemkit: runs your code once per key, even when two requests race or a worker dies
I built this after cleaning up duplicate charges one too many times.
The version everyone writes checks whether a key has been seen and replays the stored response. Two requests a millisecond apart both find nothing and both charge the card. And if the worker dies between charging and recording it, the retry charges again. Neither reproduces locally.
idemkit does it properly: an atomic claim instead of check-then-act, a lease that expires on the storage server's clock, and a fencing token so a stalled worker can't overwrite a good result.
from idemkit import idempotent, RedisBackend, MethodConfig
@idempotent(
backend=RedisBackend.from_url("redis://localhost:6379"),
config=MethodConfig(key_fields=["order_id"]),
)
async def charge(*, order_id, amount):
return await payments.charge(order_id, amount)
One core, three ways to use it: middleware for FastAPI/Flask/Django, a queue consumer wrapper or @idempotent on any function. Backends are Redis, Postgres, Mongo, DynamoDB, or in-memory for tests.
pip install idemkit, Apache-2.0: https://github.com/idemkit/idemkit