Skip to content

Instantly share code, notes, and snippets.

@Graeme22
Last active January 7, 2026 05:51
Show Gist options
  • Select an option

  • Save Graeme22/5cd3bffba46480d3936dad407b14d6a4 to your computer and use it in GitHub Desktop.

Select an option

Save Graeme22/5cd3bffba46480d3936dad407b14d6a4 to your computer and use it in GitHub Desktop.
Idempotency with coredis
from datetime import timedelta
from coredis import Redis
redis = Redis.from_url("redis://localhost:6379", decode_responses=True)
async def idempotent(key: str, ttl: timedelta | int | None = 60) -> bool:
"""
Shields code from being run multiple times.
"""
return bool(
await redis.set(f"pydempotent:{key}", 1, condition=PureToken.NX, ex=ttl)
)
# Example usage
for _ in range(10):
if await idempotent("test_key"):
print("called!") # this will only print once!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment