Skip to content

perf(auth): resolving the viewer takes one database round trip, not three - #772

Merged
allisonmahmood merged 8 commits into
mainfrom
perf/748-resolve-one-statement
Oct 18, 2026
Merged

allisonmahmood merged 8 commits into
mainfrom
perf/748-resolve-one-statement

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Every viewer resolve cost 3 platform round trips:

  • a claim-refresh UPDATE users … RETURNING, which usually changed nothing;
  • the SELECT users it then fell back to;
  • Companies.findById.

A tier 2 call resolves the viewer at admission, on every directory reauthorize, in every document check, on stream open and on every subscription POST. That's 2 resolves per query, 1 per mutation and 3 per re-run.

Now a resolve whose claims haven't changed (almost every resolve) is one statement. Every resolve stays where it was and still reads current state; nothing is cached.

The fix

Users.refreshClaims returns the user and their company, and reads before it writes:

  1. One lock-free read:
    SELECT u.*, c.handle AS "companyHandle", c.name AS "companyName"
    FROM (SELECT <user columns> FROM users WHERE clerk_user_id = $1) u
    LEFT JOIN companies c ON c.id = u."companyId"
    No row means no user, as before. If the stored email and name already equal the normalized claims, this row is the answer. The normalization and the displayName fallback are unchanged.
  2. Claims differ: main's UPDATE users … WHERE … IS DISTINCT FROM … RETURNING, verbatim. It waits on any lock holder and returns the row as that holder left it. The company is then read after it, as main did, even when its id didn't change: a company renamed during the wait comes back renamed.
    • If the update changes nothing because a concurrent refresh already wrote these claims, the read from step 1 runs again with a fresh snapshot and answers instead.
    • A missing company row still comes back as null, and resolveViewer dies with User company is missing.

resolveViewer no longer needs Companies. The /join redirect, the deactivation 403 page and the Viewer it returns are unchanged. Door stops capturing Companies, and the runtime's Effect.Services<typeof resolveViewer> follows on its own.

Why it's equivalent

  • Every path that waits on a lock still goes through the same statements as before and returns the authority as it stood after the wait. That covers a deactivation, demotion, company move or company rename that an admin commits while this resolve's write waits.
  • The unchanged path didn't wait before either. The old no-op UPDATE's condition was false on its snapshot, so Postgres skipped the row without locking it. Its fallback SELECT ran one round trip later than the new read does. That difference is a request arriving a moment earlier, not a lost guarantee.
  • What round 1 got wrong (thanks, Sol). It answered from one data-modifying CTE whose SELECT read the snapshot from before its own UPDATE's lock wait. A resolve with changed claims that waited on an admin's deactivation, demotion or move then returned the authority from before that change. Doored POST handlers act on that viewer without resolving again. The fresh fallback has no single-statement equivalent either: when queued behind an identical refresh, a UNION ALL fallback still reads the old snapshot and misses a company created by the lock holder.
  • Isolation. The platform pool sets none, and no caller wraps a resolve in a transaction. Each statement runs on its own under READ COMMITTED, as before.
  • Locks. No new row locks. Only the old UPDATE takes one, and only when the claims changed. The first read takes none, so unchanged claims never wait behind an admin's transaction; a test pins that.

Tests

On a real Postgres, against the migrated test template:

  • RequireSession.test.ts (new). It counts statements with Statement.CurrentTransformer.
    • Unchanged claims and an unknown user resolve in 1 statement, and changed claims in 3: the read, the write and the company after it.
    • A deactivated user gets the same 403 page in 1 statement.
    • A missing company dies with the same defect. The test bypasses the foreign key with session_replication_role = replica, inside a rolled-back transaction.
  • Users.test.ts:
    • Admin change during the wait. Three admin changes are each held uncommitted while a refresh with new claims waits on the row. The refresh answers the role, deactivation and company as committed, and equals the stored row. The changes:
      • a demotion together with a rename of the user's company;
      • a deactivation;
      • a move to a company created by the same transaction.
    • Unchanged claims never wait. While a deactivation still holds the row, a refresh with matching claims returns the active row it can see within a 5 s bound and writes nothing. A locking first read times out here.
    • Sol's three-session queue. A deactivation is held while two identical refreshes queue on it. When it commits, either refresh may take the row first, so the test doesn't depend on which. One writes the claims; the other writes nothing, and its fresh read returns the deactivation. Every wait in these cases is bounded at 3 s and fails naming the step.
    • The existing same-claims race now checks the whole answer (stored row and company) and a single write.
    • The existing claim-refresh tests check the company too. Their audit-trigger "no write for unchanged claims" checks still hold.

The two lock-wait tests fail on round 1's CTE, and on the RETURNING/UNION ALL variant: there the queued refresh misses the deactivation, and the moved-to company comes back null. The rename case fails on round 2, which reused the first read's company.

