Performance Optimization Skill
Comprehensive frameworks for analyzing and optimizing application performance across the entire stack.
When to Use
- Application feels slow or unresponsive
- Database queries taking too long
- Frontend bundle size too large
- API response times exceed targets
- Core Web Vitals need improvement
- Preparing for scale or high traffic
Performance Targets
Core Web Vitals (Frontend)
| Metric |
Good |
Needs Work |
| LCP (Largest Contentful Paint) |
< 2.5s |
< 4s |
| INP (Interaction to Next Paint) |
< 200ms |
< 500ms |
| CLS (Cumulative Layout Shift) |
< 0.1 |
< 0.25 |
| TTFB (Time to First Byte) |
< 200ms |
< 600ms |
Backend Targets
| Operation |
Target |
| Simple reads |
< 100ms |
| Complex queries |
< 500ms |
| Write operations |
< 200ms |
| Index lookups |
< 10ms |
Bottleneck Categories
| Category |
Symptoms |
Tools |
| Network |
High TTFB, slow loading |
Network tab, WebPageTest |
| Database |
Slow queries, pool exhaustion |
EXPLAIN ANALYZE, pg_stat_statements |
| CPU |
High usage, slow compute |
Profiler, flame graphs |
| Memory |
Leaks, GC pauses |
Heap snapshots |
| Rendering |
Layout thrashing |
React DevTools, Performance tab |
Database Optimization
Key Patterns
- Add Missing Indexes - Turn
Seq Scan into Index Scan
- Fix N+1 Queries - Use JOINs or
include instead of loops
- Cursor Pagination - Never load all records
- Connection Pooling - Manage connection lifecycle
Quick Diagnostics
-- Find slow queries (PostgreSQL)
SELECT query, calls, mean_time / 1000 as mean_seconds
FROM pg_stat_statements ORDER BY total_time DESC LIMIT 10;
-- Verify index usage
EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 123;
See templates/database-optimization.ts for N+1 fixes and pagination patterns
Caching Strategy
Cache Hierarchy
L1: In-Memory (LRU, memoization) - fastest
L2: Distributed (Redis/Memcached) - shared
L3: CDN (edge, static assets) - global
L4: Database (materialized views) - fallback
Cache-Aside Pattern
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const data = await db.query(...);
await redis.setex(key, 3600, JSON.stringify(data));
return data;
See templates/caching-patterns.ts for full implementation
Frontend Optimization
Bundle Optimization
- Code Splitting -
lazy() for route-based splitting
- Tree Shaking - Import only what you need
- Image Optimization - WebP/AVIF, lazy loading, proper sizing
Rendering Optimization
- Memoization -
memo(), useCallback(), useMemo()
- Virtualization - Render only visible items in long lists
- Batch DOM Operations - Read all, then write all
See templates/frontend-optimization.tsx for patterns
Analysis Commands
# Lighthouse audit
lighthouse http://localhost:3000 --output=json
# Bundle analysis
npx @next/bundle-analyzer # Next.js
npx vite-bundle-visualizer # Vite
API Optimization
Response Optimization
- Field Selection - Return only requested fields
- Compression - Enable gzip/brotli (threshold: 1KB)
- ETags - Enable 304 responses for unchanged data
- Pagination - Cursor-based for large datasets
See templates/api-optimization.ts for middleware examples
Monitoring Checklist
Before Launch
Ongoing
See templates/performance-metrics.ts for Prometheus metrics setup
Extended Thinking Triggers
Use Opus 4.5 extended thinking for:
- Complex debugging - Multiple potential causes
- Architecture decisions - Caching strategy selection
- Trade-off analysis - Memory vs CPU vs latency
- Root cause analysis - Performance regression investigation
Templates Reference
| Template |
Purpose |
database-optimization.ts |
N+1 fixes, pagination, pooling |
caching-patterns.ts |
Redis cache-aside, memoization |
frontend-optimization.tsx |
React memo, virtualization, code splitting |
api-optimization.ts |
Compression, ETags, field selection |
performance-metrics.ts |
Prometheus metrics, performance budget |
1---2name: performance-optimization3description: Full-stack performance analysis, optimization patterns, and monitoring strategies4version: 1.0.05category: Quality & Optimization6agents: [backend-system-architect, frontend-ui-developer, code-quality-reviewer]7keywords: [performance, optimization, speed, latency, throughput, caching, profiling, bundle, Core Web Vitals]8---910# Performance Optimization Skill1112Comprehensive frameworks for analyzing and optimizing application performance across the entire stack.1314## When to Use1516- Application feels slow or unresponsive17- Database queries taking too long18- Frontend bundle size too large19- API response times exceed targets20- Core Web Vitals need improvement21- Preparing for scale or high traffic2223## Performance Targets2425### Core Web Vitals (Frontend)2627| Metric | Good | Needs Work |28|--------|------|------------|29| **LCP** (Largest Contentful Paint) | < 2.5s | < 4s |30| **INP** (Interaction to Next Paint) | < 200ms | < 500ms |31| **CLS** (Cumulative Layout Shift) | < 0.1 | < 0.25 |32| **TTFB** (Time to First Byte) | < 200ms | < 600ms |3334### Backend Targets3536| Operation | Target |37|-----------|--------|38| Simple reads | < 100ms |39| Complex queries | < 500ms |40| Write operations | < 200ms |41| Index lookups | < 10ms |4243## Bottleneck Categories4445| Category | Symptoms | Tools |46|----------|----------|-------|47| **Network** | High TTFB, slow loading | Network tab, WebPageTest |48| **Database** | Slow queries, pool exhaustion | EXPLAIN ANALYZE, pg_stat_statements |49| **CPU** | High usage, slow compute | Profiler, flame graphs |50| **Memory** | Leaks, GC pauses | Heap snapshots |51| **Rendering** | Layout thrashing | React DevTools, Performance tab |5253## Database Optimization5455### Key Patterns56571. **Add Missing Indexes** - Turn `Seq Scan` into `Index Scan`582. **Fix N+1 Queries** - Use JOINs or `include` instead of loops593. **Cursor Pagination** - Never load all records604. **Connection Pooling** - Manage connection lifecycle6162### Quick Diagnostics6364```sql65-- Find slow queries (PostgreSQL)66SELECT query, calls, mean_time / 1000 as mean_seconds67FROM pg_stat_statements ORDER BY total_time DESC LIMIT 10;6869-- Verify index usage70EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 123;71```7273> See `templates/database-optimization.ts` for N+1 fixes and pagination patterns7475## Caching Strategy7677### Cache Hierarchy7879```80L1: In-Memory (LRU, memoization) - fastest81L2: Distributed (Redis/Memcached) - shared82L3: CDN (edge, static assets) - global83L4: Database (materialized views) - fallback84```8586### Cache-Aside Pattern8788```typescript89const cached = await redis.get(key);90if (cached) return JSON.parse(cached);91const data = await db.query(...);92await redis.setex(key, 3600, JSON.stringify(data));93return data;94```9596> See `templates/caching-patterns.ts` for full implementation9798## Frontend Optimization99100### Bundle Optimization1011021. **Code Splitting** - `lazy()` for route-based splitting1032. **Tree Shaking** - Import only what you need1043. **Image Optimization** - WebP/AVIF, lazy loading, proper sizing105106### Rendering Optimization1071081. **Memoization** - `memo()`, `useCallback()`, `useMemo()`1092. **Virtualization** - Render only visible items in long lists1103. **Batch DOM Operations** - Read all, then write all111112> See `templates/frontend-optimization.tsx` for patterns113114### Analysis Commands115116```bash117# Lighthouse audit118lighthouse http://localhost:3000 --output=json119120# Bundle analysis121npx @next/bundle-analyzer # Next.js122npx vite-bundle-visualizer # Vite123```124125## API Optimization126127### Response Optimization1281291. **Field Selection** - Return only requested fields1302. **Compression** - Enable gzip/brotli (threshold: 1KB)1313. **ETags** - Enable 304 responses for unchanged data1324. **Pagination** - Cursor-based for large datasets133134> See `templates/api-optimization.ts` for middleware examples135136## Monitoring Checklist137138### Before Launch139140- [ ] Lighthouse score > 90141- [ ] Core Web Vitals pass142- [ ] Bundle size within budget143- [ ] Database queries profiled144- [ ] Compression enabled145- [ ] CDN configured146147### Ongoing148149- [ ] Performance monitoring active150- [ ] Alerting for degradation151- [ ] Lighthouse CI in pipeline152- [ ] Weekly query analysis153- [ ] Real User Monitoring (RUM)154155> See `templates/performance-metrics.ts` for Prometheus metrics setup156157## Extended Thinking Triggers158159Use Opus 4.5 extended thinking for:160- **Complex debugging** - Multiple potential causes161- **Architecture decisions** - Caching strategy selection162- **Trade-off analysis** - Memory vs CPU vs latency163- **Root cause analysis** - Performance regression investigation164165## Templates Reference166167| Template | Purpose |168|----------|---------|169| `database-optimization.ts` | N+1 fixes, pagination, pooling |170| `caching-patterns.ts` | Redis cache-aside, memoization |171| `frontend-optimization.tsx` | React memo, virtualization, code splitting |172| `api-optimization.ts` | Compression, ETags, field selection |173| `performance-metrics.ts` | Prometheus metrics, performance budget |