) {
await db.users.update(id, data)
await redis.del(`user:${id}`) // Invalidate cache
}
```
### HTTP Caching Headers
```typescript
// Express middleware
app.use((req, res, next) => {
// Static assets: cache for 1 year
if (req.url.match(/\.(js|css|png|jpg|jpeg|gif|svg|woff|woff2)$/)) {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
}
// HTML: no cache (always revalidate)
if (req.url.endsWith('.html') || req.url === '/') {
res.setHeader('Cache-Control', 'no-cache, must-revalidate')
}
// API responses: cache for 5 minutes
if (req.url.startsWith('/api/')) {
res.setHeader('Cache-Control', 'public, max-age=300')
res.setHeader('ETag', generateETag(req.url))
}
next()
})
```
### CDN Configuration
```yaml
Static Assets to CDN:
- Images: /images/**
- JavaScript: /js/**
- CSS: /css/**
- Fonts: /fonts/**
CDN Settings:
- Cache duration: 1 year (with versioned URLs)
- Gzip/Brotli compression: enabled
- Image optimization: WebP conversion
- Purge on deploy: yes (via API)
Recommended CDNs:
- Cloudflare (free tier excellent)
- CloudFront (AWS integration)
- Fastly (enterprise, very fast)
```
---
## Phase 4: Frontend Optimization
### Code Splitting & Lazy Loading
```typescript
// React lazy loading
import { lazy, Suspense } from 'react'
// ❌ Bad: Load everything upfront
import Dashboard from './Dashboard'
import AdminPanel from './AdminPanel'
// ✅ Good: Lazy load routes
const Dashboard = lazy(() => import('./Dashboard'))
const AdminPanel = lazy(() => import('./AdminPanel'))
function App() {
return (
}>
} />
} />
)
}
// Next.js dynamic imports
import dynamic from 'next/dynamic'
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => ,
ssr: false // Skip SSR for this component
})
```
### Image Optimization
```jsx
// Next.js Image component (automatic optimization)
import Image from 'next/image'
// WebP format with fallback
// Responsive images
```
### Bundle Size Optimization
```bash
# Analyze bundle
npm run build -- --analyze
# Reduce bundle size:
# 1. Remove unused dependencies
npm uninstall unused-package
# 2. Use tree-shaking compatible imports
# ❌ Bad
import _ from 'lodash'
# ✅ Good
import debounce from 'lodash/debounce'
# 3. Dynamic imports for large libraries
const moment = await import('moment')
# 4. Minification (automatic in production builds)
# Vite/Next.js handle this automatically
```
### React Performance
```typescript
// 1. Memoize expensive calculations
import { useMemo } from 'react'
function DataTable({ data }) {
const sortedData = useMemo(
() => data.sort((a, b) => a.name.localeCompare(b.name)),
[data]
)
return
}
// 2. Memoize components
import { memo } from 'react'
const ExpensiveComponent = memo(function ExpensiveComponent({ data }) {
// Only re-renders if data changes
return {/* expensive rendering */}
})
// 3. useCallback for stable function references
import { useCallback } from 'react'
function Parent() {
const handleClick = useCallback(() => {
console.log('Clicked')
}, [])
return
}
// 4. Virtualize long lists
import { FixedSizeList } from 'react-window'
{({ index, style }) => (
Row {index}
)}
```
---
## Phase 5: Backend Optimization
### Async Background Processing
```typescript
// ❌ Bad: Synchronous (slow response)
app.post('/send-email', async (req, res) => {
await sendEmail(req.body) // 3 seconds
res.json({ success: true })
})
// ✅ Good: Queue job (fast response)
import Bull from 'bull'
const emailQueue = new Bull('emails', 'redis://localhost:6379')
app.post('/send-email', async (req, res) => {
await emailQueue.add('send', req.body)
res.json({ success: true, message: 'Email queued' })
})
// Process jobs in background worker
emailQueue.process('send', async job => {
await sendEmail(job.data)
})
```
### API Response Optimization
```typescript
// 1. Compression
import compression from 'compression'
app.use(compression()) // Gzip responses
// 2. Pagination
app.get('/api/posts', async (req, res) => {
const page = parseInt(req.query.page) || 1
const limit = parseInt(req.query.limit) || 20
const posts = await db.posts.findAll({
offset: (page - 1) * limit,
limit: limit
})
res.json({
data: posts,
pagination: {
page,
limit,
total: await db.posts.count()
}
})
})
// 3. Field filtering (GraphQL-style)
app.get('/api/users/:id', async (req, res) => {
const fields = req.query.fields?.split(',') || ['id', 'name', 'email']
const user = await db.users.findById(req.params.id, {
attributes: fields
})
res.json(user)
})
```
### Rate Limiting
```typescript
import rateLimit from 'express-rate-limit'
// General API rate limit
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
message: 'Too many requests, please try again later'
})
app.use('/api/', apiLimiter)
// Stricter limit for expensive endpoints
const authLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 5, // 5 requests per hour
skipSuccessfulRequests: true
})
app.post('/api/auth/login', authLimiter, loginHandler)
```
---
## Phase 6: Monitoring & Alerting
### Application Performance Monitoring (APM)
**Tools**:
- **Sentry**: Error tracking + performance
- **New Relic**: Full-stack APM
- **Datadog**: Infrastructure + APM
- **Vercel Analytics**: Next.js optimized
**Custom Monitoring**:
```typescript
// Track response times
app.use((req, res, next) => {
const start = Date.now()
res.on('finish', () => {
const duration = Date.now() - start
// Log to monitoring service
metrics.recordResponseTime(req.path, duration)
// Alert on slow requests
if (duration > 1000) {
logger.warn(`Slow request: ${req.path} took ${duration}ms`)
}
})
next()
})
// Track database query times
db.on('query', (query, duration) => {
if (duration > 100) {
logger.warn(`Slow query: ${query} took ${duration}ms`)
}
})
```
### Performance Dashboards
```yaml
Key Metrics to Track:
- Response time (P50, P95, P99)
- Throughput (requests/second)
- Error rate (%)
- Database query times
- Cache hit ratio
- Memory usage
- CPU usage
Alerting Thresholds:
- P95 response time > 1s
- Error rate > 1%
- Cache hit ratio < 80%
- Memory usage > 80%
```
---
## Optimization Checklist
### Frontend ✅
- [ ] Lighthouse score > 90
- [ ] LCP < 2.5s
- [ ] FID < 100ms
- [ ] CLS < 0.1
- [ ] Bundle size < 200KB (initial)
- [ ] Images optimized (WebP, lazy loading)
- [ ] Code splitting implemented
- [ ] Critical CSS inlined
### Backend ✅
- [ ] P95 response time < 500ms
- [ ] Database queries indexed
- [ ] N+1 queries eliminated
- [ ] Connection pooling enabled
- [ ] Background jobs async
- [ ] Rate limiting configured
- [ ] API responses compressed
### Database ✅
- [ ] Slow query log enabled
- [ ] All queries < 100ms (P95)
- [ ] Indexes on foreign keys
- [ ] Indexes on WHERE/ORDER BY columns
- [ ] Query explain plans reviewed
- [ ] Connection pool sized correctly
### Caching ✅
- [ ] Redis/Memcached configured
- [ ] CDN for static assets
- [ ] HTTP cache headers set
- [ ] Cache hit ratio > 80%
- [ ] Cache invalidation strategy
### Infrastructure ✅
- [ ] Auto-scaling configured
- [ ] Load balancer healthy
- [ ] Monitoring/alerting active
- [ ] Logs centralized
- [ ] Backups automated
---
## Related Resources
**Related Skills**:
- `deployment-advisor` - For infrastructure optimization
- `frontend-builder` - For React performance patterns
- `api-designer` - For API optimization
**Related Patterns**:
- `META/DECISION-FRAMEWORK.md` - Scaling decisions
- `STANDARDS/architecture-patterns/caching-patterns.md` - Caching strategies (when created)
**Related Playbooks**:
- `PLAYBOOKS/optimize-database-performance.md` - DB optimization steps (when created)
- `PLAYBOOKS/frontend-performance-audit.md` - Frontend audit procedure (when created)