Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚡️ perf: serve dashboard message totals from a planner estimate instead of a full COUNT (#19223)

Arvin Xu2f2e939df6d6
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index b9a3e8d6c67..3d092e66bc8 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -248,9 +248,17 @@ export const messageRouter = router({
return ctx.messageModel.queryAll(input);
}),
- count: messageProcedure.input(messageAnalyticsSchema.optional()).query(async ({ ctx, input }) => {
- return ctx.messageModel.count(input);
- }),
+ count: messageProcedure
+ .input(messageAnalyticsSchema.extend({ approximate: z.boolean().optional() }).optional())
+ .query(async ({ ctx, input }) => {
+ const { approximate, ...filters } = input ?? {};
+
+ // Dashboard totals tolerate an estimate; an exact COUNT over a heavy
+ // account's messages takes tens of seconds.
+ if (approximate) return ctx.messageModel.countApproximate(filters);
+
+ return ctx.messageModel.count(filters);
+ }),
/**
* Count messages grouped by topic (server-side GROUP BY), sorted by count
diff --git a/packages/database/src/models/__tests__/messages/message.stats.test.ts b/packages/database/src/models/__tests__/messages/message.stats.test.ts
index d7194154205..4777e6a6446 100644
--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts
@@ -176,6 +176,61 @@ describe('MessageModel Statistics Tests', () => {
});
});
+ describe('countApproximate', () => {
+ it('returns the exact count when under the cap', async () => {
+ await serverDB.insert(messages).values([
+ { id: 'approx-1', userId, role: 'user', content: 'message 1' },
+ { id: 'approx-2', userId, role: 'user', content: 'message 2' },
+ { id: 'approx-3', userId: otherUserId, role: 'user', content: 'message 3' },
+ ]);
+
+ const result = await messageModel.countApproximate();
+
+ expect(result).toBe(2);
+ });
+
+ it('excludes agent-share visitor messages like count does', async () => {
+ await serverDB.insert(topics).values({
+ id: 'topic-visitor-approx',
+ userId,
+ senderId: 'visitor-user-y',
+ title: 'visitor topic',
+ });
+ await serverDB.insert(messages).values([
+ {
+ id: 'approx-visitor-1',
+ userId,
+ role: 'user',
+ content: 'visitor message',
+ topicId: 'topic-visitor-approx',
+ },
+ { id: 'approx-creator-1', userId, role: 'user', content: 'creator message' },
+ ]);
+
+ const result = await messageModel.countApproximate();
+
+ expect(result).toBe(1);
+ });
+
+ it('falls back to a planner estimate once past the cap', async () => {
+ await serverDB.insert(messages).values(
+ Array.from({ length: 8 }, (_, i) => ({
+ id: `approx-cap-${i}`,
+ userId,
+ role: 'user',
+ content: `message ${i}`,
+ })),
+ );
+
+ const result = await messageModel.countApproximate(undefined, { cap: 5 });
+
+ // The estimate itself depends on planner statistics; what must hold is
+ // that it never reports fewer rows than the capped scan already saw.
+ expect(result).toBeGreaterThanOrEqual(6);
+ expect(Number.isFinite(result)).toBe(true);
+ });
+ });
+
describe('genId', () => {
it('should generate unique message IDs', () => {
const model = new MessageModel(serverDB, userId);
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 57bddf77145..ff82a753318 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -2877,6 +2877,63 @@ export class MessageModel {
return result[0].count;
};
+ /**
+ * Approximate variant of {@link count} for dashboard totals. An exact
+ * COUNT over `messages` heap-fetches every row the user owns (tens of
+ * seconds for accounts with 100k+ messages), which no stats card needs.
+ *
+ * Strategy: ask the planner for a row estimate first (EXPLAIN, a few ms).
+ * Accounts the estimate marks as clearly heavy get the estimate, rounded
+ * to 3 significant digits so the number reads as the approximation it is.
+ * Everyone else — the vast majority — gets an exact count capped at
+ * `cap + 1` rows, which is cheap at that size. A user the planner
+ * underestimates still can't get a value below what the capped scan saw.
+ * Parallel workers are disabled for the EXPLAIN because parallel plans
+ * report per-worker row estimates, not totals.
+ */
+ countApproximate = async (
+ params?: MessageAnalyticsFilters,
+ { cap = 10_000 }: { cap?: number } = {},
+ ): Promise<number> => {
+ const where = genWhere(this.analyticsConditions(params));
+
+ const roundEstimate = (estimate: number) => {
+ const magnitude = 10 ** Math.max(0, Math.floor(Math.log10(estimate)) - 2);
+ return Math.round(estimate / magnitude) * magnitude;
+ };
+
+ let estimate: number | undefined;
+ try {
+ const estimateQuery = this.db.select({ id: messages.id }).from(messages).where(where);
+ const result = await this.db.transaction(async (trx) => {
+ await trx.execute(sql`SET LOCAL max_parallel_workers_per_gather = 0`);
+ return trx.execute(sql`EXPLAIN (FORMAT JSON) ${estimateQuery.getSQL()}`);
+ });
+ const rawPlan = result.rows[0]?.['QUERY PLAN'];
+ const parsed = typeof rawPlan === 'string' ? JSON.parse(rawPlan) : rawPlan;
+ const parsedRows = Number((parsed as any)?.[0]?.['Plan']?.['Plan Rows']);
+ if (Number.isFinite(parsedRows)) estimate = parsedRows;
+ } catch (error) {
+ // Best-effort — fall through to the capped exact count, but surface the
+ // degradation: past-cap accounts will all read as `cap + 1` until fixed.
+ console.error('countApproximate: planner estimate failed, using capped count only:', error);
+ }
+
+ if (estimate !== undefined && estimate > cap * 2) return roundEstimate(estimate);
+
+ const cappedRows = this.db
+ .select({ id: messages.id })
+ .from(messages)
+ .where(where)
+ .limit(cap + 1)
+ .as('capped');
+ const capped = await this.db.select({ count: count() }).from(cappedRows);
+ const exact = capped[0].count;
+ if (exact <= cap) return exact;
+
+ return Math.max(estimate === undefined ? 0 : roundEstimate(estimate), exact);
+ };
+
/**
* Count matching messages grouped by topic, sorted by count desc.
* Topics without a `topicId` are excluded. Pushes the GROUP BY to the DB
diff --git a/src/features/Settings/stats/features/overview/TotalMessages.tsx b/src/features/Settings/stats/features/overview/TotalMessages.tsx
index b3b0fcfcbe8..cf9fbe71658 100644
--- a/src/features/Settings/stats/features/overview/TotalMessages.tsx
+++ b/src/features/Settings/stats/features/overview/TotalMessages.tsx
@@ -15,10 +15,19 @@ import TotalCard from './ShareButton/TotalCard';
const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare }) => {
const { t } = useTranslation('auth');
- const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.messages(), async () => ({
- count: await messageService.countMessages(),
- prevCount: await messageService.countMessages({ endDate: lastMonth().format('YYYY-MM-DD') }),
- }));
+ const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.messages(), async () => {
+ // The total is a planner estimate, but the last-month baseline is derived
+ // from it with an exact count of this month's messages (cheap — date-
+ // bounded) rather than a second estimate: without multicolumn statistics
+ // the planner can badly misjudge a user×date predicate, which would turn
+ // the growth percentage next to the number into noise.
+ const count = await messageService.countMessages({ approximate: true });
+ const sinceLastMonth = await messageService.countMessages({
+ startDate: lastMonth().add(1, 'day').format('YYYY-MM-DD'),
+ });
+
+ return { count, prevCount: Math.max(count - sinceLastMonth, 0) };
+ });
if (inShare)
return (
diff --git a/src/features/User/DataStatistics.tsx b/src/features/User/DataStatistics.tsx
index 1bfaed936f6..d1ef7087563 100644
--- a/src/features/User/DataStatistics.tsx
+++ b/src/features/User/DataStatistics.tsx
@@ -58,7 +58,8 @@ const DataStatistics = memo<Omit<FlexboxProps, 'children'>>(({ style, ...rest })
const { data: { messages, messagesToday } = {}, isLoading: messagesLoading } = useClientDataSWR(
statsKeys.countMessages(),
async () => ({
- messages: await messageService.countMessages(),
+ messages: await messageService.countMessages({ approximate: true }),
+ // today's delta stays exact — it is small, cheap, and shown as "+N"
messagesToday: await messageService.countMessages({
startDate: today().format('YYYY-MM-DD'),
}),
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 38a18ee5991..d03a010c669 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -185,6 +185,7 @@ export class MessageService {
};
countMessages = async (params?: {
+ approximate?: boolean;
endDate?: string;
range?: [string, string];
startDate?: string;