Skip to main content

fencekit

CI PyPI Python License: MIT

Redis-backed idempotency and fenced distributed locks for background jobs.

Celery with acks_late redelivers work after a worker crash. Redis gives you SET NX and Lua. fencekit wraps those into tested pieces:

Piece Problem it solves
IdempotencyGuard Double-start / redelivery of the same logical job
DistributedLock + fencing token Two workers on the same resource at once
FenceGate / fenced_update Stale lock holder overwriting newer state after TTL expiry

Extracted from ChessMate (Celery + Redis + Postgres). See DESIGN.md for guarantees, non-guarantees, and crash semantics.

Install

pip install fencekit
pip install "fencekit[django]"   # optional Django QuerySet helper

Requires Redis 6+ (tested with Redis 7) and Python 3.10+.

Quick example

from datetime import timedelta
from redis import Redis

from fencekit import (
    DistributedLock,
    FenceGate,
    IdempotencyGuard,
    IdempotencyResultMissing,
    fenced_update,
    idempotency_key,
)

r = Redis.from_url("redis://localhost:6379/0", decode_responses=True)
guard = IdempotencyGuard(r)
lock = DistributedLock(r)
fence = FenceGate(r)

def analyze_batch(job) -> dict | None:
    key = idempotency_key(
        {"game_ids": ["abc", "def"], "engine": "sf16"},
        namespace="analysis",
    )
    if not guard.try_begin(key, ttl=timedelta(hours=24)):
        try:
            return guard.get_result(key)  # prior outcome on redelivery
        except IdempotencyResultMissing:
            return None  # still pending or done without a memo

    handle = lock.acquire(f"analysis:{job.pk}", ttl=timedelta(minutes=5))
    try:
        fence.set_if_fresh(handle.token, f"analysis:{job.pk}:status", "running")
        fenced_update(
            type(job).objects.filter(pk=job.pk),
            handle.token,
            updates={"progress": 50, "status": "running"},
        )
        result = {"report_id": job.pk, "status": "done"}
        guard.mark_done(key, result=result, ttl=timedelta(hours=24))
        return result
    finally:
        lock.release(handle)

API overview

idempotency_key(payload, namespace=...): deterministic key from JSON-canonicalized payload.

IdempotencyGuard.try_begin / mark_done / get_result: at-most-once start; optional JSON memo on completion.

DistributedLock.acquire / release / extend: lease plus monotonic fencing token (Lua).

FenceGate.set_if_fresh: atomic fenced Redis string writes.

fenced_update(queryset, token, updates=...): fenced Django/Postgres UPDATE in one statement.

Typed public API (py.typed). No Celery adapter yet; wire the guard in your task body for now.

Comparison

Short view. Sources and nuance: docs/COMPARISON.md.

Dedup start Celery plugin Stale-write fencing Postgres helper
fencekit Yes Manual Yes fenced_update
celery-once / celery-singleton Yes Yes No No
redis-py Lock No No No No
relier Yes Yes Partial (framework) App-owned

fencekit complements celery-once. celery-once dedupes scheduling; fencekit rejects writes from a worker whose lock TTL already expired.

Local demo (no cloud)

Redis via Docker on your machine. No hosted services, no monthly bill.

docker compose -f examples/reference/docker-compose.yml up -d
pip install -e .
python examples/reference/demo_stale_fence.py
python examples/reference/demo_idempotency.py

See examples/reference/README.md.

Guarantees

Claim Status
At-most-once start within idempotency TTL Yes (SET NX)
Memoized result after mark_done(..., result=...) Yes (within TTL)
Mutual exclusion while lock TTL held (single Redis primary) Best-effort lease
Stale holder blocked via FenceGate / fenced_update Yes (when used)
Exactly-once delivery No
Safety under Redis failover / split brain No
Writes that skip the fencing token No

fencekit does not implement Redlock. Fencing only works when the storage layer checks the token in the same operation as the write.

Development

REM Windows (CMD)
python -m pip install -e ".[dev]"
python -m ruff check src tests
python -m mypy src
python -m pytest -m "not integration" -q

Full suite (Redis on localhost:6379):

set FENCEKIT_REDIS_URL=redis://localhost:6379/15
python -m pytest -q
# Linux/macOS with uv
uv sync --extra dev
uv run pytest

CI runs lint, type-check, and tests on Python 3.10–3.13 with Redis. Releases publish to PyPI via Trusted Publishing (OIDC, no long-lived token).

License

MIT

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fencekit-0.4.0.tar.gz (30.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fencekit-0.4.0-py3-none-any.whl (17.9 kB view details)

Uploaded Python 3

File details

Details for the file fencekit-0.4.0.tar.gz.

File metadata

  • Download URL: fencekit-0.4.0.tar.gz
  • Upload date:
  • Size: 30.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for fencekit-0.4.0.tar.gz
Algorithm Hash digest
SHA256 0977876a9af22beee6910287bc0a17034b024fd152339252dc44412429f6a652
MD5 8a4565a54090145684045497e72f2a7e
BLAKE2b-256 82064bf176c48a2c9f8c4e86cb05b548643e1e4b0a4278440079877da65d4ddc

See more details on using hashes here.

Provenance

The following attestation bundles were made for fencekit-0.4.0.tar.gz:

Publisher: release.yml on ahmed5145/fencekit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fencekit-0.4.0-py3-none-any.whl.

File metadata

  • Download URL: fencekit-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 17.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for fencekit-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5066d208ad84194ef4d4a1685f1a34ea0b4e358371e8cda9a20506d5dfc690f4
MD5 b65816d3aed33144df6b64a9daf51833
BLAKE2b-256 2fc1749e99a9990ff0c9400d75e3ff0f9232f82b56bdb70a6668b881b22e95d1

See more details on using hashes here.

Provenance

The following attestation bundles were made for fencekit-0.4.0-py3-none-any.whl:

Publisher: release.yml on ahmed5145/fencekit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.6.1

2 files

0.6.0

2 files

0.5.0

2 files

This release

0.4.0 This release

2 files

0.3.2

2 files

0.3.1

2 files

0.3.0

2 files

0.2.0

2 files

0.1.0

2 files

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