Skip to content

Email for professionals and teams

perf: covering index for folder navigation listing

ssthormess34a9a838bbca
diff --git a/drizzle/migrations/0076_add_navigation_cover_index.sql b/drizzle/migrations/0076_add_navigation_cover_index.sql
new file mode 100644
index 0000000..cb08aca
--- /dev/null
+++ b/drizzle/migrations/0076_add_navigation_cover_index.sql
@@ -0,0 +1,12 @@
+-- The navigation endpoint streams every row in a folder ordered by
+-- created_at desc, selecting id/read/direction/thread_id with filters on
+-- mailbox/status/folder/direction/snoozed_until. messages_inbox_page_idx
+-- supplies the sort order but lacks direction/read/thread_id/snoozed_until,
+-- so the plan was covering-sort + a table lookup per row: ~54s for a 155k
+-- inbox. This index carries the payload columns in the tail, making the
+-- scan fully covering: ~400ms for the same folder.
+-- Column order matters: direction/read/thread_id/snoozed_until go AFTER
+-- created_at/id. Putting direction between folder_id and created_at would
+-- break ordering for queries that do not filter on direction (the plain
+-- inbox list), forcing a temp b-tree over every matching row.
+CREATE INDEX IF NOT EXISTS `messages_nav_cover_idx` ON `messages` (`mailbox_id`, `status`, `folder_id`, `created_at` DESC, `id` DESC, `direction`, `read`, `thread_id`, `snoozed_until`);
diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json
index 9181edb..f8396cb 100644
--- a/drizzle/migrations/meta/_journal.json
+++ b/drizzle/migrations/meta/_journal.json
@@ -456,6 +456,13 @@
"when": 1792844400000,
"tag": "0073_add_undo_send_seconds",
"breakpoints": true
+ },
+ {
+ "idx": 66,
+ "version": "6",
+ "when": 1792848000000,
+ "tag": "0076_add_navigation_cover_index",
+ "breakpoints": true
}
]
}
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index 39bf658..1ce7ebc 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -328,6 +328,17 @@ export const messages = sqliteTable(
t.createdAt,
),
index("messages_mailbox_thread_key_idx").on(t.mailboxId, sql`coalesce(${t.threadId}, ${t.id})`),
+ index("messages_nav_cover_idx").on(
+ t.mailboxId,
+ t.status,
+ t.folderId,
+ sql`${t.createdAt} desc`,
+ sql`${t.id} desc`,
+ t.direction,
+ t.read,
+ t.threadId,
+ t.snoozedUntil,
+ ),
],
);