How to Prevent Lost Updates in Automation Workflows
Prevent lost updates in automation workflows: reproduce a stale overwrite in PostgreSQL, then fix it with a version check, row lock or atomic update.
Guide by the Otomatzia editorial team · source content checked on

Both runs succeeded, so why did one change disappear?
To prevent lost updates in automation workflows, put the guard inside the write itself: let one statement derive the new value from the current row, make the update conditional on the version the run actually read, or lock the row before a dependent change. Two runs can both report success and still lose a change, because the later write silently replaces the earlier one.
A self-reported operator account describes that exact shape: two n8n workflows updated one customer record, both reported success, and one contact change disappeared. DEV Community n8n operator account, accessed November 2026 It is one operator's account of one case. It does not show how common the problem is.
The mechanism is simple. Each run reads the record, prepares a replacement outside the database and writes it back. Read Committed is PostgreSQL's default isolation level, and each plain SELECT sees a snapshot as of the start of that query. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 Nothing in that read reserves the row, so a second run can read the same state before the first one writes. Each write is valid on its own, which is why no error marks the lost change.
This guide covers one failure only: stale replacement of an existing mutable value. The controls are PostgreSQL controls, rehearsed for this guide on PostgreSQL 18.7 with synthetic rows. Duplicate creation, per-key queues, advisory locks, ETags and other database engines are outside its scope.
By the end you can reproduce a stale overwrite with synthetic data, choose between an atomic update, a version check and a row lock, and prove three intended effects. Ten atomic increments leave the counter at 10. A version check of a stale write changes zero rows and leaves `worker-a` at version 2. The worker that waited for the row lock reads counter 1 before writing 2.
You need a workflow that reads an existing record and later writes it back. For the full rehearsal script you need Bash and Docker, with permission to pull `postgres:18.7` and to create and remove one disposable container. To run the SQL steps by hand in two sessions instead, you need a disposable PostgreSQL 18 database and `psql`, with synthetic rows only. Node.js is needed only if you choose to run the optional retry budget fixture near the end.
Is this a lost update, a duplicate or a double claim?
Name the failure before you choose a control. The three cases below can look alike in an execution log, yet each needs a different fix, and a control built for one does nothing for the others. Concurrent deletion is a fourth case and is outside this guide.
Stale replacement of an existing value
A lost update happens when two workers read the same existing record state, each derives a replacement, and the later write overwrites the earlier one. The row count does not change. One value is simply gone, and both executions look healthy.
The fix belongs in the write. When an UPDATE at Read Committed finds a row changed by another transaction, PostgreSQL waits if needed and then reevaluates the WHERE condition against the updated row version. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 An UPDATE can report whether it changed a row through its command count, and RETURNING exposes values from rows actually updated. PostgreSQL and UPDATE, accessed November 2026 Those two behaviors are what the atomic update and the version check in this guide are built on.
Duplicate delivery or duplicate creation
Duplicate creation happens when concurrent paths create more than one row or object for one logical event. The symptom is an extra record, not a missing value. It needs uniqueness and idempotency controls, which the guide to avoiding duplicate records covers.
Keep the two apart when you diagnose. A version column does not stop a second insert for the same event. A unique key does not stop a stale overwrite of a row that already exists.
Two requests claiming one resource
A claim answers a different question: which worker owns this piece of work right now. At Tiger Media we built a PostgreSQL notification worker that claims one due row in a single statement, using a row lock with skip-locked selection, and assigns a lease token. Every later state transition is permitted only while that token still owns the row. In a PostgreSQL integration test on synthetic records, two workers started together against 21 due jobs and all 21 finished in the sent state.
We apply the same rule in a lead routing workflow. The mutable route row is claimed under a database row lock, and its progress, retry and completion updates all include the current lease token. A zero-row update is treated as lost ownership and goes to an explicit error path instead of writing stale state. After deployment, that lead routing workflow was verified with a synthetic lead.
A lease token proves ownership. It does not prove that the value a worker is about to write was computed from the current row. That is the stale replacement problem, and the rest of this guide stays with it.
Reproduce a stale overwrite with synthetic data
Reproduce the failure on a throwaway table before you apply any fix. The rehearsal script at the end of this section ran for this guide on PostgreSQL 18.7 with Docker version 29.9.3. Later sections reuse the same harness for the three fixes, so one run produces every result quoted in this guide.
Before you save the script, create a new empty directory and save it there as `run-concurrency-rehearsal.sh`, the only file in that directory. The script overwrites named log files beside itself, and its printed output includes every file in that directory that matches `increment-*.log`. A stray file with a matching name would be overwritten or mixed into the evidence.
The script needs access to the Docker daemon. It starts one uniquely named disposable container from `postgres:18.7`, creates the table inside it and inserts one synthetic row. It does not connect to an existing database, and it coordinates the workers with temporary barrier files. Run it from that directory with `bash run-concurrency-rehearsal.sh`.
The script stops at the first failed assertion. Its EXIT trap still runs in that case and removes its own container, together with that container's anonymous PostgreSQL volume, through `docker rm -fv`. It also deletes the temporary barrier directory. The evidence logs stay beside the script.
In the naive race, both workers read row 42 and record `draft` at version 1 before either one writes. Their fixed replacement titles, `worker-a` and `worker-b`, are stand-ins for edits that each worker prepared against version 1. Worker B writes first. Worker A's unguarded write then also succeeds and leaves only `worker-a`.
The recorded output shows it line by line. Both logs carry the same read, `worker-a-read=draft|v1` and `worker-b-read=draft|v1`. Both writes report `UPDATE 1`. The final line is `naive-final=worker-a|v1`, and the script subsequently asserts both recorded reads, both `UPDATE 1` results and that final value. The version is still 1 because an unguarded write does not advance it. That is a workflow race condition in its smallest form: no error, no warning and one edit gone.
One note on reading the output. The printed increment logs follow the filename order the shell uses when it sorts them, not execution order, so `increment-10` prints beside `increment-1` instead of after `increment-9`. In the recorded run it printed first, followed by 1 through 9. The counter value each increment returned shows the order in which the increments took effect.
If you use a separate disposable PostgreSQL 18 test copy instead of the script, first create `mutable_records` and insert row 42 exactly as the script does. Before each proof, reset `title` to `draft`, `counter` to 0 and `version` to 1. The naive race and the row-lock proof use two `psql` sessions. The version check stays in one sequential session, and before the atomic proof you reset `counter` to 0.
To run the naive race by hand, read row 42 in Session A and again in Session B. Run the unguarded title update in Session B, then run it in Session A with the other title. Compare the stored row with what each session read. The table summarizes the sequence the script enforces.
Three consecutive readiness checks survive the image initialization restart. A unique disposable container is created and only that container is removed. Both synthetic workers record the same initial row before a barrier releases either write. Worker B commits first. Every PID is checked, and the expected outputs are asserted.
| Moment | Worker A | Worker B | Stored title and version |
|---|---|---|---|
| Both read | Records draft at version 1 | Records draft at version 1 | draft, version 1 |
| Barrier releases | Waits for worker B's write marker | Runs its unguarded update and gets UPDATE 1 | worker-b, version 1 |
| Late write | Runs its unguarded update and gets UPDATE 1 | Has already finished | worker-a, version 1 |
| Final read | Its edit is stored | Its edit is gone and no error was raised | worker-a, version 1 |
#!/usr/bin/env bash
set -euo pipefail
container_name="otomatzia-lost-update-$$"
evidence_dir="$(cd "$(dirname "$0")" && pwd)"
runtime_dir="$(mktemp -d -t otomatzia-lost-update-XXXXXX)"
container_created=0
cleanup() {
if [[ "$container_created" -eq 1 ]]; then
docker rm -fv "$container_name" >/dev/null 2>&1 || true
fi
rm -rf "$runtime_dir"
}
trap cleanup EXIT
docker run -d --name "$container_name" -e POSTGRES_PASSWORD=synthetic -e POSTGRES_DB=rehearsal postgres:18.7 >/dev/null
container_created=1
ready_streak=0
for _ in $(seq 1 60); do
if docker exec "$container_name" pg_isready -U postgres -d rehearsal >/dev/null 2>&1; then
ready_streak=$((ready_streak + 1))
if [[ "$ready_streak" -ge 3 ]]; then
break
fi
else
ready_streak=0
fi
sleep 1
done
[[ "$ready_streak" -ge 3 ]]
docker exec "$container_name" pg_isready -U postgres -d rehearsal >/dev/null
docker exec -i "$container_name" psql -X -v ON_ERROR_STOP=1 -U postgres -d rehearsal <<'SQL'
CREATE TABLE mutable_records (
id integer PRIMARY KEY,
title text NOT NULL,
counter integer NOT NULL DEFAULT 0,
version integer NOT NULL DEFAULT 1
);
INSERT INTO mutable_records (id, title) VALUES (42, 'draft');
SQL
run_naive_worker() {
local worker_name="$1"
local replacement="$2"
local after_barrier_delay="$3"
local log_path="$evidence_dir/$worker_name-naive.log"
local observed
observed="$(docker exec "$container_name" psql -X -v ON_ERROR_STOP=1 -At -U postgres -d rehearsal \
-c "SELECT title || '|v' || version FROM mutable_records WHERE id = 42")"
printf '%s-read=%s\n' "$worker_name" "$observed" >"$log_path"
: >"$runtime_dir/$worker_name.ready"
for _ in $(seq 1 100); do
if [[ -f "$runtime_dir/worker-a.ready" && -f "$runtime_dir/worker-b.ready" ]]; then
break
fi
sleep 0.05
done
[[ -f "$runtime_dir/worker-a.ready" && -f "$runtime_dir/worker-b.ready" ]]
if [[ "$worker_name" == "worker-a" ]]; then
for _ in $(seq 1 100); do
[[ -f "$runtime_dir/worker-b.wrote" ]] && break
sleep 0.05
done
[[ -f "$runtime_dir/worker-b.wrote" ]]
else
sleep "$after_barrier_delay"
fi
docker exec "$container_name" psql -X -v ON_ERROR_STOP=1 -At -U postgres -d rehearsal \
-c "UPDATE mutable_records SET title = '$replacement' WHERE id = 42 RETURNING '$worker_name-write=' || title" \
>>"$log_path"
: >"$runtime_dir/$worker_name.wrote"
}
run_naive_worker worker-a worker-a 0.00 &
pid_a=$!
run_naive_worker worker-b worker-b 0.00 &
pid_b=$!
status_a=0
status_b=0
wait "$pid_a" || status_a=$?
wait "$pid_b" || status_b=$?
[[ "$status_a" -eq 0 && "$status_b" -eq 0 ]]
docker exec "$container_name" psql -X -At -U postgres -d rehearsal \
-c "SELECT 'naive-final=' || title || '|v' || version FROM mutable_records WHERE id = 42" \
>"$evidence_dir/naive-final.log"
docker exec "$container_name" psql -X -v ON_ERROR_STOP=1 -U postgres -d rehearsal \
-c "UPDATE mutable_records SET title = 'draft', counter = 0, version = 1 WHERE id = 42" >/dev/null
(docker exec -e PGAPPNAME=worker_a_locked -i "$container_name" psql -X -v ON_ERROR_STOP=1 -At -U postgres -d rehearsal <<'SQL'
BEGIN;
SELECT counter AS locked_counter FROM mutable_records WHERE id = 42 FOR UPDATE \gset
\echo worker-a-locked-read=:locked_counter
SELECT pg_sleep(2.0);
UPDATE mutable_records SET counter = :locked_counter + 1, title = 'worker-a-from-current' WHERE id = 42 RETURNING 'worker-a-write=' || counter;
COMMIT;
SQL
) >"$evidence_dir/worker-a-locked.log" &
pid_a=$!
for _ in $(seq 1 100); do
lock_holder="$(docker exec "$container_name" psql -X -At -U postgres -d rehearsal -c "SELECT count(*) FROM pg_stat_activity WHERE application_name = 'worker_a_locked' AND state = 'active' AND query LIKE 'SELECT pg_sleep%'")"
[[ "$lock_holder" == "1" ]] && break
sleep 0.05
done
[[ "$lock_holder" == "1" ]]
(docker exec -e PGAPPNAME=worker_b_locked -i "$container_name" psql -X -v ON_ERROR_STOP=1 -At -U postgres -d rehearsal <<'SQL'
BEGIN;
SELECT counter AS locked_counter FROM mutable_records WHERE id = 42 FOR UPDATE \gset
\echo worker-b-locked-read=:locked_counter
UPDATE mutable_records SET counter = :locked_counter + 1, title = 'worker-b-from-current' WHERE id = 42 RETURNING 'worker-b-write=' || counter;
COMMIT;
SQL
) >"$evidence_dir/worker-b-locked.log" &
pid_b=$!
for _ in $(seq 1 100); do
lock_waiter="$(docker exec "$container_name" psql -X -At -U postgres -d rehearsal -c "SELECT count(*) FROM pg_stat_activity WHERE application_name = 'worker_b_locked' AND wait_event_type = 'Lock'")"
[[ "$lock_waiter" == "1" ]] && break
sleep 0.05
done
[[ "$lock_waiter" == "1" ]]
status_a=0
status_b=0
wait "$pid_a" || status_a=$?
wait "$pid_b" || status_b=$?
[[ "$status_a" -eq 0 && "$status_b" -eq 0 ]]
docker exec "$container_name" psql -X -At -U postgres -d rehearsal \
-c "SELECT 'locked-final=' || title || '|counter=' || counter FROM mutable_records WHERE id = 42" \
>"$evidence_dir/locked-final.log"
docker exec "$container_name" psql -X -v ON_ERROR_STOP=1 -U postgres -d rehearsal \
-c "UPDATE mutable_records SET title = 'draft', counter = 0, version = 1 WHERE id = 42" >/dev/null
docker exec "$container_name" psql -X -At -U postgres -d rehearsal \
-c "UPDATE mutable_records SET title = 'worker-a', version = version + 1 WHERE id = 42 AND version = 1 RETURNING 'optimistic-a=' || title || '|v' || version" \
>"$evidence_dir/optimistic-a.log"
docker exec "$container_name" psql -X -At -U postgres -d rehearsal \
-c "UPDATE mutable_records SET title = 'worker-b', version = version + 1 WHERE id = 42 AND version = 1 RETURNING 'optimistic-b=' || title || '|v' || version" \
>"$evidence_dir/optimistic-b.log"
docker exec "$container_name" psql -X -At -U postgres -d rehearsal \
-c "SELECT 'optimistic-final=' || title || '|v' || version FROM mutable_records WHERE id = 42" \
>"$evidence_dir/optimistic-final.log"
docker exec "$container_name" psql -X -v ON_ERROR_STOP=1 -U postgres -d rehearsal \
-c "UPDATE mutable_records SET counter = 0 WHERE id = 42" >/dev/null
increment_pids=()
for worker_number in $(seq 1 10); do
docker exec "$container_name" psql -X -At -U postgres -d rehearsal \
-c "UPDATE mutable_records SET counter = counter + 1 WHERE id = 42 RETURNING 'increment-$worker_number=' || counter" \
>"$evidence_dir/increment-$worker_number.log" &
increment_pids+=("$!")
done
for increment_pid in "${increment_pids[@]}"; do
wait "$increment_pid"
done
docker exec "$container_name" psql -X -At -U postgres -d rehearsal \
-c "SELECT 'increments-final=' || counter FROM mutable_records WHERE id = 42" \
>"$evidence_dir/increments-final.log"
{
echo "postgres=$(docker exec "$container_name" postgres --version)"
echo "docker=$(docker --version)"
cat "$evidence_dir/worker-a-naive.log"
cat "$evidence_dir/worker-b-naive.log"
cat "$evidence_dir/naive-final.log"
cat "$evidence_dir/worker-a-locked.log"
cat "$evidence_dir/worker-b-locked.log"
cat "$evidence_dir/locked-final.log"
cat "$evidence_dir/optimistic-a.log"
cat "$evidence_dir/optimistic-b.log"
cat "$evidence_dir/optimistic-final.log"
cat "$evidence_dir"/increment-*.log
cat "$evidence_dir/increments-final.log"
} >"$evidence_dir/concurrency-rehearsal.log"
grep -Fx 'worker-a-read=draft|v1' "$evidence_dir/worker-a-naive.log" >/dev/null
grep -Fx 'worker-b-read=draft|v1' "$evidence_dir/worker-b-naive.log" >/dev/null
grep -Fx 'UPDATE 1' "$evidence_dir/worker-a-naive.log" >/dev/null
grep -Fx 'UPDATE 1' "$evidence_dir/worker-b-naive.log" >/dev/null
grep -Fx 'naive-final=worker-a|v1' "$evidence_dir/naive-final.log" >/dev/null
grep -Fx 'worker-a-locked-read=0' "$evidence_dir/worker-a-locked.log" >/dev/null
grep -Fx 'worker-b-locked-read=1' "$evidence_dir/worker-b-locked.log" >/dev/null
grep -Fx 'worker-b-write=2' "$evidence_dir/worker-b-locked.log" >/dev/null
grep -Fx 'locked-final=worker-b-from-current|counter=2' "$evidence_dir/locked-final.log" >/dev/null
grep -Fx 'optimistic-a=worker-a|v2' "$evidence_dir/optimistic-a.log" >/dev/null
grep -Fx 'UPDATE 0' "$evidence_dir/optimistic-b.log" >/dev/null
grep -Fx 'optimistic-final=worker-a|v2' "$evidence_dir/optimistic-final.log" >/dev/null
grep -Fx 'increments-final=10' "$evidence_dir/increments-final.log" >/dev/null
cat "$evidence_dir/concurrency-rehearsal.log"

