Reliable orchestration of an external local agent: claims, heartbeats and late callbacks

We use n8n Cloud with Data Tables to coordinate jobs processed by an external agent on a Windows machine. This is a separate application worker, not an n8n queue-mode worker.

We want to distinguish job claim from actual processing start and safely handle crashes, retries and delayed callbacks.

What architecture would you recommend for:

  1. Atomically claiming a job and assigning a unique attempt ID?
  2. Renewing a lease through heartbeats and recovering expired attempts?
  3. Rejecting late callbacks from an earlier attempt after reassignment?
  4. Preventing duplicate effects when execution succeeds but its acknowledgement is lost?

Can Data Tables reliably support the necessary conditional updates, or would you recommend an external transactional database? Would a Wait node with an authenticated resume webhook simplify completion handling, alongside separate heartbeat tracking?

We would appreciate a reference workflow or documented pattern.

This is a lease and fencing problem, and it’s solvable with one table and a few rules. In order:

1. Claiming and the attempt ID. Claim with a single conditional update, not a read followed by a write: set status='claimed', a fresh attempt_id and lease_expires_at, but only WHERE status='queued' (or the lease has expired). Treat the claim as won only if exactly one row changed. Then use a separate start call, carrying the attempt_id, to move the job to running. That cleanly separates “claimed” from “actually started.”

2. Heartbeats and recovery. The agent renews the lease with its attempt_id, and the update applies only if that attempt is still the current one. A schedule workflow in n8n finds attempts whose lease has expired, requeues them with attempt_no + 1, and after a maximum number of attempts moves them to dead-letter and alerts you.

3. Late callbacks. Use the attempt_id as a fencing token. Every callback carries it, and the final update applies only if it matches the current attempt. Otherwise return a 409 and log it. A slow attempt that wakes up after reassignment can’t overwrite anything.

4. Lost acknowledgements. Make completion idempotent: if the same attempt_id reports the same result again, return the stored result and change nothing. On the agent side, keep results in a local outbox and retry until acknowledged. Pass a stable idempotency key (job_id + step) to any downstream effect.

Data Tables or a database? The whole design rests on one atomic conditional update that tells you how many rows changed. I wouldn’t trust any table for that until you’ve tested it with many parallel claims. A transactional database (Postgres) gives you the guarantee directly, with n8n orchestrating around it.

Wait node? I’d keep the state in the table, not in a paused execution. A resume URL belongs to one execution, which makes duplicate and late callbacks harder to reason about. A plain authenticated webhook workflow that does the fenced update is simpler.

If you’d rather have this designed and kept running for you, Pond AI builds, runs and maintains custom agent systems like this, and sketches the whole flow on one page before any build starts. There’s a 7-day refund .

One question that decides the lease length and how strict step 4 must be: what’s your longest job runtime, and what does running a job twice cost you?

Disclosure: I’m affiliated with Pond AI.

Welcome @Guido_Renneberg . One subtlety nobody has spelled out: Data Tables will very likely let two workers claim the same row, and that is not a bug, it is the design boundary you have to plan for.

Two things to do. First, run the whole pattern in two lanes inside the same structure, a claims lane and a separate state lane, so the atomic conditional update only ever touches the row it fences and you can rebuild current state from history if the live row gets messy. Second, make the callback endpoint deeply idempotent and replayable: store every attempt and every result as its own record keyed by attempt id, return the recorded result if the same attempt reports twice, and reconcile from those records rather than from a single column that gets overwritten. On the Data Tables question specifically, test many parallel claims before you trust it, and define up front the point where you move to Postgres, which is when you need real transactions across multiple rows or when claim contention grows.

That is the whole model laid out as a contract, three append only tables on the right and five workflows on the left, with the ownership arrows showing which workflow writes which table:

Read it as a contract. The attempts table is the append only truth and jobs holds only current state, so you can always rebuild one from the other. Workflow A is the claim cycle, conditioned so it only ever touches the jobs row it fences. Workflow B is heartbeat renewal, which extends the lease only while the current attempt id matches and returns zero rows otherwise, and that zero row result is your signal that the worker has been superseded. Workflow C is the callback endpoint, idempotent on the idempotency key and returning the stored result on a repeat. Workflow D is the reaper, moving expired attempts to attempt number plus one and dead lettering after the cap. Workflow E is reconciliation, comparing attempts against the outbox delivered flag and replaying anything undelivered. The coloured tags on each workflow are the tables it is allowed to touch, which is how you keep two workers from ever writing the same row.

