I Computed Live State by Rescanning History on Every Read
I recently shipped code that made our system re-read its own history every time someone opened a list. It caused an incident. This post covers what I wrote, why it went wrong, and what I’m doing differently.
What I built
Our controller records every event in an agent session in an append-only log: messages, tool calls, tool results, usage reports, end-of-turn markers, and occasionally a question to the user and the user’s answer. The log holds hundreds of thousands of rows and is close to a gigabyte in production. Almost all of those rows are routine. The interesting ones, questions and answers, are extremely rare, a handful at most. The table’s only index is its primary key.
Two features needed live state about sessions:
-
Is this session asking for input right now? The rule in the design was clear: a session is asking exactly while it has an open question. The design didn’t say where that answer should be stored, so I computed it. I wrote a correlated
EXISTSthat looks for a question event with no later matching answer event. Then I reused that query in every listing that needed it, so it ran once per row of the sessions page and of every work listing. -
How many turns did each agent take today? I counted end-of-turn events per agent by joining every event of every session belonging to that agent, then filtering by kind and time. A counter column for turns already existed on the agent record, right next to the query I wrote to recompute it.
Both queries returned correct results. Both were also the wrong design.
What it caused
During the incident we measured the queries with EXPLAIN (ANALYZE, BUFFERS) against production:
- Asking status for one project’s work listing (about a thousand rows) ran a parallel sequential scan over the whole event table. It took about 170ms with a warm cache and over 6 seconds under load.
- Asking status across all open sessions used the index, but read hundreds of events per session to keep one. It took more than a second.
- Turns per agent today read nearly 2GB of buffers and threw away 99.7% of the rows it touched. Each run took over 5 seconds, and it ran more than twenty times in two hours.
That last query became the largest consumer of database CPU. It pushed out of cache the working set the event writer depended on, so the writer fell behind. The growing write backlog drove up the controller’s memory. The sessions page also lagged reality by the size of that backlog: the answer came from the store, and the store was several minutes behind what the agents were actually doing.
The feedback I got was blunt, and it was fair: scanning that many rows and discarding 99.7% of them was never acceptable. There’s no reasonable data size at which this design would have been fine. It only seemed fine because the table was small when I wrote it.
What I got wrong
The bug wasn’t really in the SQL. I treated “what state is this thing in right now” as a question to ask history, when it is a fact the system should keep as events happen.
Specifically:
- I derived state when it was read instead of recording it when it changed. Each question, answer and end-of-turn event passes through the controller as it happens. That was the cheap moment to update a flag or a counter, and I skipped it.
- I ignored an existing column that already held the answer. A stored turn counter sat right beside a query that recomputed it from the raw log.
- I ignored a pattern already in the codebase. Our machine registry keeps live state in memory and updates it as frames arrive, and its listing never touches the database. Session state should have worked the same way.
- I never measured. The queries returned the right answers on a dev-sized dataset, so I moved on. A table with hundreds of thousands of rows, one index, and two rows that matter is a table nobody profiled.
- I filled a gap in the design without saying so. The design defined what “asking” means but not where that state lives. I picked “compute it from everything, every time” without flagging that as a decision.
What I should have written
- Record live state as it changes. A question event sets
asking, the matching answer clears it, and an end-of-turn event increments a counter. The listing reads a field. Live session state belongs in memory in the controller, next to the machine registry, and is written to the stored record as it changes. Queries over past sessions read the recorded state and never rescan a session’s events to work it out again. - Make the design say where live state lives. “A session is asking while it has an open question” is a definition, not a storage plan. Designs that describe what something is (asking, resting, running, its current stage) should also say who holds that state and when it updates.
- Index the rare cases when a scan is truly needed. If some path really has to search the log for rare event kinds, a partial index on just those kinds turns a full scan into a few index probes.
How I’ll check this from now on
For every query on a listing, a stream, or any path the UI or agents hit repeatedly, I’ll ask: how many rows does it read compared to how many it returns? A listing’s cost should scale with what it lists, never with the history behind it.
Each of these red flags now gets an EXPLAIN (ANALYZE, BUFFERS) against production-scale data before I merge:
- A correlated subquery that runs once per row of a listing.
- An
EXISTSorCOUNTover an event, log, history, or audit table, filtered by a rare kind. - A state the design says something “is” that gets answered by a query instead of read from a field.
- A column that already holds the answer, next to a query that recomputes it.
- A table whose only index is its primary key, filtered by anything other than that key.
The number I’ll watch is the discard rate: the share of rows read that didn’t contribute to the answer. If that’s above a few percent on a hot path, the state is stored in the wrong place, and I need to move it rather than tune the query.
I’m sorry for the incident and for the time others spent tracking it down. The fix is to store this state in the right place, and that work is underway.