FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Two agents, one row, and 50 credits gone without a single error

A lost update throws no exception, and whether a client's database allows one comes down to an isolation level few engineers ever check.

ShareLinkedInFacebookX

In brief

  • Reading a value, computing in code and writing it back is the fastest way to lose an update when two agents run at once
  • PostgreSQL defaults to Read Committed, MySQL InnoDB to REPEATABLE READ and CockroachDB to SERIALIZABLE, so the same code can produce three different results
  • The stricter the isolation level, the more the client must be ready to retry, and the retry loop has to catch deadlocks as well as serialization failures
Comparison table of three ways to prevent a lost update when two agents write the same record: atomic update (the later writer waits; suits arithmetic; try it first), SELECT … FOR UPDATE (the other side waits on a lock; suits read-then-decide), and Repeatable Read with retry (one transaction is aborted and rerun; suits complex logic).
For additions and subtractions, letting the database compute inside the UPDATE statement is the first approach to try. When an agent must read before deciding, use locks, or run at a higher isolation level with retries. Source: PostgreSQL documentation, per the article.

A client reports on a Monday morning that an account has been charged the wrong number of credits. The logs show the support agent adding 50 credits as compensation and the billing agent deducting a 30-credit fee, and both report success. The balance should be 120. The database says 70.

In the usual sense, the code has no bug. Each agent ran its own logic correctly; they just ran at the same moment. Once agents go into a client’s systems, several processes writing to the same record becomes routine. The number left in the database depends on how transactions are used and on the isolation level the database is running.

Most engineers know the acronym ACID, but few know how the I is configured on their client’s database. FDEs need to, because this class of bug throws no exception. It quietly corrupts data and waits for the client to find out.

Where did the 50 credits go?

Lay the two sessions side by side in time order and the answer is plain. Both agents share the same code: read the balance, compute the new balance in Python, write it back.

-- Agent A (support)             -- Agent B (billing)
SELECT balance FROM accounts      SELECT balance FROM accounts
 WHERE id = 42;   -- 100           WHERE id = 42;   -- 100
-- compute 100 + 50 = 150         -- compute 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 write overwrites the earlier one without ever knowing it existed. The 70 was computed in Python from a stale read, so the database simply receives a constant and stores it.

The scenario above runs under Read Committed, which is PostgreSQL’s default. Unless someone has deliberately changed the configuration, read, compute, write code of this kind has no protection when two agents interleave.

Three fixes, each for a different kind of problem

The simplest fix is to let the database do the arithmetic. With UPDATE accounts SET balance = balance + 50 WHERE id = 42, the addition happens inside the statement, so there is no constant computed from a stale read as in the example above.

For changes that add or subtract a number, this is the first thing to try. Even so, verify it yourself with two psql windows on the client’s actual database.

Agents, though, often have to read before they decide: deduct the fee only if the balance covers it, say, or have an LLM choose an action based on the customer’s current state. That calls for pessimistic locking. SELECT ... FOR UPDATE locks the rows just read as if they were about to be updated, stopping the other agent from writing over them.

BEGIN;
SELECT balance FROM accounts WHERE id = 42 FOR UPDATE;
-- decide in code while row 42 is locked
UPDATE accounts SET balance = 70 WHERE id = 42;
COMMIT;

The third fix is for PostgreSQL: run the transaction at Repeatable Read or Serializable and accept that the database may abort it with a serialization error. The PostgreSQL documentation requires applications running at Repeatable Read to be ready to retry when that happens. When it does, the whole transaction must be abandoned and rerun from the start, not just the statement that failed.

Note that this describes PostgreSQL’s behavior. MySQL InnoDB also has a level called REPEATABLE READ, but the same name does not mean the same behavior, so do not assume it protects you in the same way.

The retry loop has to catch one more kind of error. In psycopg, SerializationFailure (code 40001) and DeadlockDetected (code 40P01) are separate exception classes. Catch only the first and 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)  # re-read from scratch on every attempt
        except RETRYABLE:
            if i == attempts - 1:
                raise
            # jittered backoff so the two agents don't collide again immediately
            time.sleep(0.05 * 2 ** i + random.uniform(0, 0.05))

