perf: Remove eager user joins from Document default scope

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012rKcnTfSLGCzcMq4yvmopj
This commit is contained in:
Claude committed 2026-07-05 10:10:23 +00:00
1 parent 1b268ee26d
commit b399ffaca9
12 files changed
+201 -38

No files matched your search

+1
View File
@@ -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",
@@ -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, {
+3 -24
View File
@@ -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 {};
+12 -2
View File
@@ -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;
+16 -7
View File
@@ -91,9 +91,9 @@ const presentGroup = async (
};
};
const presentDocument = (
const presentDocument = async (
data: UnfurlData
): UnfurlResponse[UnfurlResourceType.Document] => {
): Promise<UnfurlResponse[UnfurlResourceType.Document]> => {
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,
@@ -131,7 +131,7 @@ export default class DocumentPublishedNotificationsTask extends BaseTask<Documen
await Notification.create({
event: NotificationEventType.PublishDocument,
userId: recipient.id,
actorId: document.updatedBy.id,
actorId: document.lastModifiedById,
teamId: document.teamId,
documentId: document.id,
});
+6
View File
@@ -115,6 +115,12 @@ export default class ExportJSONTask extends ExportTask {
for (const node of nodes) {
const document = await Document.findByPk(node.id, {
includeState: true,
include: [
{
association: "createdBy",
paranoid: false,
},
],
});
if (!document) {
@@ -184,7 +184,7 @@ export default class RevisionCreatedNotificationsTask extends BaseTask<RevisionE
event: NotificationEventType.UpdateDocument,
userId: recipient.id,
revisionId: event.modelId,
actorId: document.updatedBy.id,
actorId: document.lastModifiedById,
teamId: document.teamId,
documentId: document.id,
});
+6
View File
@@ -47,6 +47,12 @@ router.post(
} else if (documentId) {
const document = await Document.findByPk(documentId, {
userId: user.id,
include: [
{
association: "updatedBy",
paranoid: false,
},
],
});
authorize(user, "listRevisions", document);
revision = Revision.buildFromDocument(document);
+74
View File
@@ -0,0 +1,74 @@
import { User } from "@server/models";
import type { APIContext } from "@server/types";
import { buildUser } from "@server/test/factories";
import { loaders } from "./loaders";
describe("loaders", () => {
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();
});
});
});
+67
View File
@@ -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<Array<User | null>> {
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<string, User | null>;
constructor(options?: { cache?: boolean }) {
this.users = new DataLoader(batchUsers, { cache: options?.cache ?? true });
}
}
const requestLoaders = new WeakMap<APIContext, RequestLoaders>();
// 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;
}
+8
View File
@@ -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"