Skip to content

perf(api): optimize session storage by reducing extra writes to MongoDB - #3839

Open
Aryainguz wants to merge 4 commits into
ClickHouse:mainfrom
Aryainguz:aryainguz/session-touch-after
Open

Aryainguz wants to merge 4 commits into
ClickHouse:mainfrom
Aryainguz:aryainguz/session-touch-after

Conversation

@Aryainguz

@Aryainguz Aryainguz commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #3837

On every request that leaves the session unchanged, express-session calls store.touch() to push its expiry forward, and connect-mongo's touch() runs an updateOne unless touchAfter is set. So every API request from a signed-in browser wrote its session document, and the response waited for that write.

  • Set touchAfter to one hour (SESSION_TOUCH_AFTER_SEC in config.ts). The stored expiry moves forward at most once an hour, which is plenty for 30-day sessions. The cookie still rolls on every response, and a changed session (login, logout) is still saved right away.
  • connect-mongo only skips a touch when the stored session has lastModified, and touch() never adds that field. Sessions that existed before this change would keep writing on every request, and rolling sessions never expire while in use. A startup backfill in runStartupMigrations() stamps lastModified on them, following the same pattern as backfillAlertDisplayFields.

Opening a 12-tile dashboard in the browser (yarn dev, a temporary counter on the store's write events), two runs each:

One dashboard load main This PR
Signed-in API requests 52 (40 ClickHouse queries) 52 (40 ClickHouse queries)
Session writes to MongoDB 52 0

Signed-in GET /me in the integration environment, with 3 ms of network delay added to MongoDB (tc netem), two runs each:

main This PR
Session writes, 450 requests 450 0
Sequential latency 20.1 ms/req 14.5 ms/req (−28%)
10 rounds × 25 parallel requests, p95 83 ms 49 ms (−41%)

Without the added delay, sequential latency went from 3.3 to 2.4 ms/req.

Trade-offs

  • The stored expiry can lag the cookie by up to an hour, so an idle session may end up to an hour before its 30 days are up. Logout and deleted users still take effect immediately.
  • The backfill runs on every startup. After the first run it matches nothing, but the $exists: false filter still scans the sessions collection.

How to reproduce

Starting point: yarn dev, signed in.

  1. mongosh "<MONGO_URI>" --eval 'db.sessions.find({}, { expires: 1, lastModified: 1 })'
  2. Open any dashboard and run step 1 again.

On main: expires moves on every API request.

On this branch: expires stays the same until an hour has passed.

Tests

__tests__/sessionStore.int.test.ts:

  • Signed-in requests leave the stored session unchanged. Fails on main.
  • A session stored without lastModified stops being rewritten after the backfill. Fails without the backfill.
  • Once the touch interval has passed, the next request still extends the session.

The full API integration suite (71 suites), unit tests for all packages, make ci-lint and knip pass.

How to test on Vercel preview

N/A, non-UI change.

References


Note

Medium Risk
Changes session persistence timing in MongoDB (stored expiry can lag the cookie by up to an hour), though logout and explicit session changes remain immediate.

Overview
Reduces per-request MongoDB writes for signed-in API traffic by configuring connect-mongo’s touchAfter to one hour (SESSION_TOUCH_AFTER_SEC). Rolling cookies and immediate saves on login/logout/session changes are unchanged; only deferred expiry updates in the sessions collection are throttled.

Existing sessions lacked lastModified, so they would still touch on every request without a migration. A startup backfillSessionLastModified stamps lastModified (same pattern as other startup backfills) so legacy rows benefit from the throttle after the first touch.

Integration tests cover: no rewrite on repeated /me calls, backfill behavior, logout deletion, and extension after the interval elapses.

Reviewed by Cursor Bugbot for commit 62f81a7. Bugbot is set up for automated code reviews on this repo. Configure here.

@Aryainguz
Aryainguz requested a review from a team as a code owner November 26, 2026 15:20
@vercel

vercel Bot commented Nov 26, 2026

Copy link
Copy Markdown

@Aryainguz is attempting to deploy a commit to the HyperDX Team on Vercel.

A member of the Team first needs to authorize it.

@changeset-bot

changeset-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 62f81a7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@hyperdx/api Patch
@hyperdx/app Patch
@hyperdx/otel-collector Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@Aryainguz Aryainguz changed the title perf(api): optimize session storage by reducing writes to MongoDB and… perf(api): optimize session storage by reducing writes to MongoDB Nov 26, 2026
@Aryainguz Aryainguz changed the title perf(api): optimize session storage by reducing writes to MongoDB perf(api): optimize session storage by reducing extra writes to MongoDB Nov 26, 2026
@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

PR Review

✅ No issues found.

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

Report-only multi-agent review of the session-store write-reduction change (touchAfter, startup lastModified backfill, integration test). The correctness, security, and adversarial passes each traced the connect-mongo v4 touch()/touchAfter semantics against the backfill and found the core design sound: active sessions are never pruned (any request older than the window re-stamps expires to ~now+30d), the backfilled now − touchAfter timestamp triggers exactly one re-touch with no off-by-one, and logout/deleted-user invalidation stay immediate. No ship-blocking issues.

✅ No critical issues found.

🟡 P2 — recommended

  • packages/api/src/migrations.ts:137 — The backfill hardcodes the 'sessions' collection name, which matches only because MongoStore in api-app.ts omits collectionName and inherits connect-mongo's default; the two sites share no constant, so a later custom collectionName would make the backfill silently no-op while legacy sessions keep rewriting on every request.
    • Fix: Define one shared session-collection-name constant and pass it to both the MongoStore config and the .collection() call in the backfill.
    • data-migrations, maintainability
  • packages/api/src/__tests__/sessionStore.int.test.ts:52 — No test asserts the { lastModified: { $exists: false } } filter leaves an already-stamped session untouched, yet runStartupMigrations re-runs the backfill on every boot, so a filter regression would silently re-stamp every session (resetting its touch clock) on each restart.
    • Fix: Add a test that seeds a session with a recent lastModified, runs backfillSessionLastModified(), and asserts the value is unchanged and a repeat run reports zero modifications.
    • testing
🔵 P3 nitpicks (2)
  • packages/api/src/migrations.ts:138 — backfillSessionLastModified runs updateMany({ lastModified: { $exists: false } }) against an unindexed field on every startup, a full-collection scan each boot even once it matches nothing.
    • Fix: Bound the update with an explicit maxTimeMS, or short-circuit after the first successful backfill, so the scan does not repeat on every restart.
    • data-migrations, reliability, performance, adversarial
  • packages/api/src/__tests__/sessionStore.int.test.ts:62 — The "stops rewriting…once backfilled" test infers the backfill's effect only from settling behavior and never asserts lastModified was actually advanced by the first post-backfill request, so a connect-mongo upgrade that changed touch() semantics would pass silently.
    • Fix: After the first post-backfill request, assert lastModified advanced, not just that expires later stops changing.
    • testing, adversarial

Reviewers (13): correctness, security, adversarial, performance, data-migrations, reliability, testing, maintainability, kieran-typescript, project-standards, agent-native, learnings-researcher, previous-comments.

Testing gaps: backfill idempotency / zero-match no-op path is unasserted; the runStartupMigrations try/catch swallow path (backfill throwing is logged but not rethrown) is uncovered; no assertion that a backfilled session's lastModified advances after its first request.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

Comment thread packages/api/src/migrations.ts Resolved

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(api) : API writes the login session to MongoDB on every request

1 participant