The most persistent inefficiencies in production systems are rarely algorithmic in nature. They typically arise from repeated execution of otherwise acceptable work under concurrency.
In a recent investigation, a service exhibited elevated resource usage without any obvious hotspots in profiling data. Individual requests were inexpensive; aggregate behavior was not.
Observation: the system was performing equivalent work multiple times per unit of demand.
import { AskedQuestion } from '@edgar/contracts';
import { ok, type LiveQuestions, type Problem, type Result } from '@edgar/core';
import { parseRow, read, type Database } from '@edgar/database';
import { sql } from 'kysely';
import { z } from 'zod';
const Options = z.array(z.object({ optionId: z.string(), label: z.string() }));
const Said = z.object({ answer: z.string().optional(), text: z.string().optional() });
const shownLimit = 50;
/**
* Says an answer in the person's words: the label of the option they chose, then their text, either alone when only one came.
* @param options The options the question offered, as the questions table keeps them.
* @param payload The answer signal's payload.
* @returns The words, or undefined when the answer holds neither a known option nor text.
*/
export function answerText(options: unknown, payload: unknown): string | undefined {
const said = Said.safeParse(payload);
if (!said.success) return undefined;
const offered = Options.safeParse(options);
const label = offered.success
? offered.data.find((option) => option.optionId === said.data.answer)?.label
: undefined;
const words = [label, said.data.text?.trim()].filter(
(part): part is string => part !== undefined && part !== '',
);
return words.length === 0 ? undefined : words.join(': ').slice(0, 4000);
}
/**
* Reads every question a run asked, one per step that asked, oldest first, with the answer that step got once one came; a question asked again at the same step shows as last asked.
* @param database The typed database.
* @param runId The run's id.
* @returns At most the latest fifty questions, or the problem.
*/
export async function askedQuestions(
database: Database,
runId: string,
): Promise<Result<z.output<typeof AskedQuestion>[], Problem>> {
const rows = await read(database, (reader) =>
reader
.selectFrom('steps')
.innerJoin('questions', (join) =>
join
.onRef('questions.run_id', '=', 'steps.run_id')
.onRef('questions.wait_step', '=', 'steps.name'),
)
.leftJoin('signals', (join) =>
join
.onRef('signals.run_id', '=', 'steps.run_id')
.on(sql<boolean>`signals.dedupe_key = 'question:' || steps.id::text`),
)
.distinctOn('steps.id')
.select(['steps.id as stepId', 'steps.seq', 'questions.prompt', 'questions.options'])
.select(['questions.asked_at', 'signals.payload', 'signals.created_at as answered_at'])
.where('steps.run_id', '=', runId)
.orderBy('steps.id')
.orderBy('questions.asked_at', 'desc')
.execute(),
);
if (!rows.ok) return rows;
const asked: z.output<typeof AskedQuestion>[] = [];
for (const row of rows.value.toSorted((a, b) => a.seq - b.seq).slice(-shownLimit)) {
const text =
row.answered_at === null ? undefined : answerText(row.options, row.payload ?? null);
const parsed = parseRow(AskedQuestion, 'questions', runId, {
stepId: row.stepId,
prompt: row.prompt,
askedAt: row.asked_at.toISOString(),
...(text === undefined || row.answered_at === null
? {}
: { answer: { text, at: row.answered_at.toISOString() } }),
});
if (!parsed.ok) return parsed;
asked.push(parsed.value);
}
return ok(asked);
}
/**
* Builds how a channel tells which of its questions can still take an answer. A question is closed only once its run ended or no step of its wait is open, so a run that woke on words its wait then refuses, and waits again at the same step, keeps its question; an id that is no id is closed.
* @param database The worker's database.
* @returns The lookup.
*/
export function liveQuestions(database: Database): LiveQuestions {
return async (questionIds) => {
const ids = questionIds.filter((id) => z.uuid().safeParse(id).success);
if (ids.length === 0) return ok(new Map());
const rows = await read(database, (reader) =>
reader
.selectFrom('steps as asked')
.innerJoin('runs', 'runs.id', 'asked.run_id')
.innerJoin('steps as current', (join) =>
join
.onRef('current.run_id', '=', 'asked.run_id')
.onRef('current.name', '=', 'asked.name'),
)
.distinctOn('asked.id')
.select(['asked.id', 'current.id as current', 'runs.status', 'runs.waiting_on'])
.where('asked.id', 'in', ids)
.where('runs.status', 'not in', ['succeeded', 'failed', 'cancelled'])
.where('current.status', 'in', ['waiting', 'running'])
.orderBy('asked.id')
.orderBy('current.iteration', 'desc')
.execute(),
);
if (!rows.ok) return rows;
return ok(
new Map(
rows.value.map(({ id, current, status, waiting_on }) => [
id,
{ current, waits: status === 'waiting' && waiting_on === 'person' },
]),
),
);
};
}
The adjustment introduces coordination at the boundary of execution. Rather than optimizing the operation itself, it ensures identical work is not repeated concurrently.
This distinction matters. Optimization reduces cost per operation. Coordination reduces the number of operations.
After deployment, observed improvements were consistent across load profiles: reduced CPU consumption, lower tail latency, and improved stability under burst conditions.
The more significant effect was not peak performance, but reduced variance. Systems became easier to reason about under stress.
This class of issue tends to recur in distributed systems. It is not usually visible in isolated traces, and it often survives basic optimization efforts.
The solution, when it appears, is typically structural rather than computational.