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 strategies4---56# Performance Optimization Skill78Comprehensive frameworks for analyzing and optimizing application performance across the entire stack.910## When to Use1112- Application feels slow or unresponsive13- Database queries taking too long14- Frontend bundle size too large15- API response times exceed targets16- Core Web Vitals need improvement17- Preparing for scale or high traffic1819## Performance Targets2021### Core Web Vitals (Frontend)2223| Metric | Good | Needs Work |24|--------|------|------------|25| **LCP** (Largest Contentful Paint) | < 2.5s | < 4s |26| **INP** (Interaction to Next Paint) | < 200ms | < 500ms |27| **CLS** (Cumulative Layout Shift) | < 0.1 | < 0.25 |28| **TTFB** (Time to First Byte) | < 200ms | < 600ms |2930### Backend Targets3132| Operation | Target |33|-----------|--------|34| Simple reads | < 100ms |35| Complex queries | < 500ms |36| Write operations | < 200ms |37| Index lookups | < 10ms |3839## Bottleneck Categories4041| Category | Symptoms | Tools |42|----------|----------|-------|43| **Network** | High TTFB, slow loading | Network tab, WebPageTest |44| **Database** | Slow queries, pool exhaustion | EXPLAIN ANALYZE, pg_stat_statements |45| **CPU** | High usage, slow compute | Profiler, flame graphs |46| **Memory** | Leaks, GC pauses | Heap snapshots |47| **Rendering** | Layout thrashing | React DevTools, Performance tab |4849## Database Optimization5051### Key Patterns52531. **Add Missing Indexes** - Turn `Seq Scan` into `Index Scan`542. **Fix N+1 Queries** - Use JOINs or `include` instead of loops553. **Cursor Pagination** - Never load all records564. **Connection Pooling** - Manage connection lifecycle5758### Quick Diagnostics5960```sql61-- Find slow queries (PostgreSQL)62SELECT query, calls, mean_time / 1000 as mean_seconds63FROM pg_stat_statements ORDER BY total_time DESC LIMIT 10;6465-- Verify index usage66EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 123;67```6869> See `templates/database-optimization.ts` for N+1 fixes and pagination patterns7071## Caching Strategy7273### Cache Hierarchy7475```76L1: In-Memory (LRU, memoization) - fastest77L2: Distributed (Redis/Memcached) - shared78L3: CDN (edge, static assets) - global79L4: Database (materialized views) - fallback80```8182### Cache-Aside Pattern8384```typescript85const cached = await redis.get(key);86if (cached) return JSON.parse(cached);87const data = await db.query(...);88await redis.setex(key, 3600, JSON.stringify(data));89return data;90```9192> See `templates/caching-patterns.ts` for full implementation9394## Frontend Optimization9596### Bundle Optimization97981. **Code Splitting** - `lazy()` for route-based splitting992. **Tree Shaking** - Import only what you need1003. **Image Optimization** - WebP/AVIF, lazy loading, proper sizing101102### Rendering Optimization1031041. **Memoization** - `memo()`, `useCallback()`, `useMemo()`1052. **Virtualization** - Render only visible items in long lists1063. **Batch DOM Operations** - Read all, then write all107108> See `templates/frontend-optimization.tsx` for patterns109110### Analysis Commands111112```bash113# Lighthouse audit114lighthouse http://localhost:3000 --output=json115116# Bundle analysis117npx @next/bundle-analyzer # Next.js118npx vite-bundle-visualizer # Vite119```120121## API Optimization122123### Response Optimization1241251. **Field Selection** - Return only requested fields1262. **Compression** - Enable gzip/brotli (threshold: 1KB)1273. **ETags** - Enable 304 responses for unchanged data1284. **Pagination** - Cursor-based for large datasets129130> See `templates/api-optimization.ts` for middleware examples131132## Monitoring Checklist133134### Before Launch135136- [ ] Lighthouse score > 90137- [ ] Core Web Vitals pass138- [ ] Bundle size within budget139- [ ] Database queries profiled140- [ ] Compression enabled141- [ ] CDN configured142143### Ongoing144145- [ ] Performance monitoring active146- [ ] Alerting for degradation147- [ ] Lighthouse CI in pipeline148- [ ] Weekly query analysis149- [ ] Real User Monitoring (RUM)150151> See `templates/performance-metrics.ts` for Prometheus metrics setup152153## Extended Thinking Triggers154155Use Opus 4.5 extended thinking for:156- **Complex debugging** - Multiple potential causes157- **Architecture decisions** - Caching strategy selection158- **Trade-off analysis** - Memory vs CPU vs latency159- **Root cause analysis** - Performance regression investigation160161## Templates Reference162163| Template | Purpose |164|----------|---------|165| `database-optimization.ts` | N+1 fixes, pagination, pooling |166| `caching-patterns.ts` | Redis cache-aside, memoization |167| `frontend-optimization.tsx` | React memo, virtualization, code splitting |168| `api-optimization.ts` | Compression, ETags, field selection |169| `performance-metrics.ts` | Prometheus metrics, performance budget |