Why a version check in an earlier node still races
A workflow built as a read node, a comparison node and an update node checks the version at one moment and writes at another. The check can pass and be out of date by the time the write runs. Moving the comparison closer to the write narrows the gap without closing it.
The gap between check and write
In the rehearsal, both workers recorded version 1. A comparison node placed after each read would have passed for both of them, because each compared against a value that was correct when it was read. Both would then have gone on to write.
The read cannot hold the row for the write. PostgreSQL row locks affect writers and lockers of the same row, not ordinary reads, and are normally held until the transaction ends. PostgreSQL and 13.3. Explicit Locking, accessed November 2026 Each plain SELECT sees a snapshot as of the start of that query. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 A plain SELECT therefore takes no row lock, and what it returns is a past observation by the time the next node runs.
A separate demonstration on SQL Server makes the same point for that platform. It shows that checking a version separately from an unguarded write leaves a race; the version condition must protect the write itself and a rejected write must be detected. Redgate concurrency demonstration, accessed November 2026 That article was written for SQL Server and was not rerun for this guide.
What a Read Committed transaction around an unguarded update cannot fix
Wrapping the read and an unguarded UPDATE in one transaction at Read Committed does not close the gap. The plain SELECT inside the transaction still takes no row lock. When the UPDATE finds a row changed by another transaction, PostgreSQL waits if needed and then reevaluates the WHERE condition against the updated row version. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026
That recheck helps only when the condition carries the guard. An unguarded condition on the key alone still matches the changed row, so the stale replacement is applied on top of the newer value. A transaction around only the final UPDATE has the same limit: it cannot repair a value that was read before the transaction began.
Put the version the run read into the WHERE clause and the same recheck works for you: the changed row no longer matches and the update changes zero rows. This is why the guard must sit inside the write statement and not in an earlier node.
Repeatable Read behaves differently. It can reject an update when the target row changed after the transaction began, and the application must retry the entire transaction. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 The control comparison later in this guide places that option beside the three fixes.
Fix one: let a single statement derive the new value
This is the smallest fix, and it applies when the change can be written as an expression of the current row. A counter increment is the tested example. The workflow sends no value it read earlier, so there is no stale replacement to write back.
It works because of the documented update behavior. When an UPDATE at Read Committed finds a row changed by another transaction, PostgreSQL waits if needed and then reevaluates the WHERE condition against the updated row version. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 The expression is applied to that current row, not to a copy the workflow holds. RETURNING exposes values from rows actually updated, so the run learns the value it wrote without a second read. PostgreSQL and UPDATE, accessed November 2026
The rehearsal script resets the counter to 0, launches ten workers concurrently, records each worker's PID, checks every exit status and asserts a final count of 10. In the recorded run every command reported `UPDATE 1`, each value from 1 to 10 was returned once, and the final line was `increments-final=10`. The statement below is the single statement each worker runs.
Be clear about what a hand run proves. Ten autocommit statements typed one after another do not overlap, so they only confirm the arithmetic. Only the script proves the ten-worker concurrent case. To create real overlap by hand, pair the sessions as the steps describe: Session A holds an open transaction while Session B's statement waits behind it.
The limit of this fix is its condition. If the run must take the value out of the database, decide something in the workflow and then write a replacement, a single statement cannot express the change. Use the version check or the row lock for those writes.
1. Reset the counter on row 42 to 0 before the proof. 2. Run `BEGIN` in Session A, then run the statement below and leave the transaction open. 3. Submit the same statement in Session B in autocommit mode and watch it wait. 4. Commit in Session A and confirm that Session B's statement then returns. 5. Repeat the pair until five pairs have run, which is ten increments in total. 6. Read row 42 and verify that the stored counter is 10.
Single-statement update derived from the current row
UPDATE mutable_records
SET counter = counter + 1
WHERE id = 42
RETURNING counter;
Fix two: add a version check and treat zero rows as a conflict
When the workflow prepares its replacement outside the database, use a version check. This is optimistic concurrency for automation: a conditional UPDATE whose WHERE clause includes both the record key and the version the run read, while the SET clause advances the version. One updated row means success. Zero updated rows means a concurrency conflict.
PostgreSQL documents the primitives this compare-and-swap workflow step relies on. The WHERE condition is reevaluated against the updated row version. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 The command count reports whether a row changed, and RETURNING exposes values from rows actually updated. PostgreSQL and UPDATE, accessed November 2026 Those pages do not name this composition optimistic locking; it is an application pattern built from the documented parts.
The check is a protocol, not a single query. Every writer that changes protected state must advance the revision, and every replacement derived from a read must check the revision it observed. A writer that bypasses the protocol, such as another workflow that updates the same column without the version condition, can still overwrite changes.
The rehearsal script resets the row and runs two version-checked writes one after the other with the same expected version. The first returns `optimistic-a=worker-a|v2` with `UPDATE 1`. The second reports `UPDATE 0`, and the final line is `optimistic-final=worker-a|v2`. The SQL below is that exact sequence, run in one session.
That sequence is sequential, and the rehearsal does not exercise two version-checked updates that overlap in time. For the overlapping case the documentation describes the behavior: the second UPDATE waits if needed and then reevaluates its WHERE condition against the updated row version. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 With the version in the condition, the changed row no longer matches. Treat that as the documented behavior, not as a result measured here.
The SQL Server demonstration reaches the same rule on that platform: the version condition must protect the write itself and a rejected write must be detected. Redgate concurrency demonstration, accessed November 2026 Detection is the half that gets skipped. A node that ignores the command count and continues down the success path hides the conflict the check just found.
At Tiger Media we treat the affected-row count the same way in a lead routing workflow: its token-guarded updates check the count, and a zero-row update is handled as lost ownership instead of a silent stale write. Our notification worker permits each state transition only while its lease token still owns the row. A lease token proves current ownership. It does not, though, replace revision checking, because a worker can own a row and still hold a value computed from an older read.
1. Add an integer version column to the record and give existing rows a starting value. 2. Read the key and the version together, and carry that version with the prepared edit. 3. Write with a condition on the key and the version you read, and advance the version in the same statement. 4. Check the command count before the run does anything else. 5. Treat one updated row as success and zero updated rows as a conflict. 6. Read the stored row and confirm that the accepted write and its new version are intact.
Both conditional writes use the same version that was read. The accepted writer advances the version; the stale writer changes zero rows and must reread before recomputing.
UPDATE mutable_records SET title = 'draft', counter = 0, version = 1 WHERE id = 42;
UPDATE mutable_records
SET title = 'worker-a', version = version + 1
WHERE id = 42 AND version = 1
RETURNING title, version;
UPDATE mutable_records
SET title = 'worker-b', version = version + 1
WHERE id = 42 AND version = 1
RETURNING title, version;
SELECT title, version FROM mutable_records WHERE id = 42;
Fix three: lock the row around a dependent update
Use a row lock when the workflow must inspect current database state and then perform a write that depends on it. When non-serializable writes are possible, PostgreSQL's application consistency guidance calls for row or table locks to validate and protect current data. PostgreSQL and 13.4. Data Consistency Checks at the Application Level, accessed November 2026 The lock acquisition, the decision and the UPDATE must stay in one database transaction on one connection.
SELECT FOR UPDATE protects the returned rows from conflicting lock, update, and delete operations until the transaction ends. Row locks affect writers and lockers of the same row, not ordinary reads, and are normally held until the transaction ends. PostgreSQL and 13.3. Explicit Locking, accessed November 2026 A plain read elsewhere is not blocked, while a second session that asks for the same lock waits.
What the waiting session receives matters. At Read Committed, a waiting SELECT FOR UPDATE can return the newer row after the concurrent transaction finishes. PostgreSQL and 13.3. Explicit Locking, accessed November 2026 The decision must run on the row returned after the wait, not on a value the workflow observed before it asked for the lock.
A lock delays a conflicting operation but does not cancel it; after the locking transaction ends, the blocked operation can continue unless the application logic prevents it. PostgreSQL and 13.4. Data Consistency Checks at the Application Level, accessed November 2026 If the blocked write carries a value fixed before the lock, it still lands last and still wins.
The rehearsal script confirms through `pg_stat_activity` that Session A holds the lock and that Session B is waiting. Each session captures the locked counter with the psql `\gset` command, computes its replacement from that value on the same connection and writes it inside the same transaction. The recorded lines are `worker-a-locked-read=0`, `worker-a-write=1`, `worker-b-locked-read=1`, `worker-b-write=2` and `locked-final=worker-b-from-current|counter=2`.
The protected change that survives is the counter: worker A writes 1, then the worker that waited for the row lock reads 1 and writes 2. The title is only a constant writer label, and the later commit replaces it by design. A lock protects values derived from the locked read. A constant, or a value captured before the lock, can still be overwritten by whichever write lands last.
For a hand run, create and seed the table, reset the row and follow the steps. The two-second `pg_sleep` in Session A is tuned for the script. By hand, lengthen it, or leave it out and hold back Session A's UPDATE and COMMIT until Session B is waiting.
::youtube[vfq3o5yG-PU]{title="What is SELECT FOR UPDATE in SQL? | Database Essentials" channel="CockroachDB" caption="Starting at 03:15, the presenter walks through a read-then-write transaction and explains how SELECT FOR UPDATE locks matching rows before the later update. This third-party walkthrough is contextual only; the database and isolation level shown may differ from the guide's local PostgreSQL 18.7 rehearsal, and it does not establish facts not cited in the dossier." start=195}
At Tiger Media we use a related but separate pattern in the notification worker described earlier. It claims one due row with a row lock and skip-locked selection and assigns a lease token. That is a claim on a piece of work, in which a second worker passes over a locked row. It is not the waiting pattern shown here.
1. Reset row 42 to title draft, counter 0 and version 1. 2. Begin a transaction in Session A, run the locking read and keep the session open. 3. Begin a transaction in Session B and run the same locking read while Session A still owns the lock. 4. Write counter 1 from the locked value in Session A and commit. 5. Watch Session B's read return counter 1, then write counter 2 from that value and commit. 6. Read row 42 and verify that the stored counter is 2.
The two tested sessions keep the locked read, application-style replacement derived from that read and the write on one connection inside one transaction. pg_stat_activity confirms Session A holds the row lock and Session B is waiting; Session B then reads counter 1 and returns counter 2.
-- Session A
BEGIN;
SELECT counter AS locked_counter FROM mutable_records WHERE id = 42 FOR UPDATE \gset
\echo worker-a-locked-read=:locked_counter
SELECT pg_sleep(2.0);
UPDATE mutable_records SET counter = :locked_counter + 1, title = 'worker-a-from-current' WHERE id = 42 RETURNING 'worker-a-write=' || counter;
COMMIT;
-- Session B, started only after pg_stat_activity confirms Session A holds the row lock
BEGIN;
SELECT counter AS locked_counter FROM mutable_records WHERE id = 42 FOR UPDATE \gset
\echo worker-b-locked-read=:locked_counter
UPDATE mutable_records SET counter = :locked_counter + 1, title = 'worker-b-from-current' WHERE id = 42 RETURNING 'worker-b-write=' || counter;
COMMIT;

