From b399ffaca922e30cb9382fb08d3b794d49edfb2d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 5 Jul 2026 10:10:23 +0000 Subject: [PATCH] perf: Remove eager user joins from Document default scope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every Document query previously eager-loaded the createdBy and updatedBy User associations via the default scope, paying for two LEFT JOINs to the wide users table on every query — including the many policy checks, background tasks, and command paths that never read them. The associations are now resolved only where needed: - The document presenter loads users through a new request-scoped DataLoader (server/utils/loaders.ts), so a page of documents resolves all creator/updater rows in a single batched query, memoized per request. When no request context is available a shared batch-only (non-caching) loader is used instead. - Consumers that only needed the actor ID now read the FK column directly (lastModifiedById) instead of the joined row. - Single-document consumers (revisions.info, JSON export, Slack processor, unfurls) load the association explicitly or lazily. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_012rKcnTfSLGCzcMq4yvmopj --- package.json | 1 + .../slack/server/processors/SlackProcessor.ts | 9 ++- server/models/Document.ts | 27 +------ server/presenters/document.ts | 14 +++- server/presenters/unfurl.ts | 23 ++++-- .../DocumentPublishedNotificationsTask.ts | 2 +- server/queues/tasks/ExportJSONTask.ts | 6 ++ .../tasks/RevisionCreatedNotificationsTask.ts | 2 +- server/routes/api/revisions/revisions.ts | 6 ++ server/utils/loaders.test.ts | 74 +++++++++++++++++++ server/utils/loaders.ts | 67 +++++++++++++++++ yarn.lock | 8 ++ 12 files changed, 201 insertions(+), 38 deletions(-) create mode 100644 server/utils/loaders.test.ts create mode 100644 server/utils/loaders.ts diff --git a/package.json b/package.json index a257db2698..bfec38edc5 100644 --- a/package.json +++ b/package.json @@ -125,6 +125,7 @@ "copy-to-clipboard": "^3.3.3", "core-js": "^3.49.0", "crypto-js": "^4.2.0", + "dataloader": "^2.2.3", "date-fns": "^3.6.0", "dd-trace": "^5.109.0", "diff": "^5.2.2", diff --git a/plugins/slack/server/processors/SlackProcessor.ts b/plugins/slack/server/processors/SlackProcessor.ts index 50a81b47a5..d4172fa56b 100644 --- a/plugins/slack/server/processors/SlackProcessor.ts +++ b/plugins/slack/server/processors/SlackProcessor.ts @@ -124,10 +124,13 @@ export default class SlackProcessor extends BaseProcessor { if (!integration) { return; } - let text = `${document.updatedBy.name} updated "${document.titleWithDefault}"`; - + let text: string; if (event.name === "documents.publish") { - text = `${document.createdBy.name} published "${document.titleWithDefault}"`; + const createdBy = await document.$get("createdBy", { paranoid: false }); + text = `${createdBy?.name} published "${document.titleWithDefault}"`; + } else { + const updatedBy = await document.$get("updatedBy", { paranoid: false }); + text = `${updatedBy?.name} updated "${document.titleWithDefault}"`; } await fetch(integration.settings.url, { diff --git a/server/models/Document.ts b/server/models/Document.ts index 09eb7daab5..e083d23724 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -98,18 +98,6 @@ type AdditionalFindOptions = { // @ts-expect-error Type 'Literal' is not assignable to type 'string | ProjectionAlias'. @DefaultScope(() => ({ - include: [ - { - model: User, - as: "createdBy", - paranoid: false, - }, - { - model: User, - as: "updatedBy", - paranoid: false, - }, - ], where: { publishedAt: { [Op.ne]: null, @@ -146,18 +134,9 @@ type AdditionalFindOptions = { include: [], }, }, - withDrafts: { - include: [ - { - association: "createdBy", - paranoid: false, - }, - { - association: "updatedBy", - paranoid: false, - }, - ], - }, + // an empty scope that overrides the default scope, allowing drafts to be + // included in queries. + withDrafts: {}, withViews: (userId: string) => { if (!userId) { return {}; diff --git a/server/presenters/document.ts b/server/presenters/document.ts index 6f93f7fa42..60ddf7221a 100644 --- a/server/presenters/document.ts +++ b/server/presenters/document.ts @@ -5,6 +5,7 @@ import type { Document } from "@server/models"; import FileOperation from "@server/models/FileOperation"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import type { APIContext } from "@server/types"; +import { loaders } from "@server/utils/loaders"; import presentUser from "./user"; type Options = { @@ -107,8 +108,17 @@ async function presentDocument( res.isCollectionDeleted = await document.isCollectionDeleted(); res.collectionId = document.collectionId; res.parentDocumentId = document.parentDocumentId; - res.createdBy = presentUser(document.createdBy); - res.updatedBy = presentUser(document.updatedBy); + // The user associations are no longer eager-loaded with every document + // query; resolve them here through a request-scoped, batching loader so a + // page of documents results in a single users query. + const createdBy = + document.createdBy ?? + (await loaders(ctx).users.load(document.createdById)); + const updatedBy = + document.updatedBy ?? + (await loaders(ctx).users.load(document.lastModifiedById)); + res.createdBy = createdBy ? presentUser(createdBy) : undefined; + res.updatedBy = updatedBy ? presentUser(updatedBy) : undefined; res.collaboratorIds = document.collaboratorIds ?? []; res.templateId = document.templateId; res.insightsEnabled = document.insightsEnabled; diff --git a/server/presenters/unfurl.ts b/server/presenters/unfurl.ts index caa88daebd..aae3ded259 100644 --- a/server/presenters/unfurl.ts +++ b/server/presenters/unfurl.ts @@ -91,9 +91,9 @@ const presentGroup = async ( }; }; -const presentDocument = ( +const presentDocument = async ( data: UnfurlData -): UnfurlResponse[UnfurlResourceType.Document] => { +): Promise => { const document: Document = data.document; const viewer: User | undefined = data.viewer; const url: string | undefined = data.url; @@ -104,7 +104,7 @@ const presentDocument = ( title: document.titleWithDefault, summary: document.getSummary(), lastActivityByViewer: viewer - ? presentLastActivityInfoFor(document, viewer) + ? await presentLastActivityInfoFor(document, viewer) : undefined, }; }; @@ -172,13 +172,16 @@ const presentLastViewedInfoFor = async (user: User, document: Document) => { return info; }; -const presentLastActivityInfoFor = (document: Document, viewer: User) => { +const presentLastActivityInfoFor = async ( + document: Document, + viewer: User +) => { const locale = dateLocale(viewer.language); const wasUpdated = document.createdAt !== document.updatedAt; let info: string; if (wasUpdated) { - const lastUpdatedByViewer = document.updatedBy.id === viewer.id; + const lastUpdatedByViewer = document.lastModifiedById === viewer.id; if (lastUpdatedByViewer) { info = t("You updated {{ timeAgo }}", { timeAgo: formatDistanceToNowStrict(document.updatedAt, { @@ -188,8 +191,11 @@ const presentLastActivityInfoFor = (document: Document, viewer: User) => { ...opts(viewer), }); } else { + const updatedBy = + document.updatedBy ?? + (await document.$get("updatedBy", { paranoid: false })); info = t("{{ user }} updated {{ timeAgo }}", { - user: document.updatedBy.name, + user: updatedBy?.name, timeAgo: formatDistanceToNowStrict(document.updatedAt, { addSuffix: true, locale, @@ -208,8 +214,11 @@ const presentLastActivityInfoFor = (document: Document, viewer: User) => { ...opts(viewer), }); } else { + const createdBy = + document.createdBy ?? + (await document.$get("createdBy", { paranoid: false })); info = t("{{ user }} created {{ timeAgo }}", { - user: document.createdBy.name, + user: createdBy?.name, timeAgo: formatDistanceToNowStrict(document.createdAt, { addSuffix: true, locale, diff --git a/server/queues/tasks/DocumentPublishedNotificationsTask.ts b/server/queues/tasks/DocumentPublishedNotificationsTask.ts index 1851c41855..259054d566 100644 --- a/server/queues/tasks/DocumentPublishedNotificationsTask.ts +++ b/server/queues/tasks/DocumentPublishedNotificationsTask.ts @@ -131,7 +131,7 @@ export default class DocumentPublishedNotificationsTask extends BaseTask { + const contextOne = {} as APIContext; + const contextTwo = {} as APIContext; + + it("should return the same instance for the same context", () => { + expect(loaders(contextOne)).toBe(loaders(contextOne)); + }); + + it("should return different instances for different contexts", () => { + expect(loaders(contextOne)).not.toBe(loaders(contextTwo)); + }); + + it("should return a shared instance when no context is available", () => { + expect(loaders()).toBe(loaders()); + expect(loaders()).not.toBe(loaders(contextOne)); + }); + + describe("users", () => { + it("should batch concurrent loads into a single query", async () => { + const [userOne, userTwo] = await Promise.all([ + buildUser(), + buildUser(), + ]); + const findAll = vi.spyOn(User, "findAll"); + + const ctx = {} as APIContext; + const [loadedOne, loadedTwo] = await Promise.all([ + loaders(ctx).users.load(userOne.id), + loaders(ctx).users.load(userTwo.id), + ]); + + expect(findAll).toHaveBeenCalledTimes(1); + expect(loadedOne?.id).toEqual(userOne.id); + expect(loadedTwo?.id).toEqual(userTwo.id); + findAll.mockRestore(); + }); + + it("should memoize loads within the same context", async () => { + const user = await buildUser(); + const findAll = vi.spyOn(User, "findAll"); + + const ctx = {} as APIContext; + await loaders(ctx).users.load(user.id); + await loaders(ctx).users.load(user.id); + + expect(findAll).toHaveBeenCalledTimes(1); + findAll.mockRestore(); + }); + + it("should load deleted users", async () => { + const teammate = await buildUser(); + const user = await buildUser({ teamId: teammate.teamId }); + await user.destroy(); + + const ctx = {} as APIContext; + const loaded = await loaders(ctx).users.load(user.id); + expect(loaded?.id).toEqual(user.id); + expect(loaded?.deletedAt).toBeTruthy(); + }); + + it("should return null for unknown IDs", async () => { + const ctx = {} as APIContext; + const loaded = await loaders(ctx).users.load( + "00000000-0000-0000-0000-000000000000" + ); + expect(loaded).toBeNull(); + }); + }); +}); diff --git a/server/utils/loaders.ts b/server/utils/loaders.ts new file mode 100644 index 0000000000..1ba3426437 --- /dev/null +++ b/server/utils/loaders.ts @@ -0,0 +1,67 @@ +import DataLoader from "dataloader"; +import { User } from "@server/models"; +import type { APIContext } from "@server/types"; + +/** + * Batches and de-duplicates user lookups by primary key. Deleted users are + * included (paranoid: false) to match presentation requirements — documents + * created or updated by since-deleted users must still present them. + * + * @param userIds the user IDs to load. + * @return an array of users (or null for missing IDs) in the same order as the input. + */ +async function batchUsers( + userIds: readonly string[] +): Promise> { + const users = await User.findAll({ + where: { + id: [...userIds], + }, + paranoid: false, + }); + const usersById = new Map(users.map((user) => [user.id, user])); + return userIds.map((id) => usersById.get(id) ?? null); +} + +/** + * A set of DataLoader instances scoped to a single request. Loads made within + * the same event loop frame are coalesced into one database query, and results + * are memoized for the lifetime of the request. + */ +export class RequestLoaders { + /** Loads users by ID, including deleted users. */ + users: DataLoader; + + constructor(options?: { cache?: boolean }) { + this.users = new DataLoader(batchUsers, { cache: options?.cache ?? true }); + } +} + +const requestLoaders = new WeakMap(); + +// Used when no request context is available (background workers, websockets). +// Caching is disabled so nothing is memoized across unrelated operations — +// this instance only coalesces loads made in the same event loop frame. +const sharedLoaders = new RequestLoaders({ cache: false }); + +/** + * Returns the set of DataLoaders for the given request context, creating it + * on first access. Loaders are garbage-collected with the request. When no + * context is available a shared, batch-only (non-caching) instance is + * returned instead. + * + * @param ctx the API context of the current request, if any. + * @return the loaders for this request. + */ +export function loaders(ctx?: APIContext): RequestLoaders { + if (!ctx) { + return sharedLoaders; + } + + let existing = requestLoaders.get(ctx); + if (!existing) { + existing = new RequestLoaders(); + requestLoaders.set(ctx, existing); + } + return existing; +} diff --git a/yarn.lock b/yarn.lock index 78ee08d708..9caea58228 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10045,6 +10045,13 @@ __metadata: languageName: node linkType: hard +"dataloader@npm:^2.2.3": + version: 2.2.3 + resolution: "dataloader@npm:2.2.3" + checksum: 10c0/9b9a056fbc863ca86da87d59e053e871e263b4966aa4d55e40d61a65e96815fae5530ca220629064ca5f8e3000c0c4ec93292e170c38ff393fb34256b4d7c1aa + languageName: node + linkType: hard + "date-fns@npm:^2.30.0": version: 2.30.0 resolution: "date-fns@npm:2.30.0" @@ -15663,6 +15670,7 @@ __metadata: copy-to-clipboard: "npm:^3.3.3" core-js: "npm:^3.49.0" crypto-js: "npm:^4.2.0" + dataloader: "npm:^2.2.3" date-fns: "npm:^3.6.0" dd-trace: "npm:^5.109.0" diff: "npm:^5.2.2"