Performance Optimization
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: performance for comprehensive documentation.
When NOT to Use This Skill
This skill focuses on runtime performance optimization. Do NOT use for:
- Algorithm optimization - Use computer science/data structures fundamentals
- Code readability - Use
clean-code skill (don't sacrifice readability for micro-optimizations)
- Build time optimization - Use build tool specific skills (Vite, Webpack, etc.)
- Developer experience - Use DX-focused skills and tooling
- Security hardening - Use security-specific skills (performance != security)
Anti-Patterns
| Anti-Pattern |
Why It's Bad |
Performance Solution |
| Premature Optimization |
Waste time on non-bottlenecks |
Measure first, optimize bottlenecks only |
| **SELECT *** |
Fetches unnecessary data |
Select only needed columns |
| N+1 Queries |
Multiple DB roundtrips |
Use joins or eager loading |
| No Caching |
Repeated expensive computations |
Cache at appropriate layer (memory, Redis, CDN) |
| Blocking Operations |
Holds up main thread |
Use async/background jobs |
| Large Bundle |
Slow initial load |
Code splitting, lazy loading |
| No Image Optimization |
Huge assets over network |
Compress, modern formats (WebP, AVIF), lazy load |
| Missing Indexes |
Full table scans |
Add indexes on queried columns |
| Memory Leaks |
Unbounded growth |
Clean up listeners, close connections, clear refs |
| Synchronous I/O |
Blocks event loop |
Use async I/O operations |
Quick Troubleshooting
| Issue |
Diagnostic |
Solution |
| Slow page load |
Check Network tab |
Optimize images, enable compression, use CDN |
| Poor LCP |
Lighthouse audit |
Preload critical resources, optimize largest element |
| High INP |
Performance profiler |
Debounce handlers, use web workers, reduce JS |
| Layout shifts (CLS) |
Layout Shift Regions |
Set dimensions on images/embeds, avoid dynamic content |
| Slow API response |
APM tools, logging |
Add database indexes, cache responses, optimize queries |
| High memory usage |
Memory profiler |
Fix leaks, clear intervals/listeners, use weak refs |
| Large bundle |
Bundle analyzer |
Code split, tree shake, lazy load routes |
| Slow database query |
EXPLAIN ANALYZE |
Add indexes, rewrite query, partition table |
Frontend Performance
Core Web Vitals
| Metric |
Target |
Measurement |
| LCP (Largest Contentful Paint) |
< 2.5s |
Largest visible element |
| INP (Interaction to Next Paint) |
< 200ms |
Input responsiveness |
| CLS (Cumulative Layout Shift) |
< 0.1 |
Visual stability |
Optimization Techniques
// Code splitting
const Dashboard = lazy(() => import('./Dashboard'));
// Image optimization
<Image
src="/hero.jpg"
width={1200}
height={600}
priority // Above fold
placeholder="blur"
/>
// Memoization
const MemoizedComponent = memo(ExpensiveComponent);
const memoizedValue = useMemo(() => computeExpensive(a, b), [a, b]);
const memoizedFn = useCallback(() => handleClick(id), [id]);
// Virtual lists for long lists
<VirtualList items={items} itemHeight={50} />
Backend Performance
// N+1 prevention
const usersWithPosts = await prisma.user.findMany({
include: { posts: true } // Single query with join
});
// Caching
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));
// Connection pooling
const pool = new Pool({ max: 20 });
// Async processing
await queue.add('sendEmail', { userId });
Database Performance
-- Use EXPLAIN ANALYZE
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'x';
-- Add indexes for frequently queried columns
CREATE INDEX idx_users_email ON users(email);
-- Partial indexes
CREATE INDEX idx_active_users ON users(email) WHERE is_active = true;
-- Avoid SELECT *
SELECT id, name, email FROM users;
-- Pagination
SELECT * FROM users ORDER BY id LIMIT 20 OFFSET 0;
Checklist
| Area |
Check |
| Images |
Optimized, lazy loaded, proper format |
| JS Bundle |
Code split, tree shaken, minified |
| CSS |
Critical CSS inline, unused removed |
| Fonts |
Preloaded, subset, font-display |
| Caching |
CDN, browser cache, API cache |
| Database |
Indexes, query optimization |
Production Readiness
Monitoring Setup
// Web Vitals reporting
import { onCLS, onINP, onLCP, onFCP, onTTFB } from 'web-vitals';
function sendToAnalytics(metric: Metric) {
const body = JSON.stringify({
name: metric.name,
value: metric.value,
id: metric.id,
page: window.location.pathname,
});
// Use sendBeacon for reliability
navigator.sendBeacon('/analytics', body);
}
onCLS(sendToAnalytics);
onINP(sendToAnalytics);
onLCP(sendToAnalytics);
onFCP(sendToAnalytics);
onTTFB(sendToAnalytics);
Performance Budget
// webpack.config.js or vite.config.ts
{
performance: {
maxAssetSize: 250000, // 250KB
maxEntrypointSize: 500000, // 500KB
hints: 'error',
},
}
// Lighthouse CI budget
// lighthouserc.js
module.exports = {
ci: {
collect: {
url: ['http://localhost:3000/'],
},
assert: {
assertions: {
'categories:performance': ['error', { minScore: 0.9 }],
'first-contentful-paint': ['error', { maxNumericValue: 2000 }],
'largest-contentful-paint': ['error', { maxNumericValue: 2500 }],
'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],
'total-blocking-time': ['error', { maxNumericValue: 300 }],
},
},
},
};
Backend Optimization
// Response compression
import compression from 'compression';
app.use(compression({ threshold: 1024 }));
// Response caching headers
function setCacheHeaders(res: Response, maxAge: number) {
res.setHeader('Cache-Control', `public, max-age=${maxAge}, stale-while-revalidate=${maxAge * 2}`);
res.setHeader('Vary', 'Accept-Encoding');
}
// Streaming responses
async function streamLargeData(res: Response) {
const stream = db.users.findMany().cursor();
res.setHeader('Content-Type', 'application/json');
res.write('[');
let first = true;
for await (const user of stream) {
if (!first) res.write(',');
res.write(JSON.stringify(user));
first = false;
}
res.write(']');
res.end();
}
// Query optimization
const users = await prisma.user.findMany({
select: { id: true, name: true, email: true }, // Only needed fields
where: { isActive: true },
take: 20,
orderBy: { createdAt: 'desc' },
});
Database Optimization
-- Composite indexes for common queries
CREATE INDEX idx_users_active_created
ON users(is_active, created_at DESC)
WHERE is_active = true;
-- Query analysis
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM users WHERE email = 'test@example.com';
-- Connection pooling configuration
-- pgbouncer.ini
[pgbouncer]
pool_mode = transaction
default_pool_size = 20
max_client_conn = 100
CI Performance Testing
# .github/workflows/performance.yml
name: Performance
on:
pull_request:
branches: [main]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build
run: npm run build
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@v10
with:
configPath: ./lighthouserc.js
uploadArtifacts: true
bundle-size:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build
run: npm run build
- name: Check bundle size
uses: siddharthkp/bundlesize@v2
with:
files: 'dist/*.js'
maxSize: '250KB'
Caching Strategy
// Cache layers
const cacheStrategy = {
// L1: In-memory (fastest, smallest)
memory: new LRUCache({ max: 1000, ttl: 60000 }),
// L2: Redis (fast, larger)
redis: new Redis({ maxRetriesPerRequest: 3 }),
// L3: CDN (edge caching)
cdn: {
cacheControl: 'public, max-age=31536000, immutable', // Static assets
staleWhileRevalidate: 'public, max-age=60, stale-while-revalidate=600', // API
},
};
async function getCachedData<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
// Check memory
const memoryHit = cacheStrategy.memory.get(key);
if (memoryHit) return memoryHit as T;
// Check Redis
const redisHit = await cacheStrategy.redis.get(key);
if (redisHit) {
const data = JSON.parse(redisHit);
cacheStrategy.memory.set(key, data);
return data;
}
// Fetch and cache
const data = await fetcher();
cacheStrategy.memory.set(key, data);
await cacheStrategy.redis.setex(key, 300, JSON.stringify(data));
return data;
}
Monitoring Metrics
| Metric |
Target |
| LCP |
< 2.5s |
| INP |
< 200ms |
| CLS |
< 0.1 |
| TTFB |
< 200ms |
| API p95 latency |
< 500ms |
| Database query time |
< 100ms |
| Cache hit rate |
> 90% |
Production Checklist
Reference Documentation
- Bundle Analysis
- Caching Strategies
1---2name: performance3description: |4 Web performance optimization. Covers frontend, backend, and5 database optimization. Use for performance reviews.67 USE WHEN: user mentions "performance", "slow", "optimization", "Core Web Vitals", "LCP", "INP", "CLS",8 "bundle size", "lazy load", "caching", "N+1 query", "memory leak", asks about "how to speed up",9 "improve performance", "reduce load time", "database optimization"1011 DO NOT USE FOR: Algorithm complexity - use computer science fundamentals,12 Code quality/readability - use `clean-code` instead,13 Security optimization - use security-specific skills14allowed-tools: Read, Grep, Glob15---1617# Performance Optimization1819> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `performance` for comprehensive documentation.2021## When NOT to Use This Skill2223This skill focuses on runtime performance optimization. Do NOT use for:2425- **Algorithm optimization** - Use computer science/data structures fundamentals26- **Code readability** - Use `clean-code` skill (don't sacrifice readability for micro-optimizations)27- **Build time optimization** - Use build tool specific skills (Vite, Webpack, etc.)28- **Developer experience** - Use DX-focused skills and tooling29- **Security hardening** - Use security-specific skills (performance != security)3031## Anti-Patterns3233| Anti-Pattern | Why It's Bad | Performance Solution |34|--------------|--------------|---------------------|35| **Premature Optimization** | Waste time on non-bottlenecks | Measure first, optimize bottlenecks only |36| **SELECT *** | Fetches unnecessary data | Select only needed columns |37| **N+1 Queries** | Multiple DB roundtrips | Use joins or eager loading |38| **No Caching** | Repeated expensive computations | Cache at appropriate layer (memory, Redis, CDN) |39| **Blocking Operations** | Holds up main thread | Use async/background jobs |40| **Large Bundle** | Slow initial load | Code splitting, lazy loading |41| **No Image Optimization** | Huge assets over network | Compress, modern formats (WebP, AVIF), lazy load |42| **Missing Indexes** | Full table scans | Add indexes on queried columns |43| **Memory Leaks** | Unbounded growth | Clean up listeners, close connections, clear refs |44| **Synchronous I/O** | Blocks event loop | Use async I/O operations |4546## Quick Troubleshooting4748| Issue | Diagnostic | Solution |49|-------|------------|----------|50| **Slow page load** | Check Network tab | Optimize images, enable compression, use CDN |51| **Poor LCP** | Lighthouse audit | Preload critical resources, optimize largest element |52| **High INP** | Performance profiler | Debounce handlers, use web workers, reduce JS |53| **Layout shifts (CLS)** | Layout Shift Regions | Set dimensions on images/embeds, avoid dynamic content |54| **Slow API response** | APM tools, logging | Add database indexes, cache responses, optimize queries |55| **High memory usage** | Memory profiler | Fix leaks, clear intervals/listeners, use weak refs |56| **Large bundle** | Bundle analyzer | Code split, tree shake, lazy load routes |57| **Slow database query** | EXPLAIN ANALYZE | Add indexes, rewrite query, partition table |5859## Frontend Performance6061### Core Web Vitals6263| Metric | Target | Measurement |64|--------|--------|-------------|65| LCP (Largest Contentful Paint) | < 2.5s | Largest visible element |66| INP (Interaction to Next Paint) | < 200ms | Input responsiveness |67| CLS (Cumulative Layout Shift) | < 0.1 | Visual stability |6869### Optimization Techniques7071```tsx72// Code splitting73const Dashboard = lazy(() => import('./Dashboard'));7475// Image optimization76<Image77 src="/hero.jpg"78 width={1200}79 height={600}80 priority // Above fold81 placeholder="blur"82/>8384// Memoization85const MemoizedComponent = memo(ExpensiveComponent);86const memoizedValue = useMemo(() => computeExpensive(a, b), [a, b]);87const memoizedFn = useCallback(() => handleClick(id), [id]);8889// Virtual lists for long lists90<VirtualList items={items} itemHeight={50} />91```9293## Backend Performance9495```typescript96// N+1 prevention97const usersWithPosts = await prisma.user.findMany({98 include: { posts: true } // Single query with join99});100101// Caching102const cached = await redis.get(key);103if (cached) return JSON.parse(cached);104const data = await db.query();105await redis.setex(key, 3600, JSON.stringify(data));106107// Connection pooling108const pool = new Pool({ max: 20 });109110// Async processing111await queue.add('sendEmail', { userId });112```113114## Database Performance115116```sql117-- Use EXPLAIN ANALYZE118EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'x';119120-- Add indexes for frequently queried columns121CREATE INDEX idx_users_email ON users(email);122123-- Partial indexes124CREATE INDEX idx_active_users ON users(email) WHERE is_active = true;125126-- Avoid SELECT *127SELECT id, name, email FROM users;128129-- Pagination130SELECT * FROM users ORDER BY id LIMIT 20 OFFSET 0;131```132133## Checklist134135| Area | Check |136|------|-------|137| Images | Optimized, lazy loaded, proper format |138| JS Bundle | Code split, tree shaken, minified |139| CSS | Critical CSS inline, unused removed |140| Fonts | Preloaded, subset, font-display |141| Caching | CDN, browser cache, API cache |142| Database | Indexes, query optimization |143144## Production Readiness145146### Monitoring Setup147148```typescript149// Web Vitals reporting150import { onCLS, onINP, onLCP, onFCP, onTTFB } from 'web-vitals';151152function sendToAnalytics(metric: Metric) {153 const body = JSON.stringify({154 name: metric.name,155 value: metric.value,156 id: metric.id,157 page: window.location.pathname,158 });159160 // Use sendBeacon for reliability161 navigator.sendBeacon('/analytics', body);162}163164onCLS(sendToAnalytics);165onINP(sendToAnalytics);166onLCP(sendToAnalytics);167onFCP(sendToAnalytics);168onTTFB(sendToAnalytics);169```170171### Performance Budget172173```javascript174// webpack.config.js or vite.config.ts175{176 performance: {177 maxAssetSize: 250000, // 250KB178 maxEntrypointSize: 500000, // 500KB179 hints: 'error',180 },181}182183// Lighthouse CI budget184// lighthouserc.js185module.exports = {186 ci: {187 collect: {188 url: ['http://localhost:3000/'],189 },190 assert: {191 assertions: {192 'categories:performance': ['error', { minScore: 0.9 }],193 'first-contentful-paint': ['error', { maxNumericValue: 2000 }],194 'largest-contentful-paint': ['error', { maxNumericValue: 2500 }],195 'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],196 'total-blocking-time': ['error', { maxNumericValue: 300 }],197 },198 },199 },200};201```202203### Backend Optimization204205```typescript206// Response compression207import compression from 'compression';208app.use(compression({ threshold: 1024 }));209210// Response caching headers211function setCacheHeaders(res: Response, maxAge: number) {212 res.setHeader('Cache-Control', `public, max-age=${maxAge}, stale-while-revalidate=${maxAge * 2}`);213 res.setHeader('Vary', 'Accept-Encoding');214}215216// Streaming responses217async function streamLargeData(res: Response) {218 const stream = db.users.findMany().cursor();219220 res.setHeader('Content-Type', 'application/json');221 res.write('[');222223 let first = true;224 for await (const user of stream) {225 if (!first) res.write(',');226 res.write(JSON.stringify(user));227 first = false;228 }229230 res.write(']');231 res.end();232}233234// Query optimization235const users = await prisma.user.findMany({236 select: { id: true, name: true, email: true }, // Only needed fields237 where: { isActive: true },238 take: 20,239 orderBy: { createdAt: 'desc' },240});241```242243### Database Optimization244245```sql246-- Composite indexes for common queries247CREATE INDEX idx_users_active_created248ON users(is_active, created_at DESC)249WHERE is_active = true;250251-- Query analysis252EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)253SELECT * FROM users WHERE email = 'test@example.com';254255-- Connection pooling configuration256-- pgbouncer.ini257[pgbouncer]258pool_mode = transaction259default_pool_size = 20260max_client_conn = 100261```262263### CI Performance Testing264265```yaml266# .github/workflows/performance.yml267name: Performance268269on:270 pull_request:271 branches: [main]272273jobs:274 lighthouse:275 runs-on: ubuntu-latest276 steps:277 - uses: actions/checkout@v4278279 - name: Build280 run: npm run build281282 - name: Run Lighthouse CI283 uses: treosh/lighthouse-ci-action@v10284 with:285 configPath: ./lighthouserc.js286 uploadArtifacts: true287288 bundle-size:289 runs-on: ubuntu-latest290 steps:291 - uses: actions/checkout@v4292293 - name: Build294 run: npm run build295296 - name: Check bundle size297 uses: siddharthkp/bundlesize@v2298 with:299 files: 'dist/*.js'300 maxSize: '250KB'301```302303### Caching Strategy304305```typescript306// Cache layers307const cacheStrategy = {308 // L1: In-memory (fastest, smallest)309 memory: new LRUCache({ max: 1000, ttl: 60000 }),310311 // L2: Redis (fast, larger)312 redis: new Redis({ maxRetriesPerRequest: 3 }),313314 // L3: CDN (edge caching)315 cdn: {316 cacheControl: 'public, max-age=31536000, immutable', // Static assets317 staleWhileRevalidate: 'public, max-age=60, stale-while-revalidate=600', // API318 },319};320321async function getCachedData<T>(key: string, fetcher: () => Promise<T>): Promise<T> {322 // Check memory323 const memoryHit = cacheStrategy.memory.get(key);324 if (memoryHit) return memoryHit as T;325326 // Check Redis327 const redisHit = await cacheStrategy.redis.get(key);328 if (redisHit) {329 const data = JSON.parse(redisHit);330 cacheStrategy.memory.set(key, data);331 return data;332 }333334 // Fetch and cache335 const data = await fetcher();336 cacheStrategy.memory.set(key, data);337 await cacheStrategy.redis.setex(key, 300, JSON.stringify(data));338339 return data;340}341```342343### Monitoring Metrics344345| Metric | Target |346|--------|--------|347| LCP | < 2.5s |348| INP | < 200ms |349| CLS | < 0.1 |350| TTFB | < 200ms |351| API p95 latency | < 500ms |352| Database query time | < 100ms |353| Cache hit rate | > 90% |354355### Production Checklist356357- [ ] Core Web Vitals monitored358- [ ] Performance budget set359- [ ] Lighthouse CI in pipeline360- [ ] Bundle size monitoring361- [ ] Image optimization362- [ ] Code splitting enabled363- [ ] Compression enabled364- [ ] Caching strategy defined365- [ ] Database indexes optimized366- [ ] CDN configured367368## Reference Documentation369- [Bundle Analysis](quick-ref/bundle.md)370- [Caching Strategies](quick-ref/caching.md)