Leave the row unchanged when the compare fails
Zero affected rows is the control working. An UPDATE can report whether it changed a row through its command count, and RETURNING exposes values from rows actually updated. PostgreSQL and UPDATE, accessed November 2026 When the count is zero, the stored row is exactly as the accepted writer left it. Keep it that way, record a conflict and decide what to repeat.
Never replay the stale replacement
Do not resend the same replacement with the new version number, and do not drop the condition to force the write through. Either move rebuilds the original overwrite with extra steps. The WHERE condition failed because PostgreSQL reevaluated it against the updated row version, which means the basis for the prepared edit no longer exists. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026
Make the conflict visible in the workflow. The SQL Server demonstration states the requirement for that platform: the version condition must protect the write itself and a rejected write must be detected. Redgate concurrency demonstration, accessed November 2026 Give zero rows its own branch, with its own log line, so that it is not folded into success or into a generic error.
Reread before you recompute
Repeat two things, in order. First repeat the read of the row, taking the key and the current version together. Then repeat the computation that produced the replacement, using the fresh values. Only then send a new conditional write that names the version from the fresh read.
The fresh read leads to one of three outcomes. The run can recompute and write again. It can merge the two edits, when an explicit business rule says how. Or it can stop and surface the conflict for review. If the fresh row contains a conflicting edit and the workflow has no rule for combining the two edits, leave the row unchanged and surface the conflict.
At Tiger Media, the documented design of one internal reconciliation job follows this order. It rereads the authoritative outcome, compare-and-swaps on the fields it expects and leaves the row untouched on a mismatch. That is a description of the design. It is not a test run or a measured outcome.
When events arrive late: guard by event time
This section rests on a first-hand rehearsal on synthetic records, with no external source behind it. It covers a case the version check does not: status callbacks that arrive out of order.
At Tiger Media we rehearsed a delivery status path in which callback events are stored separately and the mutable notification row is updated only when the event timestamp is newer than the one already applied. The test applied a delivered event at 12:00 and then a delayed event at 11:00. The status remained delivered. A bounce at 13:00 then advanced it.
The question asked is different from the version check. A version check asks whether the row changed since this run read it. An event-time guard asks whether this event is newer than the one that set the current state. Arrival order is not event order, so a late callback can pass a version check and still carry older information.
The limits are specific. The guard depends on trustworthy provider timestamps. The rehearsal did not test equal timestamps or clock skew. No SQL is published here, because the evidence for this guide contains no run-proven snippet for it, and how to design the event storage itself is outside the claim.
Which control fits which workflow
Choose by asking what the write depends on. If the new value can be written from the current row, use the atomic update. If the replacement is prepared outside the database and a conflict can be handled by rereading, use the version check. If the run must inspect current state and write a dependent value inside one transaction, use the row lock.
The table compares those three with the two stricter isolation levels. The PostgreSQL behavior comes from the PostgreSQL 18 transaction isolation page, which describes how a waiting UPDATE rechecks its condition, and from the PostgreSQL 18 UPDATE page, which describes the affected-row count and RETURNING. Both links are pinned to the major version used in the rehearsal.
Repeatable Read and Serializable move conflict handling from an explicit check to a transaction abort. Repeatable Read can reject an update when the target row changed after the transaction began, and the application must retry the entire transaction. Serializable aims to make committed concurrent transactions equivalent to some serial ordering, but applications must handle serialization failures by retrying. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026
One principle sits under every row: the condition that decides the write must be part of the write. The Redgate article shows this on SQL Server only, as a demonstration that the version condition must guard the write itself. Redgate concurrency demonstration, accessed November 2026 The table makes no claim about relative cost, because no benchmark was run for this guide.
| Control | When it fits | What a losing writer observes | Whole transaction retry | Documented in |
|---|---|---|---|---|
| Atomic update | The new value can be written as an expression of the current row | No loser: the statement waits if needed and applies its expression to the current row version | No, at Read Committed | PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 |
| Version check | The replacement is prepared outside the database from an earlier read | A command count of zero and no returned row | The conditional write was not applied; reread, establish the cause, then recompute before sending a new conditional write | PostgreSQL and UPDATE, accessed November 2026 |
| Row lock | The run must inspect current state and write a dependent value in one transaction | A wait, then the newer row once the lock holder finishes | No by itself; the blocked operation continues after the wait | PostgreSQL and 13.3. Explicit Locking, accessed November 2026 |
| Repeatable Read | The whole read and write unit can be rerun from its start | A rejected update when the target row changed after the transaction began | Yes, the entire transaction | PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 |
| Serializable | Several statements must behave as if they ran in some serial order | A serialization failure | Yes, handled by retrying | PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 |

What an n8n concurrency limit of one does and does not cover
A concurrency setting decides when executions run. It does not decide what a write is allowed to replace. The statements below describe what the single cited n8n documentation page and the single cited Google Sheets page say, and what they do not say.
Global limits versus per record safety
In regular mode, n8n's self-hosted concurrency control limits the number of production executions running at once and queues excess executions in FIFO order. n8n and Control concurrency, accessed November 2026 That is a description of execution scheduling. The page does not document record-key awareness, compare-and-swap behavior, database row locks or serializable transactions.
A limit of one can serialize the documented production executions on that instance. It does so for all of them together, including runs that touch unrelated records. The n8n concurrency setting controls production execution scheduling but does not establish record level consistency across other writers or excluded execution types. n8n control concurrency documentation, accessed November 2026
Other writers and excluded execution types
n8n self-hosted concurrency control is disabled by default and its documented scope excludes several execution types. n8n and Control concurrency, accessed November 2026 Read the page for the version you run to see which execution types sit outside the limit, and do not assume a given run is covered.
The queue also knows nothing about writers that are not in it. A person editing the record, an external integration or a second instance writes to the datastore directly. Only a control in the datastore, on the mutable record itself, applies to every one of those writers.
What Sheets request atomicity does not promise
The Google Sheets API allows simultaneous requests within quota and applies each request atomically, so invalid suboperations make the entire update fail. Google for Developers and Google Sheets API Usage limits, accessed November 2026 That guarantee is about one request: it applies as a unit or fails as a unit.
The same page does not state that a later request is rejected because its client read an older cell value. A Sheets workflow that reads, computes and later writes therefore still needs its own serialization or version strategy outside that guarantee. This guide does not rehearse one, so treat Sheets as a contrast and not as a tested control.
Deadlocks, retry budgets and side effects
Explicit locking can introduce deadlocks, and PostgreSQL resolves one by aborting a transaction. PostgreSQL and 13.3. Explicit Locking, accessed November 2026 A run can therefore be aborted even though each of its statements was valid. If one run updates several rows, make the lock order part of the design and take the locks in the same order in every run.
The stricter isolation levels add their own aborts. Repeatable Read can reject an update when the target row changed after the transaction began, and the application must retry the entire transaction. Serializable requires applications to handle serialization failures by retrying. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 The unit of retry is the whole transaction, reads included, not the last statement.
Bound the retries. AWS Prescriptive Guidance describes exponential backoff as increasing wait times for a specified number of retry attempts and warns that frequent retries can increase contention. It also says an operation retried with backoff should be idempotent; otherwise partial updates can corrupt system state. AWS Prescriptive Guidance and Retry with backoff pattern, accessed November 2026
For a workflow, that becomes three decisions: a fixed attempt budget, a delay that grows between attempts and a defined behavior when the budget runs out. Keep external side effects, such as a message send or a call to another system, outside the retryable transaction unless they have their own idempotency contract. A version conflict is a separate path: zero rows is not an error to replay, and it is handled by rereading as described earlier.
The optional fixture below, published as `retry-budget.mjs`, shows the budget logic alone. Run it with `node retry-budget.mjs`; it was run for this guide on Node.js v24.22.1. It allows 3 attempts with a base delay of 25 milliseconds. In the recorded output the retry delays were 32 and 64 milliseconds on the commit path and the same two values again on the exhaustion path, and the scenarios ended as committed on the third attempt, exhausted after three attempts and stopped on a non-retryable label.
Read its limits before you reuse it. The fixture feeds scripted labels in place of real database errors, and it proves only the attempt budget and the classification logic, not PostgreSQL retry behavior. It executes no database transactions and no external side effects, and its timing offsets are deterministic test values, not randomized jitter. Treating `40P01` as retryable and `23505` as not retryable is the fixture's own classification choice, so check the error codes your driver returns before you copy it.
A complete synthetic fixture treats the scripted labels 40001 and 40P01 as retryable and 23505 as non-retryable, then tests commit and exhaustion paths within three attempts. It does not execute database transactions, verify database retry behavior or run external side effects; its timing offsets are deterministic test values.
const maxAttempts = 3;
const baseDelayMs = 25;
const delay = async (milliseconds) => {
await new Promise((resolve) => setTimeout(resolve, milliseconds));
};
const runBudget = async (name, syntheticOutcomes) => {
const rows = [];
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
const outcome = syntheticOutcomes[attempt - 1];
if (outcome === "ok") {
rows.push({ attempt, outcome: "committed", sideEffect: "not-run-in-rehearsal" });
return { name, maxAttempts, rows };
}
if (!new Set(["40001", "40P01"]).has(outcome)) {
rows.push({ attempt, outcome: "non_retryable", sqlstate: outcome, sideEffect: "not-run-in-rehearsal" });
return { name, maxAttempts, rows };
}
if (attempt === maxAttempts) {
rows.push({ attempt, outcome: "exhausted", sqlstate: outcome, sideEffect: "not-run-in-rehearsal" });
return { name, maxAttempts, rows };
}
const deterministicJitterMs = attempt * 7;
const delayMs = baseDelayMs * 2 ** (attempt - 1) + deterministicJitterMs;
rows.push({ attempt, outcome: "retry", sqlstate: outcome, delayMs, sideEffect: "not-run-in-rehearsal" });
await delay(delayMs);
}
throw new Error("fixture outcomes shorter than maxAttempts");
};
const scenarios = [
await runBudget("commit_on_third_attempt", ["40001", "40P01", "ok"]),
await runBudget("exhaust_after_three_attempts", ["40001", "40001", "40P01"]),
await runBudget("stop_on_non_retryable_error", ["23505"]),
];
if (scenarios[0].rows.at(-1).outcome !== "committed") throw new Error("commit fixture failed");
if (scenarios[1].rows.at(-1).outcome !== "exhausted") throw new Error("exhaustion fixture failed");
if (scenarios[2].rows.at(-1).outcome !== "non_retryable") throw new Error("classification fixture failed");
console.log(JSON.stringify({ maxAttempts, baseDelayMs, retryableSqlstates: ["40001", "40P01"], scenarios }, null, 2));Prove it and watch for conflicts
Rehearse with synthetic data and isolated triggers, so that no rehearsal run can reach a production record. The guide to n8n staging trigger isolation covers how to run a rehearsal with synthetic data and isolated triggers. The rehearsal in this guide goes one step further and uses a disposable database that the script creates and removes.
Verify the intended effect of each operation, not the execution status. The naive race in this guide finished with every status green. Each fix has one pass condition, read from the stored row or from the value the statement returned, and the table lists all three.
Be precise about the lock proof. Both commits on the lock path succeed, and the later constant title replaces the earlier one by design. The lock rehearsal proves that the derived counter effect is preserved. It does not prove that every assigned column value is preserved.
In production, count the conflict signals separately from success counts. An UPDATE reports whether it changed a row through its command count, so zero-row conditional updates can be counted directly. PostgreSQL and UPDATE, accessed November 2026 Deadlock aborts and Repeatable Read rejections are separate signals. PostgreSQL and 13.3. Explicit Locking, accessed November 2026 PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 Add final failures after the retry budget as a fourth count.
A successful execution count can hide all of these, because a run that lost its write and a run that kept it can both finish green. The guide to automation monitoring covers how to preserve conflict and rejected-write evidence so that someone can review it later.
The list at the end of this section is the short form of the Lost update rehearsal checklist: reproduce the race, pick a control, prove the intended effect or a visible rejection. Copy the inline list into the workflow record and keep the completed copy with the workflow it describes.
If a write path still does not fit one of the three controls after the rehearsal, request a review from Tiger Media. Describe the record, every writer that touches it and the result of your rehearsal, so the review can start from evidence.
- Classify the failure as a stale replacement, a duplicate or a claim before choosing a control.
- Reproduce the stale overwrite on synthetic rows and keep the logs.
- Choose an atomic update, a version check or a row lock for each write path.
- Confirm each pass condition from the stored row, not from the execution status.
- Route zero-row updates to a conflict branch that rereads before it recomputes.
- Count conflicts, retries and exhausted retry budgets separately from successes.
| Proof | Pass condition | What it shows |
|---|---|---|
| Atomic update | Ten increments take the counter from 0 to 10 | Every concurrent increment took effect |
| Version check | The stale write reports UPDATE 0 and the row stays worker-a at version 2 | The rejection is visible and the accepted write is intact |
| Row lock | The worker that waited for the row lock sees 1 before advancing the counter to 2 | The value derived from the locked read is preserved |
Frequently asked questions
Does setting n8n concurrency to one fix lost updates?
No, not as a guarantee for the record. The n8n documentation describes a limit on production executions running at once, with excess executions queued in FIFO order, and says the feature is disabled by default with several execution types outside its scope. n8n and Control concurrency, accessed November 2026 It does not establish record level consistency across other writers. n8n control concurrency documentation, accessed November 2026 Guard the write in the datastore.
Why did both runs report success?
Because each write was valid on its own. Each plain SELECT sees a snapshot as of the start of that query, so both runs can read the same state, and an unguarded UPDATE still matches the row after PostgreSQL reevaluates its WHERE condition. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026 The self-reported n8n case describes that result: both workflows reported success and one contact change disappeared. DEV Community n8n operator account, accessed November 2026
What should I repeat after a version conflict?
Repeat the read, then the computation, then the conditional write. A command count of zero means the conditional write was not applied. In this rehearsal, the cause is a stale version; in production, reread and establish the cause before recomputing, and do not resend the rejected replacement. PostgreSQL and UPDATE, accessed November 2026 If the fresh row holds a conflicting edit and no rule combines the two, leave the row unchanged and surface the conflict. At Tiger Media, the documented design of an internal reconciliation job follows that order; it is a design description, with no test run or measured outcome claimed.
Does this apply to Google Sheets or other databases?
The principle carries over, but the tested SQL does not. The rehearsal ran only on PostgreSQL 18.7. The Redgate article is a SQL Server demonstration that the version condition must guard the write, not a tested implementation on another engine. Redgate concurrency demonstration, accessed November 2026 The cited Sheets page says each request is applied atomically; it does not describe rejecting a write that was based on an older read. Google for Developers and Google Sheets API Usage limits, accessed November 2026
Key takeaways
The short version of the guide, in the order you would apply it to a workflow that already writes mutable records from concurrent runs.
- Classify the problem first: a stale replacement of an existing value, a duplicate creation and a claim on a resource need different controls.
- Guard the write itself, because PostgreSQL reevaluates the WHERE condition of a waiting UPDATE against the updated row version, and a check in an earlier node is not part of that recheck. PostgreSQL and 13.2. Transaction Isolation, accessed November 2026
- Treat zero affected rows as a signal: the command count is how a rejected write becomes visible, and the SQL Server demonstration makes detection part of the rule. PostgreSQL and UPDATE, accessed November 2026 Redgate concurrency demonstration, accessed November 2026
- Reread after a conflict and recompute from the fresh row; at Tiger Media, the documented design of an internal reconciliation job rereads the authoritative outcome and compare-and-swaps on the expected fields, which is a design description and not a tested result.
- Do not rely on a global limit: the n8n concurrency setting schedules production executions and does not establish record level consistency across other writers or excluded execution types. n8n control concurrency documentation, accessed November 2026
- Measure conflicts, zero-row updates and exhausted retry budgets separately from successful executions, so contention stays visible.
Scroll the table sideways to read every column.
| Control | Pass condition | Observed result |
|---|---|---|
| Atomic update | Ten increments take the counter from 0 to 10 | increments-final=10 |
| Version check | The stale write changes zero rows and preserves worker-a at version 2 | UPDATE 0; optimistic-final=worker-a|v2 |
| Row lock | The waiting worker reads 1 before writing 2 | worker-b-locked-read=1; worker-b-write=2 |
Sources to check next
- PostgreSQL 18.7 Documentation, 13.3. Explicit Locking
- PostgreSQL 18.7 Documentation, 13.2. Transaction Isolation
- PostgreSQL 18.7 Documentation, 13.4. Data Consistency Checks at the Application Level
- PostgreSQL 18.7 Documentation, UPDATE
- Control concurrency
- Google Sheets API, Usage limits
- Developing modifications that survive concurrency
- Why two tabs silently overwrote each other
- Two workflows wrote to one row and both reported success
- Retry with backoff pattern
Vendor features and prices change. Confirm details on the linked official pages before you rely on them.
What to read next
- Prevent duplicate CRM records when automations retry
- n8n staging production triggers: A practical isolation guide
- Automation monitoring checklist: verify completed work