DEV Community

Fidwell Engineering
Fidwell Engineering

Posted on

PostgreSQL 12-State Step Leases vs Temporal + LangGraph: Handling Non-Idempotent Legacy ERPs Without Heavy Brokers

When an AI agent moves from answering questions to modifying real business systems — posting replenishment drafts, reconciling invoices, or updating warehouse tables — prompt engineering stops being the hardest problem. Crash recovery and duplicate side effects take over.

Many engineering teams start with a graph framework like LangGraph and later consider adding Temporal plus its visibility stack once worker crashes start causing partial writes. While Temporal is battle-tested for large microservice fleets, running multiple extra stateful clusters is often heavy for mid-sized engineering teams that already run reliable PostgreSQL servers.

At Dalian Fidwell Technology, we built ZeroOS as a self-hosted Linux + PostgreSQL control plane using three pragmatic database patterns instead of external broker clusters: a 12-state step lease machine, monotonic fencing tokens, and a three-tier tool safety ledger.

1. The Split-Brain Worker Problem

Consider an agent step that calls a legacy ERP HTTP endpoint:

  1. Worker A claims step seq=4 with a 30-second lease.
  2. Worker A sends the POST request, then hits a 40-second network stall or host pause.
  3. The lease expires; Worker B claims seq=4 and retries.
  4. Both requests reach the ERP — creating duplicate purchase orders.

In-memory graph checkpoints cannot solve this because the failure occurs across process boundaries and external I/O.

2. Atomic Lease Claiming with Monotonic Fencing Tokens

In PostgreSQL, we track every step inside a lease table and increment a monotonic fencing_token on every claim or takeover:

UPDATE agent_step_leases
SET state = 'RUNNING',
    lease_owner = $3,
    fencing_token = fencing_token + 1,
    lease_expires_at = NOW() + INTERVAL '30 seconds',
    updated_at = NOW()
WHERE task_id = $1
  AND step_seq = $2
  AND (
    state = 'READY'
    OR (state = 'RUNNING' AND lease_expires_at < NOW())
  )
RETURNING fencing_token, idempotency_key;
Enter fullscreen mode Exit fullscreen mode

When the worker finishes and commits its output digest, the UPDATE requires both the exact lease_owner and the exact fencing_token:

UPDATE agent_step_leases
SET state = 'COMMITTED',
    result_digest = $4,
    updated_at = NOW()
WHERE task_id = $1
  AND step_seq = $2
  AND state = 'RUNNING'
  AND lease_owner = $3
  AND fencing_token = $5
  AND lease_expires_at > NOW()
RETURNING task_id, step_seq;
Enter fullscreen mode Exit fullscreen mode

If zero rows are updated, the stale worker knows it was preempted and aborts any downstream commit.

3. Classifying Tools Before They Touch Production

Blind retries are dangerous when legacy ERPs lack deduplication keys. Every tool registered in ZeroOS must declare one of three safety tiers:

  • READ_ONLY: Safe to retry with exponential backoff.
  • IDEMPOTENT_WRITE: Downstream accepts an external key; ZeroOS generates a deterministic idempotency_key from task_id + step_seq + payload_hash and logs it prior to dispatch.
  • NON_IDEMPOTENT: No automatic retry on ambiguous timeouts. If the network drops after dispatch, the step transitions into RECONCILE_REQUIRED and routes through a fail-closed approval or reconciliation check before proceeding.

4. Secret Hygiene & Internal Staging Observation