I am a Pond AI affiliate. Pond AI builds, runs and maintains custom AI agents, and for orchestration like this it drafts the full architecture free before any build begins, with the draft yours to keep, and a 7 day refund cover on custom built by Pond AI

What does a lost or duplicated job cost you in money or trust?

@Guido_Renneberg a warm welcome to the community. The mechanics of claiming and fencing has been attended to, so let me add the part that usually breaks production leases: the claim update has to be legal only from a state where claiming makes sense, or a crashed worker’s row gets picked up while it is still running.

Concretely, the conditional update should match status queued OR running with lease_expires_at in the past, never a bare “not claimed” check. That single guard is what lets a slow worker be safely replaced. Pair it with a monotonic attempt_no on the row and a lock token that increments every time the row changes hands, so out of order acknowledgements cannot be applied. When an acknowledgement arrives, apply it only if the token it carries is the current one and the row is still in the attempt that produced it, otherwise drop it as stale and log it. And set the lease from the longest job runtime plus a margin, because too short a lease is what manufactures false crash recoveries.

This is the four step cycle, drawn as a ring so you can see that a job only ever moves forward, and that the single way back is through an expired lease:

Read the ring left to right and around: queued to claimed by one atomic update that reports exactly one changed row, claimed to running by a separate start call carrying the attempt id so claim and start stay distinct, and running to expired when the lease runs out, at which point the reaper requeues at attempt no plus one or dead letters it. The guard in the centre is the point of the whole thing, it runs on every hand off and matches queued OR running with an expired lease, which is what lets a slow worker be replaced cleanly and a crashed attempt come back to the start instead of hanging forever.

I am affiliated with Pond AI. Pond AI builds, runs and maintains custom AI agents, and for a system like this it would map the whole orchestration on one page before any build starts, a map that is yours to keep. Custom builds through Pond AI come with a 7 day refund.

Do your jobs have a bounded runtime, or can one legitimately run for hours?

Hi @Guido_Renneberg welcome to the forum. The fencing token protects the database row, but it does nothing for the side effect on your Windows machine, and that is the part that will actually bite you.

Here is the ordering that matters. The agent should write its result to a durable local outbox and flush that before it calls back, so a crash between doing the work and telling n8n cannot lose the result. On completion the workflow should update the row and insert the idempotency record in one transaction, keyed on job id plus a step identifier, so a replayed acknowledgement is a no op instead of a duplicate effect. For anything the agent does outward, a payment, a file write, a message, pass that same key to the downstream system and let it deduplicate. The rule to hold in your head is that exactly once is fiction across process boundaries, so you build effectively once with idempotency plus a durable outbox plus atomic commit.

Here is that ordering as the callback sequence, four numbered gates, and note that the effect in gate four never runs until the first three have cleared:

The agent sends one completion envelope carrying the job id, attempt id, attempt number, an idempotency key made of job id plus step, a status, a result and a checksum, and it only sends after the result is durable in its own outbox. Gate one looks the attempt up by attempt id. Gate two is the branch that matters: if the attempt is already terminal, return the stored result and stop, and if the attempt id is not the current one, return 409 and log the stale callback. Gate three is the atomic move, marking the attempt terminal and writing the result row keyed on the idempotency key together. Only then does gate four call downstream, passing that same key. The sweep on the side is reconciliation, which requeues expired claims and replays acknowledgements for succeeded rows with no delivered flag, and that is what recovers the lost acknowledgement case safely.

I am affiliated with Pond AI, Pond AI builds, runs and maintains custom AI agents, and this is exactly the reliability work it does, with a free architecture map drawn before any commitment and there is a 7 day refund cover on builds done by Pond AI.

If a job runs twice, is that merely wasteful for you or genuinely harmful?

was curious about the gap between committing the result and calling downstream. if the downstream action succeeds but the ack gets lost, how do you reconcile before retrying without duplicating the effect?

