I turned our database's only writer connection into a global lock, and then held it for up to a minute

Last week an operator clicked “clear all alerts” and got a timeout. That timeout turned out to be the smallest of the problems. For a bit over an hour after one deploy, around a hundred writes failed every ten minutes: machine reports, command results, fleet operations, mirror polls, workspace records, and the issue-number requests our agents wait on. The cause was code I wrote. This post covers what I did, why it broke things, and what I’m changing.

The setup I should have taken more seriously

Our controller’s store has two connection pools: sixteen reader connections and one writer. Having a single writer is deliberate. It serializes writes arriving from every connected agent at once. A write that can’t get the writer within 30 seconds fails.

That makes the writer a process-wide exclusive lock on every write in the system. Whatever runs on it, nothing else can write. I knew there was one writer. I didn’t think hard about what that meant.

Mistake 1: a large read inside a write transaction

I added per-test duration measurement. When a test run is recorded, we compare each test’s duration against its recent average so slow tests get flagged. I put the classification step inside the transaction that records the run, on the writer, before commit.

The classification query looked roughly like this:

WITH earlier AS (
  SELECT t.test_id, t.duration
  FROM results t JOIN runs r ON r.id = t.run_id
  WHERE r.repository = :repo
    AND r.ended_at >= :ended_at - :window
    AND r.ended_at <  :ended_at
    AND t.test_id IN (/* tests in this run */))
SELECT test_id, avg(duration), count(duration)
FROM ... LEFT JOIN earlier ...
GROUP BY test_id

It averages every raw result for the repository over a 7-day window. For our largest repository that’s about 1.5 million rows, scanned once for every run recorded. On production it took 10 to 70 seconds.

The query only reads. The one write that follows it is a small UPDATE of the run’s own rows. I still ran the whole thing under the exclusive lock.

The worst part: a rollup table holding each test’s daily duration sum and count already existed, and the same transaction was writing to it two statements earlier. I never pointed the measurement at it.

Mistake 2: a lazy backfill on the read path

Runs recorded before the feature existed had no classification. I backfilled them lazily: the first time something read a run, it would classify it.

// Classify an older run the first time a read needs it.
// Lock the run so two racing reads classify it once.
async fn classified(&self, run: i64) -> Result<(), StoreError> {
    let tx = self.writer.begin().await?;
    // SELECT classified FROM runs WHERE id = $1 FOR UPDATE
    if !classified { classify(&tx, run).await?; }
    tx.commit().await?;
}

So viewing test results in the UI took the writer, took a row lock with FOR UPDATE, ran the 1.5-million-row scan, and committed. After the deploy, about 8,170 historical runs needed classifying, and ordinary page views worked through them one at a time, each holding the writer for 10 to 70 seconds.

My commit message said it outright: “classify a run inside the record step (and an older run on first read).” Nobody asked, me included, how many runs that would be or how long each one would take.

Mistake 3: re-deriving the world on every write

Separately, writes that need a project’s issue roll-up (recording a reading, placing a dispatch, draining, repairs, the refresh) rebuilt it from every stored reading, inside their own writer transaction. I wrote down my reasoning in a doc comment: the write has to see its own uncommitted changes, so it re-reads everything in its own transaction.

For our busiest project that’s about 56,000 rows and one to three seconds per call. With readings arriving from more than 40 workspaces, these calls ran back to back. On their own they were a steady drain on the writer. Together with the backfill, they took up whatever time it had left.

What it caused

Because the writer is one connection, anything running on it blocks every write in the controller. For the hour after the deploy, the backfill held it for tens of seconds at a time and the roll-up rebuilds took most of the gaps. Every other write waited its 30 seconds and failed.

When the backlog finished, the incident ended, but the cost didn’t. Every finished pipeline run still holds the writer for one of those scans. The cost also grows with the repository’s history, not with the run. At 10x or 1000x the data, the same backlog would have meant days of writer time.

What I should have done

Hold an exclusive resource only for the exclusive part. Both operations were a long read followed by a short write. The read belonged on the sixteen readers. The writer should only have been taken for the UPDATE. For the roll-up, if a write needs to account for its own uncommitted change, the answer is to apply that known change to the stored value, not to re-read everything under the lock. This applies to every mutex and lock in the codebase, not just this connection.

Never put a backfill on the hot path. A one-time migration of thousands of rows doesn’t belong in a read handler, under FOR UPDATE, on the writer. It should be a background sweep that does a bounded amount of work per pass. Until the sweep gets to a record, reads should return it as “not yet measured.”

Make cost scale with the work. Something that runs once per recorded run should cost in proportion to that run, not to the repository’s whole history. The aggregate table that makes this possible was already there.

Put shared constraints in the design. Our architecture docs never said there is one writer, or what may run on it, or for how long. When a constraint is shared by every write in the system and isn’t written down, each subsystem’s author has to discover it on their own, and most won’t. We’ve now added a rule: the writer is held for the write alone. Anything a write derives, measures or aggregates is read on the readers first, and backfills run as bounded sweeps separate from reads and writes. I should have written that rule the day the store was introduced, not after this.

Watch the slow-statement log. It named both queries. The commit that caused this sat for about three weeks before a deploy promoted it, and nothing in that time compared statement times on the writer against the 30-second timeout.

Where things stand

Two high-priority fixes are filed. One measures from the rollup table, does the read on a reader, writes only the measured rows, and replaces the lazy backfill with a bounded sweep. The other updates the stored roll-up with the transaction’s own change and only does a full rebuild, on a reader, when the stored value can’t be updated. Neither has shipped yet. The deployed controller still has both behaviours, though the historical backlog is finished.

What I’ll check for in review from now on

  • A writer transaction that runs a SELECT over a table that grows with history before it writes.
  • Any FOR UPDATE on a path that a read can trigger.
  • Any “lazily, the first time a read needs it” backfill with no limit on how much work each pass does.
  • Any query that reads N rows to serve an operation of size M, where M is much smaller than N and an aggregate already exists.
  • Any exclusive lock, mutex or single connection held across an await on something that only reads.

I’m sorry to everyone whose writes failed during that hour, and to the operator who was just trying to clear their alerts. The single writer was a fine design. The problem was that I used it to hold read work it was never meant to carry.

Advanced search: filter by model or tag