To avoid leaking credentials through /proc/*/environ or crash dumps, ZeroOS injects short-lived credentials using an FD-Unlink descriptor pattern rather than plaintext environment variables.

In an isolated internal staging test on self-hosted Linux hardware, killing an active worker process mid-step resulted in lease expiry detection and standby worker takeover in ~6.99s (6,994 ms) with zero duplicate step commits. Because failover timing depends directly on heartbeat TTL, CPU load, and PostgreSQL I/O settings, treat this strictly as an internal test observation rather than an external uptime guarantee.

Paired optionally with LongMemOS (~3.1 MB standalone local memory engine, embedded_models=false, 463/500 or 92.6% in our internal LongMemEval test with O13 source-line evidence replay), teams can keep both agent execution state and long-term corporate memory inside their own Linux + PostgreSQL perimeter.

Top comments (9)

Collapse
 
raju_dandigam profile image
Raju Dandigam •

The separation between fencing a stale worker’s local commit and preventing a duplicate ERP effect is crucial. A fencing token can stop A from committing its step record, but it cannot recall a POST already accepted by the ERP. For a NON_IDEMPOTENT step, does lease takeover enter RECONCILE_REQUIRED before B can dispatch anything? A kill-after-send fixture with an independent ERP-side delivery counter would make that boundary very clear.

Collapse
 
derek_f66a6ae2c4ca30bf7db profile image
Fidwell Engineering •

Thanks, Raju — great catch, and that's exactly the boundary the SQL snippet alone doesn't show.

The intended rule is to transition an ambiguous NON_IDEMPOTENT_WRITE step into RECONCILE_REQUIRED before the standby worker sends another write, pausing it for reconciliation (e.g., checking a read-only ERP view/log or an approval gate) rather than blindly retrying. The monotonic fencing_token protects the local step-state commit; it cannot undo a POST the legacy ERP already accepted.

To keep the test scope transparent as well: the 6,994 ms staging observation measured standby takeover with no duplicate local step commits — it did not establish an ERP-side effect count for the kill-after-send window.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

a kill-after-send fixture is a good idea. does the erp-side delivery count come from the vendor or a shim in front of it?

Collapse
 
derek_f66a6ae2c4ca30bf7db profile image
Fidwell Engineering •

Good question, Robert — it depends on whether we're talking about the test harness or production:

  • In a CI / staging kill-after-send fixture, we put a lightweight local test shim (mock ERP HTTP receiver) in front of the worker so the harness can deterministically accept the POST, increment an independent delivery counter, and kill the worker before it records the receipt.
  • Against a real legacy vendor ERP in production, you rarely get a vendor-side delivery counter. Reconciliation reads whatever authoritative source the ERP exposes — typically a read-only ERP view, order-history table, or batch import log keyed by a business reference — and only when the legacy endpoint exposes neither do you place a thin idempotency shim in front of it or route RECONCILE_REQUIRED to a human approval gate.
Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

the harness/production split is the part i'd keep. a counter you control in CI, and whatever the ERP actually exposes in prod. the shim only shows up when neither exists.

Thread Thread
 
derek_f66a6ae2c4ca30bf7db profile image
Fidwell Engineering •

Spot on—keeping that seam clean is what saves you long-term. CI stays deterministic with a counter you own, prod leans on whatever native receipt or sequence field the ERP already exposes, and the shim stays strictly a last-resort fallback instead of leaking into the core state machine.

Thread Thread
 
robertpaschal profile image
Odinaka Robert Nnamani •

A counter you control in CI is a small thing to keep clean. It pays for itself the first time a test flakes.

Thread Thread
 
derek_f66a6ae2c4ca30bf7db profile image
Fidwell Engineering •

Exactly — being able to assert on an explicit fencing_token directly in SQL turns ugly concurrency flakes into deterministic test cases. In CI we can force a lease expiry, spin up a second worker against the same (task_id, step_seq), and verify in a single query that the stale worker's COMMITTED update affects 0 rows without mocking a separate workflow engine. Once you've debugged one silent duplicate write against a legacy ERP, owning that counter in Postgres feels worth every line of SQL.

Thread Thread
 
robertpaschal profile image
Odinaka Robert Nnamani •

forcing a lease to expire mid-flight and checking the stale worker's update hits 0 rows is the test that proves it.