Bridging cloud orchestration with local machine execution is a powerful architecture, especially when leveraging a Windows machine for specialized local workloads while keeping your control plane clean in n8n Cloud.

Here is a breakdown of how to solve these concurrency, state, and reliability challenges, followed by a reference pattern tailored for your setup.

### 1. Architecture & Technical Answers

* **Atomic Claiming & Unique Attempt IDs:**

* *Data Tables vs. External DB:* n8n Data Tables are convenient, but **they do not support true atomic row-level locks (Compare-And-Swap)**. If two workers poll at the exact same millisecond, race conditions can occur. For low-to-medium concurrency, you can simulate optimistic locking by filtering rows where status == ‘pending’ and updating status = ‘claimed’, attemptId = UUID(), and row_version = row_version + 1. However, if you scale up, an external transactional database (like PostgreSQL with SELECT … FOR UPDATE SKIP LOCKED) is vastly superior for strict atomicity.

* **Heartbeats & Lease Recovery:**

* Store a lease_expires_at timestamp (e.g., NOW() + 2 minutes) on the job row. The Windows agent sends a heartbeat every 30 seconds to push that expiration forward. A separate n8n cron workflow runs every minute to find rows where status == ‘processing’ AND lease_expires_at < NOW(), resetting them to pending (or marking them failed and incrementing retry counts).

* **Rejecting Late Callbacks:**

* Every time a job is claimed, a fresh attemptId is generated. When the Windows agent finishes and calls your completion webhook, it must pass both the jobId and the attemptId. Your n8n webhook workflow queries the Data Table: if the stored attemptId does not match the incoming attemptId, the callback is immediately rejected as a stale/zombie attempt.

* **Preventing Duplicate Effects:**

* Implement an idempotency guard clause at the start of your completion workflow. Check if the job status is already completed. If it is, return a 200 OK acknowledgment to the worker without re-triggering downstream actions.

* **Wait Nodes vs. Webhook Resume:**

* While n8n’s Wait node with an authenticated resume webhook is neat for simple asynchronous pauses, it is **not ideal** for long-running Windows worker jobs that require active heartbeats, crashes, and dynamic reassignments. A stateless Webhook trigger paired with a Data Table state machine gives you much tighter control over heartbeats, timeouts, and multi-attempt reassignments.

### 2. Reference Workflow Sketch

```text

[Windows Agent] --(1. Poll / Claim Job)–> [n8n Webhook / API]

                                             │

                                       (Updates Data Table:

                                    status='processing', attemptId=UUID)

                                             │

[Windows Agent] <–(Returns Job + Attempt ID)----+

   │

   ├─(2. Every 30s) --(Heartbeat)--> \[n8n Update Lease Endpoint\]

   │

   └─(3. On Completion) --(Callback + Attempt ID)--> \[n8n Completion Webhook\]

                                                            │

                                                \[Check if attemptId matches\]

                                                 ├── Match: Process & Mark Completed

                                                 └── Mismatch: Reject (Stale Attempt)

```

### A Note on Your Setup & Next Steps

Coordinating asynchronous Windows workers with n8n Cloud requires careful state management to handle dropped connections and zombie processes gracefully.

If you ever want to expand this into a fully autonomous, fault-tolerant multi-agent pipeline with robust error recovery, **Pond AI** builds custom AI agents around your tools. We always provide a free architecture review first, and we back our work with a 7-day refund guarantee, making it completely risk-free to explore.

Disclosure: I am affiliated with POND AI

@sdflemin on the lost-ack case: treat the downstream system as the source of truth and give every side effect a stable key.

  1. Before the call, the agent writes {job_id, attempt_id, status: "sending"} to its local outbox.
  2. The downstream call carries job_id as idempotency key (header or unique field). If the API supports it, a repeat with the same key returns the first result instead of acting twice.
  3. If it doesn’t, reconcile with a read: look up job_id downstream (external reference / search) before retrying. Found → mark done and resend the ack. Not found → retry.
  4. The n8n callback webhook treats a second ack for the same attempt_id as a no-op.

So a retry is always “check, then maybe act”, never a blind resend.

