Skip to main content
Back to all articles
AI Engineering 13 min readUpdated October 28, 2026

Two Agent Workers Saw the Same State. Both Were Right. Your System Was Wrong.

Durable agents create a distributed-systems problem the moment retries, queue redelivery, failover, or slow model calls let two workers act on the same run. Use optimistic concurrency, leases, fencing tokens, idempotency, and short commit boundaries to keep stale workers from corrupting workflow state.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#AI Agents#Concurrency#Race Conditions#Optimistic Locking#Fencing Tokens#Distributed Systems#PostgreSQL#TypeScript#Python#Production AI
On this page

At 10:41 AM, Worker A picks up an infrastructure-agent run.

The run is on checkpoint version 18. The agent has already collected service health, found one unhealthy replica, and is about to decide whether a restart is safe.

Worker A acquires a 30-second lease and calls the model.

Then the model call stalls.

Thirty seconds pass.

The queue decides the work is available again. Worker B acquires the run, reads the same business state, gets a new lease, and makes a perfectly reasonable decision: restart replica api-3.

At 10:42 AM, Worker A wakes up.

Its model response is also perfectly reasonable.

It still believes it owns the run.

It tries to restart api-3 too.

Nothing about either model response is obviously wrong.

The bug is that two workers made valid decisions against a state that only one of them was still allowed to advance.

That is not a prompting problem.

It is concurrency control.

Once an agent runtime has queues, retries, durable checkpoints, human pauses, failover, or multiple workers, I stop thinking of it as one chatbot process. I treat it as a distributed system whose state can be observed, delayed, replayed, and contested.

And the distinction I want engineers to keep is this:

Idempotency protects repeated logical actions. Concurrency control protects competing logical decisions. Production agents often need both.

Why agents are unusually good at creating race conditions

Traditional request handlers are usually short.

Agent steps are not.

A single logical transition might contain:

Text
load checkpointretrieve evidencecall modelcall another modelwait for toolrequest human approvalresume laterwrite stateexecute side effect

The expensive parts can take seconds, minutes, or hours.

That creates large windows where the state you originally read can become stale.

A few common ways a second worker appears:

Text
queue visibility timeout expiresworker process crashes and task is redeliveredprovider timeout triggers failoverworkflow engine resumes from a checkpointhuman approval wakes a second executoroperator manually retries a stuck taskautoscaling adds consumersnetwork partition makes ownership ambiguous

Azure's Competing Consumers pattern is useful precisely because multiple workers improve throughput and availability. But the moment work for the same logical entity can overlap, you need a rule for who is allowed to commit the next transition.

The queue can help distribute work.

It cannot decide whether a worker's *business state* is still current after a thirty-second model call.

Idempotency is necessary, but it does not solve this race

I already use idempotency for agent side effects. I covered that in Idempotency Matters More Once an LLM Can Cause Side Effects.

But idempotency answers a different question.

Suppose two workers both try:

Text
restart_service(  service="api",  replica="api-3",  idempotency_key="restart:run-8421:api-3")

If they reuse the same key, the executor can collapse the duplicate physical action.

Good.

Now change the race.

Worker A reads state version 18 and decides:

Text
restart api-3

Worker B also reads version 18, but fresh metrics arrive and it decides:

Text
scale api from 6 to 8 replicas

Those are two different logical actions with two different idempotency keys.

Both could execute exactly once.

And the workflow could still be wrong because both were derived from the same old state and both attempted to become the next transition.

Idempotency cannot answer:

Text
Which decision was allowed to advance version 18?

For that, I want optimistic concurrency or another explicit serialization boundary.

Start with a versioned workflow state

I like every durable run to have a monotonically increasing version.

TypeScript
type RunStatus =  | "ready"  | "planning"  | "waiting"  | "executing"  | "complete"  | "failed";​type AgentRun = {  runId: string;  version: number;  status: RunStatus;  currentStep: string;  leaseOwner: string | null;  leaseExpiresAt: string | null;  fence: number;};

The important field is not status.

