Analyze ONLY changed files (diff scope) for runtime performance characteristics while preserving correctness, public APIs, and security constraints. Apply only clearly safe micro-optimizations.
FOCUS CATEGORIES#
- Next.js Rendering (SSR vs SSG vs ISR selection, unnecessary client-side rendering, image optimization, dynamic imports)
- React Component Optimization (unnecessary re-renders, missing memo/useMemo/useCallback, component splitting, hook dependencies)
- MongoDB Query Efficiency (missing indexes, N+1 queries, inefficient aggregation pipelines, projection usage, query selectivity)
- BullMQ Job Management (job batching, queue configuration, job priority, concurrency limits, job retry strategies)
- Data Fetching Patterns (React Query cache configuration, stale-while-revalidate, request deduplication, parallel queries)
- Bundle Size & Code Splitting (dynamic imports, route-based splitting, tree-shaking opportunities, large dependencies)
- Memory & State Management (memory leaks in effects, unnecessary state updates, large object retention, cleanup functions)
- Async & Concurrency (blocking operations, unnecessary awaits, Promise.all patterns, parallel data fetching)
- Caching Strategies (React Query cache keys, Next.js cache headers, Redis caching opportunities, memoization)
- I/O & Network Efficiency (redundant API calls, request batching, streaming responses, connection pooling)
ACTION WORKFLOW (MANDATORY)#
1 Diff list → 2 Perf analysis per category → 3 Classify (safe-edit / deferred / requires-approval) → 4 Apply only mechanical, behavior-preserving micro-optimizations (e.g., add React.memo, add MongoDB index, convert to server component, batch BullMQ jobs) → 5 Run just lint & just test → 6 Revert failing hunk if gates fail → 7 Report (summary, applied, deferred, approval-needed, perf notes, next steps) → 8 Output unified diff (no commit).
If zero safe edits: state "No safe performance edits applied" and still produce full report.
SAFE PERFORMANCE EDIT EXAMPLES#
Next.js#
- Convert client components to server components where possible
- Add
next/imageoptimization instead of regular<img>tags - Use dynamic imports (
next/dynamic) for heavy components - Add
generateStaticParamsfor static route generation - Implement ISR with appropriate
revalidatevalues - Use
unstable_cachefor server-side data caching
React#
- Add
React.memoto prevent unnecessary re-renders of expensive components - Wrap callbacks in
useCallbackto prevent child re-renders - Wrap expensive computations in
useMemo - Fix missing dependencies in
useEffect/useCallback/useMemohooks - Split large components into smaller, memoized components
- Remove unnecessary state updates or combine related state
MongoDB#
- Add indexes for frequently queried fields (especially in
find,sort,aggregate) - Use projection to limit returned fields (
selectin Mongoose) - Replace N+1 queries with
$lookupaggregations orpopulatewith proper select - Add compound indexes for multi-field queries
- Use
lean()for read-only queries to return plain objects - Optimize aggregation pipelines (early
$match, limit$projectfields)
BullMQ#
- Batch related jobs into single job with array payload
- Configure appropriate concurrency limits per queue
- Use job priorities for important tasks
- Implement job batching with
addBulkinstead of multipleaddcalls - Configure appropriate retry strategies (delays, max attempts)
- Use job options (removeOnComplete, removeOnFail) to manage queue size
General#
- Replace sequential awaits with
Promise.allfor parallel operations - Use React Query's
useQueriesfor parallel data fetching - Add request deduplication with React Query cache keys
- Implement proper cleanup in
useEffectto prevent memory leaks - Use dynamic imports for code splitting (
React.lazy,next/dynamic)
AUTO-EDIT CONSTRAINTS (STRICT)#
Scope: diff-only | Gates: just lint + tests must pass | No commits | No public signature/visibility changes | Validate after edits | No semantic changes
CRITICAL REQUIREMENTS#
- Do not trade readability or security for micro perf
- Never introduce unsafe
- Provide benchmarks only as recommendations (do not add heavy harness automatically)
- Defer structural refactors (module splits) unless trivial & internal
- Avoid premature caching introducing invalidation complexity
REPO RULES (REINFORCED)#
Zero warnings (ESLint) | Strict TypeScript (no any) | Precise typing | Async/await for I/O | Service-layer architecture | AppError for errors | Zod validation | Project-scoped multi-tenancy | Memory efficiency | S3-compatible storage (MinIO) | Path validation | No secrets in logs | JSDoc for public APIs | Pino logging
EXECUTION CHECKLIST#
1 Diff scan 2 Analyze perf 3 Classify 4 Apply safe micro-optimizations 5 Gates pass 6 Report 7 Output diff | On blocker: report & remediate guidance.
QUICK PERFORMANCE MATRIX#
Category → Sample Safe Edit:
- Next.js Rendering → Convert
'use client'component to server component, addnext/image, usedynamicimport - React Optimization → Add
React.memoto expensive component, wrap callback inuseCallback, wrap computation inuseMemo - MongoDB Queries → Add index for
find().sort()field, uselean()for read-only, add projection to limit fields - BullMQ Jobs → Batch jobs with
addBulk, configure concurrency limits, use job priorities - Data Fetching → Use
Promise.allfor parallel queries, configure React QuerystaleTime, deduplicate requests - Bundle Size → Add
next/dynamicfor heavy components, useReact.lazyfor route splitting - Memory Leaks → Add cleanup function to
useEffect, remove event listeners, cancel subscriptions - Async Patterns → Replace sequential
awaitwithPromise.all, useuseQueriesfor parallel fetching - Caching → Configure React Query cache keys, add Next.js
unstable_cache, implement Redis caching - I/O Efficiency → Batch MongoDB queries, use aggregation pipelines, optimize Redis operations
Ambiguous? Defer and document.