Stop waiting on the network eleven times per page

The app got slower as pages grew, and the reason was not the queries. It
was their number.

A transaction is pinned to one connection, and a connection runs queries
one after another. Every Promise.all in a withUser block looked like
concurrency and was a queue. Measured against the real database: the
round trip is ~36 ms, ten trivial `select 1` over one connection take
343 ms, over ten connections 39 ms. Nothing here is slow — the whole
dashboard payload is under 200 kB, and every table is around a thousand
rows.

More connections is the wrong answer: the RLS session context is per
transaction, so parallel reads mean parallel transactions, and those
multiply the connections the database will grant. Fewer round trips
instead. Postgres will return each sub-select as its own JSON column of
one result.

Per page view, counting the transaction frame:

  shell (paid by every page)  10 → 4
  overview                    14 → 5
  employee file               14 → 7
  employee list                8 → 6

The overview plus its shell went from 24 round trips to 9 — about 860 ms
of pure waiting down to about 320 ms.

The one trap is documented where it bites: inside json_agg, Postgres
formats values itself and the driver's parsers (lib/db/pool.ts) never
see them. Dates, numerics and uuids come out identical; timestamptz does
not — "+00:00" where the driver gives "…Z". Timestamps are compared as
strings in lib/history.ts to decide what happened later, and those two
forms sort against each other wrongly. Every timestamptz in a bundled
query therefore goes through zeitstempel(), which was checked
character-for-character against the driver.

Four loaders moved out of their pages into lib/ so the number of round
trips can be measured without building a React tree, and so the new path
could be held against the old one field by field: same rows, same order,
same strings, for the overview and for four employee files chosen to
differ (with history, a chief, a planned entry, one with dependents).

withUser now counts the queries in each transaction and says so in
development past a threshold. Without that, this grows back: each new
tile brings its own query, and nobody notices until everybody does.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-16 19:31:36 +02:00
parent 6957b95a97
commit 91b2b3406b
13 changed files with 753 additions and 336 deletions

View File

@@ -1,11 +1,21 @@
import type { Tx } from "./db";
import type { Database } from "./supabase/types";
import { jsonArrayFrom, zeitstempel } from "./db/json";
import { fmtName } from "./format";
import type { OrgEb } from "./org";
import type { Database } from "./supabase/types";
export type OpenNote = Database["public"]["Tables"]["employee_notes"]["Row"] & {
employeeName: string;
};
/** Was die Teilabfrage liefert: die Notiz plus den Namen aus dem Join. */
export type NotizZeile = Omit<Database["public"]["Tables"]["employee_notes"]["Row"], "created_at" | "done_at"> & {
created_at: string;
done_at: string | null;
first_name: string | null;
last_name: string | null;
};
// „Meine Notizen" (Topbar-Glocke): das geteilte, mitarbeiterübergreifende
// Postfach aller noch nicht erledigten HR-Notizen — unabhängig davon, wer sie
// verfasst hat oder zu wem sie gehören (mit Nutzer abgestimmt).
@@ -13,16 +23,39 @@ export type OpenNote = Database["public"]["Tables"]["employee_notes"]["Row"] & {
// Früher zwei Abfragen, in JavaScript zusammengeführt, weil die API-Schicht
// für eine einzelne verschachtelte Abfrage keine Verknüpfung anbot. Am
// direkten Zugang ist es schlicht ein Join.
export async function loadOpenNotes(tx: Tx): Promise<OpenNote[]> {
const rows = await tx
/**
* Die offenen Notizen als *Teilabfrage* — zum Einhängen in die eine Abfrage,
* die eine Seite ohnehin stellt (lib/db/json.ts).
*
* Die beiden Zeitstempel gehen durch zeitstempel(): innerhalb von JSON
* formatiert Postgres sie anders als der Treiber es sonst täte, und der
* Unterschied fällt erst beim Vergleichen auf.
*/
export function offeneNotizenAbfrage(eb: OrgEb) {
return eb
.selectFrom("employee_notes as n")
.leftJoin("employees as e", "e.id", "n.employee_id")
.selectAll("n")
.select(["e.first_name", "e.last_name"])
.select([
"n.id",
"n.employee_id",
"n.author_user_id",
"n.author_name",
"n.category",
"n.note_text",
"n.due_date",
"n.done",
"n.done_by",
"e.first_name",
"e.last_name",
])
.select((x) => [zeitstempel(x.ref("n.created_at")).as("created_at"), zeitstempel(x.ref("n.done_at")).as("done_at")])
.where("n.done", "=", false)
.orderBy("n.created_at", "desc")
.execute();
.orderBy("n.created_at", "desc");
}
/** Der reine Teil: aus den Zeilen die Notizen mit lesbarem Namen. */
export function baueOffeneNotizen(rows: NotizZeile[]): OpenNote[] {
return rows.map((row) => {
const { first_name, last_name, ...note } = row;
return {
@@ -31,3 +64,10 @@ export async function loadOpenNotes(tx: Tx): Promise<OpenNote[]> {
};
});
}
export async function loadOpenNotes(tx: Tx): Promise<OpenNote[]> {
const { notes } = await tx
.selectNoFrom((eb) => [jsonArrayFrom(offeneNotizenAbfrage(eb)).as("notes")])
.executeTakeFirstOrThrow();
return baueOffeneNotizen(notes as NotizZeile[]);
}