Numbers

Platform statements per call on pnpm dev up brightline, as the admin on the New Business board. The baseline is main at #771, after its echo fix. Counts come from Postgres's statement log (log_min_duration_statement = 0), sliced between marker statements. Queries and mutations ran 5 times; streams ran 3 opens × 3 writes. Every repeat matched.

Per call main this PR resolves
Query deals.board (one-shot) 14 10 2
Mutation deals.addNote 18 16 1
Stream open 7 5 1
Subscription POST and its first run 24 16 4
Write + re-run 41 33 4 (1 mutation, 3 re-run)

That's −2 per resolve: query −4, mutation −2, re-run −6.

When the claims changed (the stored name edited, so the next resolve writes), that resolve costs 3 statements here and 2 on main, and a query in that state costs 12 here and 13 on main. The extra statement buys a fresh company after the write, and the path only runs when someone's name or email changes in Clerk. If a concurrent refresh already wrote the claims, the changed path costs 3 on both: the read, the empty write and the fresh read here; the write, the fallback read and the company on main.

Company statements are unchanged. These totals come from pnpm dev's default executor, which runs tier 2 without the fleet, so they leave out the fleet's admission and release statements that #748's counts include. The resolve statements are the same on both executors.

On the same instance:

  • sign-in works;
  • after an account switch, a call still pinned to the old principal gets principal_changed, and the new one's me answers;
  • a person without a company is sent to /join;
  • a deactivated member gets the 403 page on the portal and on a patch address, and access_denied on a runtime call; reactivating restores access.

Part of #748.

Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.

…hree

Users.refreshClaims answers the user and their company in one statement: a
data-modifying CTE writes the claims only when they changed, and the SELECT
joins the company. resolveViewer no longer reads Companies.

Part of #748.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added area:server Touches the server area size:m 100-500 changed lines labels Oct 18, 2026
allisonmahmood and others added 6 commits October 18, 2026 18:01
The single-statement refresh answered every column but email and name from
its snapshot. A resolve with changed claims that waited on an admin's
uncommitted deactivation, demotion or company move then answered the
authority from before that change; the old UPDATE ... RETURNING and its
fresh fallback read answered the row as the change left it.

refreshClaims now reads the user and company in one lock-free statement and
returns when the claims already match. Otherwise it runs the old UPDATE ...
RETURNING unchanged, falls back to a fresh read when a concurrent refresh
already wrote the claims, and reads the company again only when it moved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… claims never wait

A changed-claims resolve reused the company from its first read when the
company id didn't move, so a company renamed while the write waited came back
with its old name. It now reads the company after every write, as main did.

Tests pin the rename during a held demotion, and that a refresh with
unchanged claims answers while an admin's change still holds the row.
Comments say one read for unchanged claims rather than one statement for
every resolve.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…h waiter wins

When a held deactivation commits, Postgres wakes both queued refreshes and
either may take the row first. The queued case held the first refresh open
and then waited for the second to queue behind it; when the second won
instead, nothing waited again and the test timed out (CI, Node 22).

Both refreshes now run on their own and the case asserts what holds either
way: one writes the claims, the other writes nothing, and both answer the
deactivation. Every wait is bounded at three seconds and fails naming the
step, or as soon as a transaction it waits on ends first, instead of
hanging until vitest's timeout; held transactions roll back with the case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood merged commit dd4bb20 into main Oct 18, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the perf/748-resolve-one-statement branch October 18, 2026 19:21
allisonmahmood added a commit that referenced this pull request Oct 19, 2026
…ng Reconnecting (#783)

Release 14's What's new entry, written from \`7694bab\`. It covers
everything merged since release 13's \`through\` (\`c9b8fc4\`), and sets
the \`patchy\` release to \`0.14.0\` (\`packages/patchy/package.json\`
and \`CURRENT_RELEASE\`).

| Change | PRs |
| --- | --- |
| Improved: Tools with server code answer faster | #756, #764, #768,
#769, #771, #772, #773, #775, #778 |
| Improved: Your company's tools and pages open sooner | #759, #761,
#766, #770 |
| Fixed: Tools stop flashing Reconnecting while they load | #755, #776,
#780 |
| Improved: Publishing is quicker | #729 |
| Improved: New tools start with a tidy layout | #763 |
| Improved: Your usual is easier to scan | #721 |
| Fixed: A page that isn't there says what to do | #762 |
| Fixed: A logo Patchy can't read is refused, not a crash | #728 |
| Behind the scenes: richer logs for live data | #758 |

#720 is release 13's own entry, so it's left out.

Made by Claude Opus 5.5 via Claude Code.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:server Touches the server area size:m 100-500 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant