Lost updates don't throw exceptions; whether they happen depends on the customer database's isolation level, and few engineers have ever checked that setting.
Key takeaways
- When two agents run concurrently, read the value, compute in code, then write back is the fastest path to a lost update
- PostgreSQL defaults to Read Committed, MySQL InnoDB defaults to REPEATABLE READ, CockroachDB defaults to SERIALIZABLE; the same code can produce three different outcomes
- The stricter the isolation level, the more the client must be prepared to retry; the retry loop must catch deadlocks in addition to serialization failures
On Monday morning, a customer reported that an account was charged points incorrectly. The logs showed the support agent added 50 points as compensation, and the billing agent deducted 30 points in fees; both reported success. The balance should have been 120, but the database showed 70.
By ordinary standards, this code has no bug. Each agent correctly executed its own logic; they just happened to run at the same time. Once agents enter a customer's system, multiple processes writing to the same record become routine. Which number the database ends up with depends on how transactions are used, and on which isolation level the database is running.
Most engineers know the acronym ACID, but few know how the I in the customer's database is configured. Forward Deployed Engineers (FDEs) must know, because this kind of bug throws no exceptions; it silently corrupts data until the customer discovers it themselves.
Where did the 50 points go?
Lay the two sessions side by side in chronological order, and the answer is obvious. Both agents use the same code: read the balance, compute the new balance in Python, then write it back.
-- Agent A(客服) -- Agent B(计费)
SELECT balance FROM accounts SELECT balance FROM accounts
WHERE id = 42; -- 100 WHERE id = 42; -- 100
-- 计算 100 + 50 = 150 -- 计算 100 - 30 = 70
UPDATE accounts SET balance = 150
WHERE id = 42; COMMIT;
UPDATE accounts SET balance = 70
WHERE id = 42; COMMIT;This is a lost update: the later writer overwrites the earlier writer's result, completely unaware of the other's existence. 70 is what Python computed from a stale read; the database received only a constant and stored it as-is.
The scenario above runs under Read Committed, PostgreSQL's default level. Unless someone deliberately changed the configuration, this "read, compute, write back" code has no protection when two agents interleave.
Three fixes, each covering a different problem
The simplest approach is to let the database do the arithmetic. Write it as
UPDATE accounts SET balance = balance + 50 WHERE id = 42
so the addition happens inside the statement, eliminating the stale-read constant from the example above.
For modifications that only add or subtract a number, try this first. Even so, verify it yourself by opening two psql windows against the customer's real database.
However, agents often need to read first and then decide: for example, deducting the fee only if the balance is sufficient, or letting the LLM choose an action based on the customer's current state. In that case, you need a pessimistic lock.
SELECT ... FOR UPDATE
This locks the row just read as the row about to be updated, preventing another agent from overwriting it.
BEGIN; SELECT balance FROM accounts WHERE id = 42 FOR UPDATE; -- 在第 42 行被锁住期间,由代码做出决定 UPDATE accounts SET balance = 70 WHERE id = 42; COMMIT;
The third approach is for PostgreSQL: run the transaction at the Repeatable Read or Serializable level, and accept that the database may abort the transaction with a serialization error. The PostgreSQL documentation requires applications running at Repeatable Read to be prepared to retry. When such an error occurs, you must abandon the entire transaction and rerun it from the beginning, not just the failed statement.
Note that this describes PostgreSQL's behavior. MySQL InnoDB also has a level called REPEATABLE READ, but the same name doesn't mean the same behavior; don't assume it provides the same protection.
The retry loop also needs to catch one more class of error. In psycopg,
SerializationFailure
(error code 40001) and
DeadlockDetected
(error code 40P01) are two separate exception classes. If you only catch the former, the loop will miss deadlocks.
import random
import time
from psycopg import errors
RETRYABLE = (errors.SerializationFailure, errors.DeadlockDetected)
def run_with_retry(conn, work, attempts=5):
for i in range(attempts):
try:
with conn.transaction():
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
return work(conn) # 每次尝试都从头重新读取
except RETRYABLE:
if i == attempts - 1:
raise
# 带随机抖动的退避,避免两个 Agent 立刻再次冲突
time.sleep(0.05 * 2 ** i + random.uniform(0, 0.05))The most critical point in this code is:
work
every attempt must re-read the data. If the agent reuses the old read result, or the LLM's answer computed from the old state, the retry will just write the wrong value again.
time.sleep
This line is exponential backoff with a small amount of randomness. Without it, two agents that just collided may retry at the same time and collide again.
| Approach | Mechanism | Applicable scenarios |
|---|---|---|
| Atomic update | Arithmetic is written into the statement, no stale values exist | Additions, subtractions, counters |
| SELECT ... FOR UPDATE | Locks the row just read; another agent cannot overwrite it | Read-then-decide, high contention |
| Repeatable Read/Serializable + retry (PostgreSQL) | PostgreSQL aborts the transaction with a serialization error; the client reruns the entire transaction | Low contention, complex logic |
Snapshots still let one class of bug through
Even after raising the isolation level, one trap remains. Jepsen points out that snapshot isolation allows write skew: multiple transactions read the same shared state, each modifies a different set of objects, and then all commit successfully. The PostgreSQL documentation likewise states that Repeatable Read prevents all phenomena in its table except serialization anomalies, and write skew is precisely a serialization anomaly.
Suppose the customer has a rule: every account must keep at least one emergency contact, and account 42 currently has two. Agent A deletes the first, Agent B deletes the second.
Both count two contacts and judge the deletion safe. Each deletes a different row; no row is written twice, so there is no conflict to report. In the end, the account has no contactable person at all.
So the PostgreSQL documentation warns: enforcing business rules under Repeatable Read is hard to get right without careful use of explicit locks. Write skew happens because the two sides never touch the same row; the sensible fix is to force both through the same row: before counting, execute
SELECT ... FOR UPDATE
。
Another route is Serializable. The PostgreSQL wiki calls write skew the simplest anomaly that SSI prevents: the first committer wins, and the other transaction is rolled back and must be rerun, which again requires the retry loop above.
Same isolation level names, different meanings across databases
This is where FDEs most often stumble when moving from one customer to the next. MySQL InnoDB defaults to REPEATABLE READ, not Read Committed like PostgreSQL. CockroachDB defaults to SERIALIZABLE and requires clients to implement their own retry logic, with error code 40001.
Martin Kleppmann pointed out in Hermitage, a project testing the I in ACID, that names like repeatable read mean different things in different databases.
The consequences are clear. Agent code that ran fine on CockroachDB in the last project, if it relies on the database to intercept conflicts, may corrupt data on PostgreSQL with default settings. Conversely, code written for PostgreSQL without retries will hit 40001 errors on CockroachDB with no one handling them. Check the actual configuration; don't rely on memory.
More locks, one more risk: deadlocks
Using
FOR UPDATE
After that, deadlock follows: Agent A locks the account and waits for the invoice, while Agent B locks the invoice and waits for the account. PostgreSQL detects this situation, aborts one of the transactions, and lets the others continue.
Deadlocks and serialization failures are different errors, so you need a retry loop even under Read Committed, and you must catch
DeadlockDetected
as in the code above. The MySQL documentation offers similar advice: always be prepared to re-execute transactions that failed due to deadlock.
According to the PostgreSQL documentation, the best defense is to have all applications acquire locks on multiple objects in a consistent order. Set a convention for the entire agent system—for example, always lock the account before the invoice, or lock in ascending order by id—and write it into the handover documentation so the customer's team doesn't break it later.
Common pitfalls in the field
The most common pitfall is letting agents generate "read, compute in code, write back" SQL without anyone checking for contention. Equally common: retrying without re-reading the data, retries firing consecutively without backoff, and retries that only catch serialization failures while missing deadlocks.
A pitfall specific to agent systems is keeping a transaction open while waiting for an LLM response. The MySQL documentation recommends keeping transactions small and short to reduce conflicts. So you should read the data first, call the model outside the transaction, and then open a short transaction to re-validate and write.
The next time you let a second agent write to the same table, ask yourself first: if two agents run in the same millisecond, which number is left behind? In an FDE interview, clearly describing an experience where you personally traced and fixed a lost update carries far more weight than a "PostgreSQL" entry on a skills list.
Was this article helpful?
Thanks for your feedback!