| name | performance-optimization |
| description | Performance profiling, optimization techniques, and bottleneck identification. Use when addressing performance issues or optimizing systems. |
Performance Optimization Skill
Purpose
Identify performance bottlenecks and apply targeted optimizations across the stack.
Performance Investigation Methodology
Step 1: Measure First
Never optimize without data.
node --prof app.js
node --prof-process isolate-*.log > processed.txt
node --inspect app.js
wrk -t12 -c400 -d30s http://localhost:3000/api
Step 2: Identify Bottleneck Type
| Symptom | Likely Cause |
|---|
| High CPU, normal memory | CPU-bound (algorithms, parsing) |
| Normal CPU, high memory | Memory leak or large allocations |
| Low CPU, slow response | I/O bound (DB, network, disk) |
| Intermittent slowness | GC pauses, lock contention |
Step 3: Apply Targeted Fix
Optimize the bottleneck, not everything.
Database Optimization
Query Analysis
SELECT query, calls, mean_time, total_time
FROM pg_stat_statements
ORDER BY mean_time DESC
LIMIT 10;
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@example.com';
N+1 Query Problem
const users = await User.findAll();
for (const user of users) {
const orders = await Order.findAll({ where: { userId: user.id }});
}
const users = await User.findAll({
include: [{ model: Order }]
});
const users = await User.findAll();
const userIds = users.map(u => u.id);
const orders = await Order.findAll({ where: { userId: userIds }});
Indexing Strategy
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);
CREATE INDEX idx_orders_pending ON orders(status)
WHERE status = 'pending';
SELECT indexrelname, idx_scan, idx_tup_read
FROM pg_stat_user_indexes
WHERE schemaname = 'public';
Connection Pooling
const pool = new Pool({
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
Caching Strategies
Cache Hierarchy
┌─────────────────────────────────────────────────┐
│ L1: In-Memory (fastest, per-instance) │
│ └─ Map, LRU Cache │
├─────────────────────────────────────────────────┤
│ L2: Distributed Cache (fast, shared) │
│ └─ Redis, Memcached │
├─────────────────────────────────────────────────┤
│ L3: CDN (edge, static content) │
│ └─ Cloudflare, CloudFront │
├─────────────────────────────────────────────────┤
│ L4: Database (slow, persistent) │
│ └─ PostgreSQL, MongoDB │
└─────────────────────────────────────────────────┘
Caching Patterns
async function getUser(id: string) {
let user = await cache.get(`user:${id}`);
if (!user) {
user = await db.users.findById(id);
await cache.set(`user:${id}`, user, { ttl: 3600 });
}
return user;
}
async function updateUser(id: string, data: UserData) {
const user = await db.users.update(id, data);
await cache.set(`user:${id}`, user);
return user;
}
async function deleteUser(id: string) {
await db.users.delete(id);
await cache.delete(`user:${id}`);
await cache.delete(`user-list`);
}
Cache Key Design
`user:${userId}:v2`
`products:category:${categoryId}:page:${page}`
`user:${userId}:${user.updatedAt.getTime()}`
Algorithm Optimization
Time Complexity Reference
| Operation | Array | Hash Map | Sorted Array | BST |
|---|
| Search | O(n) | O(1) | O(log n) | O(log n) |
| Insert | O(1)* | O(1) | O(n) | O(log n) |
| Delete | O(n) | O(1) | O(n) | O(log n) |
Common Optimizations
const duplicates = [];
for (const item of arr1) {
for (const item2 of arr2) {
if (item === item2) duplicates.push(item);
}
}
const set = new Set(arr2);
const duplicates = arr1.filter(item => set.has(item));
let result = '';
for (const str of strings) {
result += str;
}
const result = strings.join('');
Memory Optimization
Identifying Memory Leaks
element.addEventListener('click', handler);
function createHandler() {
const largeData = new Array(1000000);
return () => console.log(largeData.length);
}
const cache = new Map();
class Parent {
child = new Child(this);
}
Memory-Efficient Patterns
import { createReadStream } from 'fs';
import { pipeline } from 'stream/promises';
await pipeline(
createReadStream('large-file.json'),
new JSONTransformStream(),
createWriteStream('output.json')
);
async function* paginatedFetch(endpoint: string) {
let page = 1;
while (true) {
const data = await fetch(`${endpoint}?page=${page}`);
if (data.length === 0) break;
yield* data;
page++;
}
}
Network Optimization
HTTP/2 and Connection Reuse
const agent = new https.Agent({
keepAlive: true,
maxSockets: 100,
});
import http2 from 'http2';
const client = http2.connect('https://api.example.com');
Compression
import compression from 'compression';
app.use(compression());
Batching Requests
for (const id of ids) {
await fetch(`/api/users/${id}`);
}
await fetch('/api/users', {
method: 'POST',
body: JSON.stringify({ ids })
});
Frontend Optimization
Bundle Size
npx webpack-bundle-analyzer stats.json
import { debounce } from 'lodash-es'; // ✅
import _ from 'lodash'; // ❌ imports everything
Rendering Performance
const MemoizedComponent = React.memo(Component);
<Component style={{ color: 'red' }} />
const styles = { color: 'red' };
<Component style={styles} />
import { FixedSizeList } from 'react-window';
Core Web Vitals
| Metric | Target | How to Improve |
|---|
| LCP (Largest Contentful Paint) | < 2.5s | Optimize images, preload critical resources |
| FID (First Input Delay) | < 100ms | Reduce JS execution, code split |
| CLS (Cumulative Layout Shift) | < 0.1 | Reserve space for dynamic content |
Profiling Commands
node --cpu-prof app.js
node --heapsnapshot-signal=SIGUSR2 app.js
kill -SIGUSR2 <pid>
perf record -g node app.js
perf report
wrk -t12 -c400 -d30s --latency http://localhost:3000/
time psql -c "SELECT ..." database
Optimization Checklist
Before You Start
Quick Wins
Deep Optimization
Validation