It is version.

When a worker reads:

Text
run-8421version = 18status = planning

its later write should say:

Text
Apply this transition only if the run is still version 18.

In PostgreSQL, the core operation can be boring on purpose:

SQL
UPDATE agent_runsSET  status = $1,  current_step = $2,  version = version + 1,  updated_at = now()WHERE run_id = $3  AND version = $4RETURNING version;

If expectedVersion = 18 and another worker has already advanced the row to version 19, this update affects zero rows.

That zero-row update is not a database inconvenience.

It is the system telling you:

Your plan was made against stale state. You no longer have permission to commit it.

AWS documents the same optimistic-locking pattern for DynamoDB: keep a version attribute and make the update conditional on the version you last read. If another process changed the item first, the condition fails instead of silently overwriting the newer state.

Compare-and-swap should surround the commit, not the whole reasoning step

A tempting approach is to hold a database row lock while the model thinks.

I avoid that.

This is a bad production shape:

Text
BEGINSELECT ... FOR UPDATEcall LLM for 12 secondscall retrievalcall another toolUPDATECOMMIT

PostgreSQL row locks are useful. But a slow model call is not a short critical section.

Holding database locks across remote inference creates avoidable lock wait time, deadlock surface, transaction age, and contention. It also couples database throughput to provider latency.

I prefer a three-phase shape:

Text
1. READ   load version 18 + evidence snapshot​2. PLAN   model/retrieval/tool reasoning outside DB transaction​3. COMMIT   short conditional write:   version 18 -> version 19

If the commit loses the race, do not force the old plan through.

Re-read.

Then decide whether the plan can be safely reused, needs revalidation, or must be regenerated.

TypeScript
class ConcurrencyConflict extends Error {}​type PlannedTransition = {  expectedVersion: number;  nextStatus: RunStatus;  nextStep: string;  proposedAction?: {    name: string;    args: unknown;  };};​async function commitTransition(  runId: string,  plan: PlannedTransition,): Promise<number> {  const result = await db.query<{ version: number }>(    `UPDATE agent_runs       SET status = $1,           current_step = $2,           version = version + 1,           updated_at = now()     WHERE run_id = $3       AND version = $4     RETURNING version`,    [      plan.nextStatus,      plan.nextStep,      runId,      plan.expectedVersion,    ],  );​  if (result.rowCount !== 1) {    throw new ConcurrencyConflict(      `Run ${runId} changed after planning`,    );  }​  return result.rows[0].version;}

The model is allowed to be slow.

The commit is not allowed to pretend time stood still while the model was thinking.

A version check prevents lost updates, but it does not assign worker ownership

Optimistic concurrency answers:

Text
Is the state I planned against still current?

A lease answers another question:

Text
Which worker currently has permission to make progress on this run?

For long-running distributed work, leases are often better than permanent locks because ownership expires when a worker disappears.

A lease record might look like:

Text
run_id             run-8421lease_owner        worker-blease_expires_at   2026-09-26T10:42:30Zfence               42

A worker claims an expired lease atomically:

SQL
UPDATE agent_runsSET  lease_owner = $1,  lease_expires_at = now() + interval '30 seconds',  fence = fence + 1,  updated_at = now()WHERE run_id = $2  AND (    lease_expires_at IS NULL    OR lease_expires_at < now()  )RETURNING version, fence, lease_expires_at;

The worker receives:

Text
version = 18fence = 42

It now has evidence that it acquired the latest lease.

But the lease alone is still not enough.

The dangerous bug: an expired worker can wake up

This is the part many lock implementations miss.

Worker A acquires a lease with token 41.

Then it pauses.

Maybe the process is frozen by GC. Maybe its container is suspended. Maybe the network drops. Maybe the model SDK hangs longer than expected.

Its lease expires.

Worker B acquires the same run with token 42.

Worker B proceeds correctly.

Then Worker A wakes up.

Worker A might not immediately know its lease is gone.

If the only protection was:

Text
I successfully acquired a lease earlier