The most important point in this code is that work must re-read the data on every attempt. If the agent keeps its old read, or keeps an LLM answer computed from the old state, the retry just writes the wrong value one more time.

The time.sleep line is exponential backoff with a little randomness; without it, two agents that have just collided can retry at once and collide again.

Approach Mechanism Suits
Atomic update The arithmetic lives in the statement, with no stale value Adding, subtracting, counting
SELECT ... FOR UPDATE Locks the rows just read so the other agent cannot overwrite them Read then decide, high contention
Repeatable Read/Serializable + retry (PostgreSQL) PostgreSQL aborts the transaction with a serialization error and the client reruns the whole transaction Low contention, complex logic

Snapshots still let one kind of bug through

Raising the isolation level leaves one trap. Jepsen describes snapshot isolation as permitting write skew: transactions read a shared piece of state, each modifies a different set of objects, and both commit. The PostgreSQL documentation likewise says Repeatable Read prevents every phenomenon in its table except serialization anomaly, the category that includes write skew.

Say a client has a rule that every account must keep at least one emergency contact, and account 42 currently has two. Agent A removes the first; agent B removes the second.

Both count two contacts and conclude it is safe. Each deletes a different row, no row is written twice, so there is no conflict to report. The account ends up with nobody to call.

That is why the PostgreSQL documentation warns that enforcing business rules at Repeatable Read is hard to get right without careful use of explicit locks. Write skew hinges on the two sides never touching the same row, so a sensible approach is to force both through a shared row: SELECT ... FOR UPDATE on the row for account 42 itself before counting.

The other route is Serializable. The PostgreSQL wiki describes write skew as the simplest anomaly that SSI prevents: whoever commits first wins, and the other transaction is rolled back and must be rerun, which again calls for the retry loop above.

Same isolation level name, different meaning in each database

This is where FDEs most often stumble when moving from one client to the next. MySQL InnoDB defaults to REPEATABLE READ, not Read Committed as PostgreSQL does. CockroachDB defaults to SERIALIZABLE and requires clients to implement their own retry logic, with error code 40001.

Martin Kleppmann, in Hermitage, his project testing the I in ACID, observes that a name such as repeatable read means different things in different databases.

The consequence is clear. Agent code that worked on CockroachDB on the last project, if it relied on the database blocking conflicts, can corrupt data on a default PostgreSQL install. Conversely, code written for PostgreSQL without retries will hit 40001 errors on CockroachDB with nothing to handle them. Check the real configuration; do not rely on memory.

More locks, one more risk: deadlock

Once FOR UPDATE is in play, deadlocks follow: agent A locks the account and waits for the invoice, while agent B locks the invoice and waits for the account. PostgreSQL detects this and aborts one transaction so the others can proceed.

A deadlock is a different error from a serialization failure, so even under Read Committed a retry loop is needed, and it must catch DeadlockDetected as the code above does. The MySQL documentation gives similar advice: always be prepared to reissue a transaction that fails because of a deadlock.

According to the PostgreSQL documentation, the best defense is for every application to acquire locks on multiple objects in a consistent order. Set a convention for the whole agent system, such as always locking the account before the invoice, or locking in ascending id order, and write it into the handover documentation so the client’s team does not break it later.

Common traps at client sites

The most common trap is letting agents generate read, compute-in-code, write SQL without anyone checking for contention. Just as common are retries that do not re-read the data, retries fired in rapid succession with no backoff, and retries that catch serialization failures but forget deadlocks.

The trap peculiar to agent systems is holding a transaction open while waiting for an LLM to respond. The MySQL documentation advises keeping transactions small and short to reduce collisions. So read the data, call the model outside the transaction, then open a short transaction to re-check and write.

Next time, before letting a second agent write to the same table, ask which number would survive if both agents ran in the same millisecond. In an FDE interview, the story of a lost update you tracked down and fixed will carry far more weight than “PostgreSQL” on a list of skills.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
9 sources
Read next on the roadmap · Stage 2: Broad engineeringOne Mail.Read consent lets your app read every mailbox in the tenantA hands-on lab locks a Graph app to one shared mailbox on the Exchange side, then uses test results to prove the limit to IT.