Skip to content

perf(habits): batch habit log queries instead of N+1 per-day lookups#69

Open
Chzhqv wants to merge 1 commit into
TemaDeveloper:mainfrom
Chzhqv:fix/habits-n-plus-one-query
Open

perf(habits): batch habit log queries instead of N+1 per-day lookups#69
Chzhqv wants to merge 1 commit into
TemaDeveloper:mainfrom
Chzhqv:fix/habits-n-plus-one-query

Conversation

@Chzhqv

@Chzhqv Chzhqv commented Jul 7, 2026

Copy link
Copy Markdown

Summary

  • GET /api/habits ran a today-log query per habit plus up to 365 individual per-day queries per habit for streak calculation (10 habits could mean 3650+ DB round-trips).
  • Batch-fetch every log in the lookback window with a single habitId: {$in} query and compute completedToday/streak in memory instead.

Test plan

  • Seeded a habit with a controlled 4-day streak plus a gap and an isolated older log (using the same date-fns helpers the route uses, to avoid timezone drift), confirmed the API still returns streak: 4 exactly as before — gap correctly breaks the streak, isolated day correctly excluded
  • Confirmed via MongoDB's profiler that exactly 1 query hits habitlogs per call, regardless of habit count
  • pnpm lint, tsc --noEmit, full vitest run (556/556) all pass

Fixes #6

GET /api/habits ran a today-log query per habit plus up to 365
individual queries per habit for streak calculation (10 habits could
mean 3650+ DB round-trips). Batch-fetch all logs in the lookback
window with a single habitId $in query and compute completedToday/
streak in memory instead.

Fixes TemaDeveloper#6
@vercel

vercel Bot commented Jul 7, 2026

Copy link
Copy Markdown

Someone is attempting to deploy a commit to the Artemii's projects Team on Vercel.

A member of the Team first needs to authorize it.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: N+1 query pattern in habits GET endpoint

1 participant