| name | Performance Optimizer |
| description | Optimize application performance and scalability. Use when investigating slow applications, scaling bottlenecks, or improving response times. Covers profiling, caching, database optimization, and frontend performance. |
| version | 1.0.0 |
Performance Optimizer
Make applications fast, scalable, and cost-efficient.
Core Principle
Measure first, optimize second. Don't guess at bottlenecks—profile, measure, then fix the slowest parts.
Performance Budget
Web Vitals (Target Metrics)
Core Web Vitals:
Largest Contentful Paint (LCP): < 2.5s
First Input Delay (FID): < 100ms
Cumulative Layout Shift (CLS): < 0.1
Additional Metrics:
First Contentful Paint (FCP): < 1.8s
Time to Interactive (TTI): < 3.8s
Total Blocking Time (TBT): < 200ms
Speed Index: < 3.4s
Backend Metrics:
API Response Time (P95): < 500ms
Database Query Time (P95): < 100ms
Server Response Time (TTFB): < 600ms
Phase 1: Profiling & Measurement
Goal: Identify actual bottlenecks, not perceived ones
Frontend Profiling
Chrome DevTools:
lighthouse https:
React DevTools Profiler:
import { Profiler } from 'react'
function onRenderCallback(id, phase, actualDuration) {
console.log(`${id} (${phase}) took ${actualDuration}ms`)
}
;<Profiler id="ExpensiveComponent" onRender={onRenderCallback}>
<ExpensiveComponent />
</Profiler>
Backend Profiling
Node.js Profiling:
node --prof app.js
node --prof-process isolate-0x*.log > processed.txt
npm i -g 0x
0x app.js
Python Profiling:
import cProfile
import pstats
cProfile.run('slow_function()', 'output.prof')
p = pstats.Stats('output.prof')
p.sort_stats('cumulative').print_stats(20)
Database Profiling
PostgreSQL:
ALTER DATABASE yourdb SET log_min_duration_statement = 100;
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM users WHERE email = 'test@example.com';
SELECT query, mean_exec_time, calls
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 20;
MongoDB:
db.setProfilingLevel(1, { slowms: 100 })
db.system.profile.find({ millis: { $gt: 100 } }).sort({ ts: -1 })
db.collection.find({ email: 'test@example.com' }).explain('executionStats')
Phase 2: Database Optimization
Add Strategic Indexes
SELECT * FROM users WHERE email = 'user@example.com';
CREATE INDEX idx_users_email ON users(email);
SELECT * FROM users WHERE email = 'user@example.com';
CREATE INDEX idx_posts_user_date ON posts(user_id, created_at DESC);
SELECT * FROM posts WHERE user_id = 123 ORDER BY created_at DESC;
CREATE INDEX idx_active_users ON users(created_at) WHERE is_active = true;
Eliminate N+1 Queries
const users = await User.findAll()
for (const user of users) {
user.posts = await Post.findAll({ where: { userId: user.id } })
}
const users = await User.findAll({
include: [{ model: Post }]
})
const userLoader = new DataLoader(async userIds => {
const users = await User.findAll({ where: { id: userIds } })
return userIds.map(id => users.find(u => u.id === id))
})
Query Optimization
SELECT * FROM users WHERE id = 1;
SELECT id, name, email FROM users WHERE id = 1;
SELECT * FROM posts ORDER BY created_at DESC;
SELECT * FROM posts ORDER BY created_at DESC LIMIT 20;
SELECT * FROM users WHERE LOWER(email) = 'user@example.com';
SELECT * FROM users WHERE email = 'user@example.com';
Connection Pooling
import { Pool } from 'pg'
const pool = new Pool({
max: 20,
min: 5,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000
})
const client = await pool.connect()
try {
const result = await client.query('SELECT * FROM users')
return result.rows
} finally {
client.release()
}
Phase 3: Caching Strategy
Multi-Layer Caching
Browser Cache (HTTP headers)
↓
CDN Cache (Cloudflare, CloudFront)
↓
Application Cache (Redis, Memcached)
↓
Database Query Cache
↓
Database
Redis Caching
import Redis from 'ioredis'
const redis = new Redis({
maxRetriesPerRequest: 3,
enableReadyCheck: true
})
async function getUser(id: string): Promise<User> {
const cacheKey = `user:${id}`
const cached = await redis.get(cacheKey)
if (cached) {
return JSON.parse(cached)
}
const user = await db.users.findById(id)
await redis.setex(cacheKey, 3600, JSON.stringify(user))
return user
}
async function updateUser(id: string, data: Partial<User>) {
await db.users.update(id, data)
await redis.del(`user:${id}`)
}
HTTP Caching Headers
app.use((req, res, next) => {
if (req.url.match(/\.(js|css|png|jpg|jpeg|gif|svg|woff|woff2)$/)) {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
}
if (req.url.endsWith('.html') || req.url === '/') {
res.setHeader('Cache-Control', 'no-cache, must-revalidate')
}
if (req.url.startsWith('/api/')) {
res.setHeader('Cache-Control', 'public, max-age=300')
res.setHeader('ETag', generateETag(req.url))
}
next()
})
CDN Configuration
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
import { lazy, Suspense } from 'react'
import Dashboard from './Dashboard'
import AdminPanel from './AdminPanel'
const Dashboard = lazy(() => import('./Dashboard'))
const AdminPanel = lazy(() => import('./AdminPanel'))
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/admin" element={<AdminPanel />} />
</Routes>
</Suspense>
)
}
import dynamic from 'next/dynamic'
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <LoadingSpinner />,
ssr: false
})
Image Optimization
import Image from 'next/image'
<Image
src="/photo.jpg"
width={800}
height={600}
alt="Description"
loading="lazy"
placeholder="blur"
quality={75}
/>
<picture>
<source srcset="image.webp" type="image/webp" />
<source srcset="image.jpg" type="image/jpeg" />
<img src="image.jpg" alt="Description" loading="lazy" />
</picture>
<img
srcset="
small.jpg 480w,
medium.jpg 768w,
large.jpg 1200w
"
sizes="(max-width: 480px) 480px, (max-width: 768px) 768px, 1200px"
src="medium.jpg"
alt="Description"
/>
Bundle Size Optimization
npm run build -- --analyze
npm uninstall unused-package
import _ from 'lodash'
import debounce from 'lodash/debounce'
const moment = await import('moment')
React Performance
import { useMemo } from 'react'
function DataTable({ data }) {
const sortedData = useMemo(
() => data.sort((a, b) => a.name.localeCompare(b.name)),
[data]
)
return <Table data={sortedData} />
}
import { memo } from 'react'
const ExpensiveComponent = memo(function ExpensiveComponent({ data }) {
return <div>{/* expensive rendering */}</div>
})
import { useCallback } from 'react'
function Parent() {
const handleClick = useCallback(() => {
console.log('Clicked')
}, [])
return <ExpensiveChild onClick={handleClick} />
}
import { FixedSizeList } from 'react-window'
<FixedSizeList
height={600}
itemCount={10000}
itemSize={50}
>
{({ index, style }) => (
<div style={style}>Row {index}</div>
)}
</FixedSizeList>
Phase 5: Backend Optimization
Async Background Processing
app.post('/send-email', async (req, res) => {
await sendEmail(req.body)
res.json({ success: true })
})
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' })
})
emailQueue.process('send', async job => {
await sendEmail(job.data)
})
API Response Optimization
import compression from 'compression'
app.use(compression())
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()
}
})
})
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
import rateLimit from 'express-rate-limit'
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: 'Too many requests, please try again later'
})
app.use('/api/', apiLimiter)
const authLimiter = rateLimit({
windowMs: 60 * 60 * 1000,
max: 5,
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:
app.use((req, res, next) => {
const start = Date.now()
res.on('finish', () => {
const duration = Date.now() - start
metrics.recordResponseTime(req.path, duration)
if (duration > 1000) {
logger.warn(`Slow request: ${req.path} took ${duration}ms`)
}
})
next()
})
db.on('query', (query, duration) => {
if (duration > 100) {
logger.warn(`Slow query: ${query} took ${duration}ms`)
}
})
Performance Dashboards
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 ✅
Backend ✅
Database ✅
Caching ✅
Infrastructure ✅
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)