⚡ Bolt: Memoize core auth and DB queries#75
Conversation
Implement request-scoped memoization using React 'cache' for high-frequency authentication and database functions. This optimization reduces redundant JWT verifications and database roundtrips within a single request lifecycle. Key changes: - Added a conditional `memoize` helper in `lib/utils.ts` for Edge compatibility. - Memoized `verifyToken` in `lib/auth/session.ts`. - Memoized `getUser`, `getUserWithTeam`, and `getTeamForUser` in `lib/db/queries.ts`. - Added performance comments explaining the impact. Expected impact: - 100% reduction in redundant database calls for user/team data per request. - 100% reduction in redundant JWT decodes per request. - Improved Time to First Byte (TTFB) for authenticated routes. Co-authored-by: RAbuseedo <97478862+RAbuseedo@users.noreply.github.com>
|
👋 Jules, reporting for duty! I'm here to lend a hand with this pull request. When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down. I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job! For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
💡 What
Implemented request-scoped memoization for core authentication and database query functions using React's
cacheutility. I also added a conditionalmemoizehelper inlib/utils.tsto ensure the application remains compatible with the Edge Runtime (used in Next.js Middleware), where React'scacheis not available.🎯 Why
In Next.js App Router, foundational functions like
getUser()are often called multiple times across different segments of a single request (e.g., inRootLayoutfor theUserProvider, in page components for authorization, and in server actions). Without memoization, each call triggers a new database query and a JWT verification, leading to unnecessary latency and resource consumption.📊 Impact
🔬 Measurement
The optimization can be verified by monitoring database query logs or adding temporary console logs to the memoized functions. You will see that for a single page load (e.g., the dashboard), these functions now execute their logic only once, even if called 3-4 times across the component tree. Type safety was verified with
pnpm exec tsc --noEmit.PR created automatically by Jules for task 5229460848385358780 started by @RAbuseedo