Worker A can still send a stale mutation.

Hazelcast's FencedLock documentation describes this exact distributed-systems problem: a paused client can lose its session, another client can acquire the lock, and the old client can later wake up believing it still owns the resource.

The fix is a fencing token.

A fencing token makes stale ownership rejectable

A fencing token is a monotonically increasing ownership epoch.

Every time ownership changes:

Text
worker A -> fence 41worker B -> fence 42worker C -> fence 43

The worker must carry that number to the mutation boundary.

TypeScript
type ExecutableAction = {  runId: string;  fence: number;  idempotencyKey: string;  action: string;  args: unknown;};

The trusted executor or protected resource remembers the highest fence it has accepted.

TypeScript
async function executeWithFence(  command: ExecutableAction,): Promise<unknown> {  return db.transaction(async (tx) => {    // Lock the authoritative lease row, not only a history of seen fences.    const owner = await tx.query<{ fence: number; lease_valid: boolean }>(      `SELECT fence, lease_expires_at > now() AS lease_valid         FROM agent_runs        WHERE run_id = $1        FOR UPDATE`,      [command.runId],    );    const current = owner.rows[0];    if (!current || current.fence !== command.fence ||        !current.lease_valid) {      throw new Error("Lease ownership is no longer valid");    }​    const guard = await tx.query<{      highest_fence: number;    }>(      `SELECT highest_fence         FROM execution_guards        WHERE run_id = $1        FOR UPDATE`,      [command.runId],    );​    const highest = guard.rows[0]?.highest_fence ?? 0;​    if (command.fence < highest) {      throw new Error(        `Stale worker: fence ${command.fence} < ${highest}`,      );    }​    await tx.query(      `INSERT INTO execution_guards         (run_id, highest_fence)       VALUES ($1, $2)       ON CONFLICT (run_id)       DO UPDATE SET highest_fence = GREATEST(         execution_guards.highest_fence,         EXCLUDED.highest_fence       )`,      [command.runId, command.fence],    );​    return executeIdempotently(tx, command);  });}

Now imagine Worker A wakes late with fence 41.

The authoritative lease row now carries fence 42, so the transaction rejects fence 41 even if the separate execution guard has not previously observed the newer worker.

Worker A does not get to argue that its plan is reasonable.

It is stale.

The executor rejects it before the side effect.

That is the property I want.

A lease is a statement about time. A fencing token is evidence of ownership order.

The resource has to enforce the fence

This caveat matters.

Generating a fencing token and putting it in logs does nothing by itself.

The mutation boundary must reject stale tokens.

For a database effect, lock and validate the current authoritative lease alongside the guarded write. Checking only the largest fence that an executor happened to see is insufficient: an old worker could arrive before the new worker's first write. The transaction example protects effects committed in that database transaction; a remote provider call needs a dedicated trusted execution/outbox protocol, not an RPC performed while holding the database lock. A Python preflight check outside the commit would be a time-of-check/time-of-use race, so the executor itself must enforce the fence atomically.

If the target is your own database or internal service, that is straightforward: store the highest accepted fence and reject lower values.

If the target is an external SaaS API that knows nothing about your fencing scheme, you cannot make the remote provider suddenly understand token 42.

In that case I put a trusted executor in front of the remote mutation:

Text
agent worker   ↓ proposaltrusted executor   ├─ validates current workflow version   ├─ validates active fence   ├─ validates authorization   ├─ validates idempotency key   └─ calls external API

This narrows the race substantially.

It still cannot revoke a remote request that was already sent by an old worker before ownership changed.

That is why fencing composes with idempotency and reconciliation rather than replacing them.

For external side effects, the architecture is usually:

Text
current version+ valid fence+ idempotency key+ unknown-outcome reconciliation

not one magical lock.

This is the architecture I would ship

Concurrency control for durable AI agent workers

There are deliberately several guards.

The queue decides which workers receive work.

The lease decides who currently owns the run.

The version check decides whether the planned transition is still current.

The fence prevents an older owner from acting after ownership has moved on.

The idempotency key prevents one logical side effect from happening twice.

Those controls overlap a little.

That is fine.

They are defending different failure modes.

Do not make the LLM responsible for concurrency

I do not put this in the system prompt:

Text
Before modifying anything, make sure no other agent is working on it.

The model cannot establish that guarantee from text context.

It does not own the queue.

It does not control transaction isolation.

It cannot know that another worker committed version 19 a millisecond ago unless the execution layer checks.

The model's job is to propose a transition.

The runtime's job is to decide whether that proposal is still admissible.

TypeScript
type ProposedAction = {  expectedVersion: number;  action: string;  args: unknown;};​async function executeProposal(  runId: string,  proposal: ProposedAction,  lease: {    owner: string;    fence: number;  },) {  const committedVersion = await commitTransition(    runId,    {      expectedVersion: proposal.expectedVersion,      nextStatus: "executing",      nextStep: proposal.action,      proposedAction: proposal,    },  );​  return trustedExecutor.execute({    runId,    workflowVersion: committedVersion,    fence: lease.fence,    idempotencyKey: makeActionKey(      runId,      committedVersion,      proposal,    ),    action: proposal.action,    args: proposal.args,  });}

If the CAS fails, the proposal does not execute.

That is the important line.

Not every conflict needs another model call

When optimistic concurrency detects a conflict, the naive recovery is:

Text
call model again

Sometimes that is correct.

Sometimes it is wasteful.

I classify conflicts.

Benign metadata change

Maybe another worker only updated a heartbeat or trace pointer.

If the fields relevant to the plan are unchanged, the runtime may safely rebase the plan onto the new version without another expensive model call.

Evidence changed

If policy, inventory, account state, service health, or authorization changed, the plan must be revalidated or regenerated.

Terminal transition

If another worker already completed or cancelled the run, stop.

Competing consequential action

If another worker already committed a different mutation, the stale plan should normally be discarded and replanned from current state.

This is why I like storing what the plan depended on.

TypeScript
type PlanDependency = {  key: string;  version: string;};​type PlanEnvelope = {  expectedRunVersion: number;  dependencies: PlanDependency[];  proposal: ProposedAction;};

Now conflict recovery can compare the exact dependency versions instead of blindly assuming every state change invalidates everything.

Human approval has a concurrency version too

Human-in-the-loop workflows create especially long stale windows.

Suppose an agent asks a manager to approve:

Text
Refund $780 to customer C-91

The manager approves ten minutes later.

During those ten minutes:

Text
another support agent could issue a partial refundthe order could be cancelledfraud status could changepolicy could changethe workflow could be retried by another worker

An approval should therefore bind to the exact state and action that was reviewed.

TypeScript
type Approval = {  approvalId: string;  runId: string;  runVersion: number;  requestHash: string;  approvedBy: string;  approvedAt: string;};

Before execution:

Text
current run version == approved run version?request hash still matches?authorization still valid?evidence freshness still acceptable?

If not, the approval is stale.

Do not reinterpret “approved earlier” as “approved whatever the agent wants to do now.”

This fits the same principle from Your Agent Is Authorized to Act. It Still Shouldn't.: consequential actions need current evidence, not just a historical green light.

Provider failover can resurrect stale work

The previous article covered provider failover, circuit breakers, and graceful degradation.

Failover makes concurrency control more important.

Imagine:

Text
Worker A  checkpoint v18  calls provider A  request times out​runtime decides provider A is unhealthyworkflow resumes through provider BWorker B commits v19​provider A's original request eventually returnsWorker A wakes with an old plan

If Worker A is allowed to commit just because its model answer arrived eventually, failover created a race.

The correct path is:

Text
model response arrives→ compare expected version→ validate lease/fence→ stale? reject or replan

The inference provider should not own workflow truth.

A late model response is just a late proposal.

Queue redelivery is normal, not exceptional

Production queues generally optimize for not losing work.

That means duplicate delivery or redelivery after a worker failure is a normal design concern.

Azure's Competing Consumers guidance explicitly calls out reliable queues and failure recovery, including cases where a message returns to the queue so another consumer can process it.

So I design handlers as though this sequence will happen eventually:

Text
worker receives messageworker starts workworker becomes slow or loses leasemessage becomes available againsecond worker receives same logical workfirst worker returns

The protection should not depend on how rare you think that sequence is.

It should be encoded in the state transition protocol.

Row locks still have a place

I am not arguing that optimistic concurrency replaces every lock.

PostgreSQL's current documentation supports row-level locking such as SELECT ... FOR UPDATE, and it is the right primitive for some short local critical sections.

For example, inside the trusted executor I may need to serialize updates to an execution-guard row:

SQL
BEGIN;​SELECT highest_fenceFROM execution_guardsWHERE run_id = $1FOR UPDATE;​-- validate + update a few rows​COMMIT;

That transaction should be short.

No model call.

No external HTTP request.

No waiting for a human.

The distinction I use is:

Text
short local mutation critical section  -> row lock can be excellent​long distributed agent reasoning step  -> durable state + version/CAS + lease/fence

Do not turn a 20-second inference call into a 20-second database lock because the lock happened to be easy to write.

Python version: versioned transition + fence check

The same structure is straightforward in Python.

Python
from dataclasses import dataclass​​class ConcurrencyConflict(Exception):    pass​​class StaleFence(Exception):    pass​​@dataclass(frozen=True)class Lease:    owner: str    fence: int​​@dataclass(frozen=True)class Proposal:    expected_version: int    action: str    args: dict[str, object]​​async def commit_transition(    *,    repository,    run_id: str,    proposal: Proposal,) -> int:    next_version = await repository.compare_and_swap(        run_id=run_id,        expected_version=proposal.expected_version,        next_status="executing",        next_step=proposal.action,    )​    if next_version is None:        raise ConcurrencyConflict(            f"run {run_id} changed after planning"        )​    return next_version

Then keep ownership enforcement in the executor:

Python
async def execute_current_owner(    *,    executor,    run_id: str,    lease: Lease,    workflow_version: int,    idempotency_key: str,    proposal: Proposal,):    # A separate highest_fence() precheck would race a new owner.    # The trusted executor must validate the current lease and fence    # atomically with committing the protected effect.    return await executor.execute_idempotently(        run_id=run_id,        workflow_version=workflow_version,        fence=lease.fence,        idempotency_key=idempotency_key,        action=proposal.action,        args=proposal.args,    )

The model never receives a special exemption from these checks.

Do not promise “exactly once” unless you really mean it

Distributed systems make “exactly once” an overloaded phrase.

A queue may deliver more than once.

A worker may crash after a remote side effect and before checkpointing.

A network timeout may hide whether the remote server committed.

A stale worker may wake after losing its lease.

What I usually want at the business level is closer to:

Text
durable workflow state+ conflict detection+ current ownership+ idempotent side effects+ reconciliation of unknown outcomes= effectively one accepted business transition

That is a more useful engineering target than assuming one process will execute one line of code one time.

The earlier idempotency article covers the ambiguous-success case in detail.

Concurrency control covers the competing-owner case.

You need to know which failure you are fixing.

Test the races deliberately

Concurrency bugs are hard to reproduce accidentally and easy to miss in happy-path evals.

So I inject them.

Failure injectionExpected invariant
Two workers read version 18Only one may commit 18 -> 19
Worker A pauses past lease expiryWorker B may acquire a higher fence
Worker A wakes after B actsA's lower fence is rejected
Same logical action is redeliveredIdempotency produces one side effect
Two different logical actions are proposed from v18Only the winning state transition can proceed
Worker crashes after remote side effectReconciliation recovers without duplicate mutation
Human approves action at v18; run advances to v19Approval is treated as stale until revalidated
Provider failover returns old response lateOld proposal fails version/fence validation
CAS conflict changes relevant evidencePlan is regenerated or revalidated
CAS conflict changes irrelevant metadataRuntime may rebase safely if dependencies still match

The important test is not merely:

Text
Did both workers return success?

It is:

Text
Did exactly one legal state transition become authoritative,and could any stale worker still mutate the outside world?

Add concurrency invariants to trajectory evals

This also belongs in trajectory evaluation.

A correct run trace might contain:

Text
lease acquired fence=42read version=18plan generatedCAS 18->19 succeededfence=42 validatedside effect K executedcheckpoint version=20

A bad trace might contain:

Text
lease fence=41 expirednew lease fence=42 acquiredworker 42 commits version=19worker 41 wakesworker 41 executes action anyway

The final system state might even look healthy after compensation.

The trajectory is still invalid because a stale owner crossed the mutation boundary.

I would add deterministic trace rules such as:

Text
MUST:state_commit.expected_version == prior_read.version​MUST:side_effect.fence >= latest_accepted_fence​MUST:consequential_action follows successful state transition​MUST NOT:execute after lease loss without reacquisition

These are much better as deterministic invariants than as an LLM judge guessing whether the trace “looks safe.”

Metrics I want in production

Concurrency correctness needs observability too.

I track:

Text
CAS conflict rateCAS conflicts by workflow stepconflict replan rateconflict replan success ratelease acquisition conflictslease renewal failureslease age at completionstale-fence rejection countqueue redelivery countduplicate delivery rateduplicate side-effect rateunknown-outcome reconciliation raterow-lock wait timeplan-to-commit latencystuck-run countstate-transition invariant violations

A rising CAS-conflict rate can mean legitimate load growth.

It can also mean your lease duration is too short, one workflow step is too slow, or multiple schedulers are accidentally targeting the same run.

A stale-fence rejection is not always a bug.

It can be proof that the safety mechanism caught the bug before the side effect.

What should be near zero is:

Text
stale-fence action accepted

and:

Text
duplicate consequential side effect

Which primitive should I use?

I use a simple decision table.

ProblemPrimitive
Two writers may update the same state, conflicts are uncommonVersion / compare-and-swap
A short DB critical section must be serializedRow lock / transaction
A distributed worker needs temporary ownershipLease
An expired owner may wake and still actFencing token
The same logical mutation may be retriedIdempotency key
Remote outcome is ambiguous after timeoutReconciliation
Events for one entity must preserve orderPartition/session key or per-entity sequencing

Sometimes one workflow needs several rows from this table.

That is normal.

The mistake is treating them as interchangeable because all of them “stop duplicates.”

They stop different kinds of duplicates and races.

Do not serialize the whole platform just to feel safe

The opposite failure mode is over-locking.

You can eliminate many races by saying:

Text
only one agent worker may run at a time

You can also eliminate highway collisions by allowing one car onto the road at a time.

The design goal is narrower serialization.

For example:

Text
parallel across tenantsparallel across independent runsparallel across independent steps where state partitions do not overlapserialized only for transitions of the same protected entity

Azure's current Sequential Convoy guidance makes a related point: when order matters for one category/entity, preserve ordering within that group instead of collapsing the entire system to one global consumer.

Partition the coordination boundary around the actual invariant.

If the invariant is “one authoritative next transition per run,” lock or version the run.

Do not globally lock every agent in the cluster.

The production rule I would keep

The concurrency architecture can be summarized without mentioning any LLM framework:

Text
read versioned stateacquire bounded ownershipperform slow planning without holding DB lockscommit with compare-and-swapreject stale versionsissue monotonic fencing tokens when ownership can expirevalidate the fence at the mutation boundarymake side effects idempotentreconcile ambiguous outcomesbind human approvals to exact state/action versionstrace every conflict and ownership change

The model can produce an excellent plan and still be too late.

That is the subtle shift.

For a normal chatbot, a late answer is mostly a latency problem.

For an action-taking durable agent, a late answer can be a stale command from a worker that no longer owns reality.

Do not ask the model whether it is still current. Make the runtime prove it.

References

KEEP READING

Related engineering notes