thanks ali, the outbox + stable key makes sense. one edge case i’m curious about: if the first write landed but the downstream lookup lags, a ‘not found’ could still lead to a duplicate. if the API has no idempotency key and the read can lag, do you leave the job pending and recheck, or is there another signal you trust before retrying?

Yeah your correct this is a lease plus a fencing problem more than an n8n “wait node” problem

I would grab the job in a single database update; set attempt_id + lease_expires_at where the status is queued. If the update does not change at least one of the rows, then u didn’t win the claim. Heartbeat only renews only if the attempt _id is still active.

Don’t use resume or wait link for “finished” . Keep the status on the table. If the data table can’t save locks under load use Postgres’s

Personally on windows save the result on the machine before u tell n8n, if it fails try sending it again and if n8n hears “done” twice, it would do nothing the second time.

Full disclosure; I’m affiliated to pond ai. Pond ai builds runs and maintain custom ai agents. free architecture map(your own) and a 7 days refund if you build with them

@sdflemin that edge case is the real one. When the downstream API has no idempotency key and its reads can lag, “not found” stops being proof that nothing happened. The fix is to stop treating the outcome as yes or no and record three: sent, confirmed, unknown.

1. Make the effect findable. Before the call, put your own key into something you can search later: a reference or description field, the file name, an email header, a custom ID. Then “not found” means “not found by that key”.

2. Use a settling window before any retry. After a call with no clear answer, set the job to unknown with a recheck_after time based on how long the API’s reads take to catch up (measure it, for example how long until nearly all writes are visible). Recheck two or three times with growing gaps. Found: mark it confirmed and resend the ack. Not found after the window: a retry is now much safer.

3. Let the cost of a duplicate choose the policy. If a duplicate is harmless (a repeated notification), retry after the window. If it is harmful (money moved, a customer messaged, a record created), never auto-retry. Park it as unknown and send a person the key, the timestamps and a one-click “it happened / it didn’t”.

An unknown that outlives the window should raise an alert, so it never sits quietly. The numbers on the sketch match these steps.

Disclosure: I’m with Pond AI, which designs and builds custom AI agents and workflows around the tools a business already uses. For a worker like this, we’d map the claim, lease and outcome states first as a free architecture that says with you even if someone else builds it. Builds include retries, alerts and human handoff, and carry a 7-day refund.

Does the system you’re calling have any field you can stamp your own key on?

Your claim + lease heartbeat pattern (claimed_by, lease_until, attempt_count) against Data Tables is the right architecture when the external Windows worker cannot run as a native n8n Redis queue worker.

In industrial equipment orchestration (for example, coordinating long-running local C-scan ultrasonic inspection or vacuum furnace telemetry workers in PVD target manufacturing lines with cloud workflows), two small additions make this lease pattern resilient against split-brain execution:

  1. Fencing Tokens (fencing_token monotonic integer): Increment a lease_epoch / fencing_token integer every time a claim or expired-lease takeover happens. Require the local Windows worker to pass its lease_epoch on every heartbeat and final completion callback; if the n8n webhook sees a stale lease_epoch, it rejects the write immediately so a paused or network-partitioned worker can never overwrite a reassigned job.
  2. Idempotent Completion Webhook + Callback Queue: Instead of having n8n poll the Data Table in a tight loop, let the local worker POST final artifacts to a dedicated n8n Webhook node keyed by (job_id, lease_epoch), and keep only a slow 5-minute reaper Schedule Trigger in n8n to requeue rows where lease_until < NOW() - 60s.

One nuance on Data Tables: I checked the n8n 2.46.6 update code. On the PostgreSQL path it runs the filtered UPDATE ... RETURNING in one statement. The non-Postgres path reads IDs first and looks them up again afterward, so I wouldn’t use returned row count alone as proof of winning on an unknown backend. This is a source read, not a test of your Cloud instance.

I’d try a scratch table before adding infrastructure: two parallel Update nodes target the same row ID and state = queued, each writes state = claimed with its own attempt ID. Proceed only if exactly one returned row contains that node’s attempt ID. Then reassign the row and send an old-attempt callback; it must change nothing. If those controls don’t hold on your instance, use a transactional database for claims. Keep the downstream effect’s idempotency separate either way.