From b4e1c2c6549b87e1fc56ad78bda60ccb7e737201 Mon Sep 17 00:00:00 2001 From: aryainguz Date: Thu, 26 Nov 2026 20:40:47 +0530 Subject: [PATCH 1/3] perf(api): optimize session storage by reducing writes to MongoDB and implement backfill for lastModified --- .changeset/session-touch-after.md | 7 ++ .../src/__tests__/sessionStore.int.test.ts | 85 +++++++++++++++++++ packages/api/src/api-app.ts | 5 +- packages/api/src/config.ts | 2 + packages/api/src/migrations.ts | 21 +++++ 5 files changed, 119 insertions(+), 1 deletion(-) create mode 100644 .changeset/session-touch-after.md create mode 100644 packages/api/src/__tests__/sessionStore.int.test.ts diff --git a/.changeset/session-touch-after.md b/.changeset/session-touch-after.md new file mode 100644 index 0000000000..65b2b31d85 --- /dev/null +++ b/.changeset/session-touch-after.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': patch +--- + +perf: stop writing the login session to MongoDB on every API request. The +session's stored expiry now moves forward at most once an hour, and a startup +backfill applies this to sessions that already exist. diff --git a/packages/api/src/__tests__/sessionStore.int.test.ts b/packages/api/src/__tests__/sessionStore.int.test.ts new file mode 100644 index 0000000000..0786f98333 --- /dev/null +++ b/packages/api/src/__tests__/sessionStore.int.test.ts @@ -0,0 +1,85 @@ +import mongoose from 'mongoose'; + +import { SESSION_TOUCH_AFTER_SEC } from '@/config'; +import { getAgent, getServer } from '@/fixtures'; +import { backfillSessionLastModified } from '@/migrations'; + +const CREDENTIALS = { + email: 'session-store@example.com', + password: 'TacoCat!2#4X', +}; + +const sessions = () => + mongoose.connection.db!.collection<{ _id: string; expires: Date }>( + 'sessions', + ); + +describe('session store writes', () => { + const server = getServer(); + + beforeAll(async () => { + await server.start(); + }); + + afterEach(async () => { + await server.clearDBs(); + }); + + afterAll(async () => { + await server.stop(); + }); + + // Registering also signs the user in. + const login = async () => { + const agent = getAgent(server); + const res = await agent + .post('/register/password') + .send({ ...CREDENTIALS, confirmPassword: CREDENTIALS.password }) + .expect(200); + const sid = decodeURIComponent(String(res.headers['set-cookie'])).match( + /connect\.sid[^=]*=s:([^.]+)/, + )![1]; + return { agent, sid }; + }; + + const storedExpiry = async (sid: string) => + (await sessions().findOne({ _id: sid }))?.expires; + + it('does not rewrite the session on every request', async () => { + const { agent, sid } = await login(); + const before = await storedExpiry(sid); + expect(before).toBeInstanceOf(Date); + + for (let i = 0; i < 3; i++) { + await agent.get('/me').expect(200); + } + + expect(await storedExpiry(sid)).toEqual(before); + }); + + it('stops rewriting sessions stored before touchAfter once backfilled', async () => { + const { agent, sid } = await login(); + await sessions().updateOne({ _id: sid }, { $unset: { lastModified: '' } }); + + await backfillSessionLastModified(); + // The first request touches it once; later ones skip. + await agent.get('/me').expect(200); + const before = await storedExpiry(sid); + await agent.get('/me').expect(200); + + expect(await storedExpiry(sid)).toEqual(before); + }); + + it('extends the session once the touch interval has passed', async () => { + const { agent, sid } = await login(); + const stale = new Date(Date.now() - (SESSION_TOUCH_AFTER_SEC + 60) * 1000); + await sessions().updateOne({ _id: sid }, { $set: { lastModified: stale } }); + const before = await storedExpiry(sid); + + await agent.get('/me').expect(200); + + expect((await storedExpiry(sid))!.getTime()).toBeGreaterThan( + before!.getTime(), + ); + }); +}); diff --git a/packages/api/src/api-app.ts b/packages/api/src/api-app.ts index cf19282309..c61f4167ad 100644 --- a/packages/api/src/api-app.ts +++ b/packages/api/src/api-app.ts @@ -43,7 +43,10 @@ const sess: session.SessionOptions & { cookie: session.CookieOptions } = { maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days }, rolling: true, - store: new MongoStore({ mongoUrl: config.MONGO_URI }), + store: new MongoStore({ + mongoUrl: config.MONGO_URI, + touchAfter: config.SESSION_TOUCH_AFTER_SEC, + }), }; app.set('trust proxy', 1); diff --git a/packages/api/src/config.ts b/packages/api/src/config.ts index 2fb4e311c3..3a8c9391c2 100644 --- a/packages/api/src/config.ts +++ b/packages/api/src/config.ts @@ -24,6 +24,8 @@ export const IS_EXPRESS_SESSION_SECRET_GENERATED = !env.EXPRESS_SESSION_SECRET || (!IS_LOCAL_APP_MODE && env.EXPRESS_SESSION_SECRET === LEGACY_PUBLIC_SESSION_SECRET); +// Write the session's expiry at most once an hour, not on every request. +export const SESSION_TOUCH_AFTER_SEC = 60 * 60; export const EXPRESS_SESSION_SECRET = !IS_EXPRESS_SESSION_SECRET_GENERATED && env.EXPRESS_SESSION_SECRET ? env.EXPRESS_SESSION_SECRET diff --git a/packages/api/src/migrations.ts b/packages/api/src/migrations.ts index 85fd2804c3..3428f12629 100644 --- a/packages/api/src/migrations.ts +++ b/packages/api/src/migrations.ts @@ -1,5 +1,6 @@ import mongoose from 'mongoose'; +import * as config from '@/config'; import Alert, { IAlert } from '@/models/alert'; import Dashboard from '@/models/dashboard'; import { SavedSearch } from '@/models/savedSearch'; @@ -129,10 +130,30 @@ export async function backfillAlertDisplayFields() { ); } +// connect-mongo's touch() never adds lastModified, so without it older +// sessions keep being rewritten on every request. +export async function backfillSessionLastModified() { + await mongoose.connection.collection('sessions').updateMany( + { lastModified: { $exists: false } }, + { + $set: { + lastModified: new Date( + Date.now() - config.SESSION_TOUCH_AFTER_SEC * 1000, + ), + }, + }, + ); +} + export async function runStartupMigrations() { try { await backfillAlertDisplayFields(); } catch (e) { logger.error({ err: e }, 'Error backfilling alert display names and tags'); } + try { + await backfillSessionLastModified(); + } catch (e) { + logger.error({ err: e }, 'Error backfilling session lastModified'); + } } From efec714a75642c74b2c5302ac2369f063f664b0d Mon Sep 17 00:00:00 2001 From: aryainguz Date: Thu, 26 Nov 2026 21:14:35 +0530 Subject: [PATCH 2/3] test(api): cover logout and log the session backfill --- .../src/__tests__/sessionStore.int.test.ts | 10 +++++++++ packages/api/src/migrations.ts | 22 ++++++++++++------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/packages/api/src/__tests__/sessionStore.int.test.ts b/packages/api/src/__tests__/sessionStore.int.test.ts index 0786f98333..d29b956e0f 100644 --- a/packages/api/src/__tests__/sessionStore.int.test.ts +++ b/packages/api/src/__tests__/sessionStore.int.test.ts @@ -19,6 +19,8 @@ describe('session store writes', () => { beforeAll(async () => { await server.start(); + // Registration fails if an earlier suite left a team behind. + await server.clearDBs(); }); afterEach(async () => { @@ -70,6 +72,14 @@ describe('session store writes', () => { expect(await storedExpiry(sid)).toEqual(before); }); + it('still removes the session on logout', async () => { + const { agent, sid } = await login(); + + await agent.get('/logout').expect(302); + + expect(await sessions().findOne({ _id: sid })).toBeNull(); + }); + it('extends the session once the touch interval has passed', async () => { const { agent, sid } = await login(); const stale = new Date(Date.now() - (SESSION_TOUCH_AFTER_SEC + 60) * 1000); diff --git a/packages/api/src/migrations.ts b/packages/api/src/migrations.ts index 3428f12629..7e6fc7d8bb 100644 --- a/packages/api/src/migrations.ts +++ b/packages/api/src/migrations.ts @@ -133,15 +133,21 @@ export async function backfillAlertDisplayFields() { // connect-mongo's touch() never adds lastModified, so without it older // sessions keep being rewritten on every request. export async function backfillSessionLastModified() { - await mongoose.connection.collection('sessions').updateMany( - { lastModified: { $exists: false } }, - { - $set: { - lastModified: new Date( - Date.now() - config.SESSION_TOUCH_AFTER_SEC * 1000, - ), + const result = await mongoose.connection + .collection<{ _id: string; lastModified?: Date }>('sessions') + .updateMany( + { lastModified: { $exists: false } }, + { + $set: { + lastModified: new Date( + Date.now() - config.SESSION_TOUCH_AFTER_SEC * 1000, + ), + }, }, - }, + ); + logger.info( + { updatedCount: result.modifiedCount }, + 'Backfilled session lastModified', ); } From a585f9cb52cd24737a862a21cc402445711e4990 Mon Sep 17 00:00:00 2001 From: aryainguz Date: Thu, 26 Nov 2026 21:18:18 +0530 Subject: [PATCH 3/3] fix(api): log the session backfill only when it updates sessions --- packages/api/src/migrations.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/api/src/migrations.ts b/packages/api/src/migrations.ts index 7e6fc7d8bb..821328ab54 100644 --- a/packages/api/src/migrations.ts +++ b/packages/api/src/migrations.ts @@ -145,10 +145,12 @@ export async function backfillSessionLastModified() { }, }, ); - logger.info( - { updatedCount: result.modifiedCount }, - 'Backfilled session lastModified', - ); + if (result.modifiedCount > 0) { + logger.info( + { updatedCount: result.modifiedCount }, + 'Backfilled session lastModified', + ); + } } export async function runStartupMigrations() {