Skip to main content
Back to Community & Earn Hub

Distributed Locks & Idempotent Tool Execution for Multi-Agent Workflows: Preventing Double-Writes with Redis and Postgres Advisory Locks

@vikram_joshi4 days ago·1 min read 1936 views
Distributed Locks & Idempotent Tool Execution for Multi-Agent Workflows: Preventing Double-Writes with Redis and Postgres Advisory Locks

The Multi-Agent Race Condition Trap

In single-threaded demos, an agent executes one tool at a time sequentially. In production, async fan-outs and network retries introduce nasty concurrency bugs:

  • Two parallel sub-agents both decide to patch the same user record or trigger the same webhook.
  • A slow MCP tool takes 12 seconds, the agent client times out at 10s and retries—executing the side-effect twice.

To make agent tool execution safe for real-world transactions, every mutating tool needs two primitives: an atomic Distributed Lock and an Idempotency Ledger.


Architecture: Lock + Idempotency Key at the Tool Boundary

text
[Sub-Agent A: call refund(order=101, key="traj_9a_step_4")]
[Sub-Agent B: call refund(order=101, key="traj_9a_step_4")]
         │
         ▼
[Postgres Transaction: pg_advisory_xact_lock(hashtext("order:101"))]
  ├── Sub-Agent A acquires lock -> Checks idempotency_keys -> Executes -> Saves result -> COMMIT
  └── Sub-Agent B waits -> Acquires lock -> Sees "traj_9a_step_4" already DONE -> Returns cached result!

Python + PostgreSQL Advisory Lock Implementation

Using PostgreSQL's transaction-scoped pg_advisory_xact_lock avoids deadlocks completely because the lock automatically releases on COMMIT or ROLLBACK even if the Python worker crashes:

python
import hashlib
import json
from sqlalchemy import text
from sqlalchemy.orm import Session

def _lock_key(resource_id: str) -> int:
    # Deterministic signed 64-bit integer for Postgres advisory locks
    digest = hashlib.sha256(resource_id.encode()).digest()[:8]
    return int.from_bytes(digest, "big", signed=True)

def execute_idempotent_tool(
    db: Session,
    resource_id: str,
    idempotency_key: str,
    action_fn,
) -> dict:
    lock_id = _lock_key(resource_id)

    with db.begin():
        # 1. Serialize concurrent agents targeting the exact same resource
        db.execute(text("SELECT pg_advisory_xact_lock(:lid)"), {"lid": lock_id})

        # 2. Return cached outcome if this step was already executed
        existing = db.execute(
            text("SELECT result_json FROM tool_idempotency_ledger WHERE key = :k"),
            {"k": idempotency_key},
        ).scalar_one_or_none()
        if existing is not None:
            return json.loads(existing)

        # 3. Execute the mutating side-effect safely inside the lock
        result = action_fn()

        db.execute(
            text("INSERT INTO tool_idempotency_ledger (key, result_json) VALUES (:k, :r)"),
            {"k": idempotency_key, "r": json.dumps(result)},
        )
        return result

Production Checklist

  • Scope keys to (trajectory_id, step_id, tool_name): Ensures legitimate future runs can modify the order while preventing duplicate retries within the same run.
  • Keep external HTTP calls idempotent too: Forward Idempotency-Key headers to downstream Stripe, Slack, or GitHub APIs.
2 Comments

Discussion

@rohan_mehta4 days ago

Transaction-scoped pg_advisory_xact_lock is so much safer than manual Redis SET NX locks when a Python worker OOMs mid-request—Postgres automatically releases the lock on socket drop/rollback without waiting for a 60s TTL expiry.

@priya_sharma4 days ago

Scoping idempotency keys to (trajectory_id, step_id, tool_name) is the exact detail that prevents accidental collision across future legitimate runs.

Join the developer discussion

Sign in or create a free account to comment (+10 pts) and tag helpful AIStoreHub repositories.