The Problem: Slow Databases
Hampir setiap aplikasi mengalami database bottleneck di suatu titik. Symptoms:
- Page load times meningkat
- Spike di CPU usage
- Timeout errors
- User complaints
Solusinya: Database Optimization π
1. Query Optimization
EXPLAIN ANALYZE - Your Best Friend
-- See how PostgreSQL executes your query
EXPLAIN ANALYZE
SELECT u.id, u.name, COUNT(p.id) as post_count
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
WHERE u.created_at > '2024-01-01'
GROUP BY u.id
ORDER BY post_count DESC;
Cari pattern seperti:
- Seq Scan (sequential scan - bad)
- Index Scan (good)
- Hash Join vs Nested Loop
Rewrite Queries
-- β BAD - N+1 Problem
const users = await db.query('SELECT * FROM users');
for (user of users) {
user.posts = await db.query('SELECT * FROM posts WHERE user_id = ?', user.id);
}
-- β
GOOD - Single Join Query
const users = await db.query(`
SELECT u.*, json_agg(p) as posts
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
GROUP BY u.id
`);
2. Indexing Strategy
Understanding Indexes
-- Create index
CREATE INDEX idx_users_email ON users(email);
-- Multi-column index (order matters!)
CREATE INDEX idx_posts_user_created ON posts(user_id, created_at DESC);
-- Partial index (smaller = faster)
CREATE INDEX idx_active_users ON users(id) WHERE status = 'active';
-- BRIN index (for time-series data)
CREATE INDEX idx_large_table_time ON large_table USING BRIN (created_at);
When to Index
β DO:
- Foreign keys
- WHERE clauses (frequently filtered columns)
- ORDER BY columns
- JOIN conditions
β DONβT:
- Boolean columns (low cardinality)
- Columns with many NULL values
- Columns rarely used in queries
- Very small tables
Index Cost
// Indexes have trade-offs:
// β
Faster reads
// β Slower writes (need to update index)
// β More storage
// β Maintenance overhead
3. Connection Pooling
Without Connection Pooling (BAD)
// Opens new connection for EVERY request
app.get('/api/user/:id', async (req, res) => {
const conn = await database.connect(); // New connection!
const user = await conn.query('SELECT * FROM users WHERE id = ?', req.params.id);
await conn.close(); // Close connection
res.json(user);
});
// Result: Thousands of connections = System Crash π₯
With Connection Pooling (GOOD)
const pool = new Pool({
max: 20, // Max 20 connections
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
app.get('/api/user/:id', async (req, res) => {
const conn = await pool.connect(); // Reuse from pool
const user = await conn.query('SELECT * FROM users WHERE id = ?', req.params.id);
conn.release(); // Return to pool
res.json(user);
});
// Result: Efficient connection reuse β
4. Caching Strategies
Query Result Caching
const redis = require('redis');
const client = redis.createClient();
async function getUserWithCache(userId) {
const cacheKey = `user:${userId}`;
// Check cache first
const cached = await client.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
// Query database
const user = await db.query('SELECT * FROM users WHERE id = ?', userId);
// Store in cache for 1 hour
await client.setex(cacheKey, 3600, JSON.stringify(user));
return user;
}
Cache Invalidation Pattern
// Update user - invalidate cache
async function updateUser(userId, data) {
// Update database
const user = await db.query('UPDATE users SET ? WHERE id = ?', [data, userId]);
// Invalidate cache
await redis.del(`user:${userId}`);
return user;
}
5. Denormalization (When Needed)
// β Normalized approach (many JOINs)
SELECT u.id, u.name, COUNT(p.id), SUM(p.views)
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
GROUP BY u.id;
// β
Denormalized approach (single table)
// Store aggregated data in users table
users table: id, name, post_count, total_views
// Update via triggers or batch jobs
6. Partitioning for Large Tables
-- Partition by time (for time-series data)
CREATE TABLE events (
id SERIAL,
user_id INT,
event_type VARCHAR,
created_at TIMESTAMP,
data JSONB
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2024_q1 PARTITION OF events
FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');
-- Benefits:
-- β
Faster queries (scans smaller partition)
-- β
Easier maintenance
-- β
Parallel query execution
Performance Monitoring
// Track slow queries
const slowQueryThreshold = 1000; // 1 second
db.on('query', (query, duration) => {
if (duration > slowQueryThreshold) {
logger.warn('Slow query detected', {
query: query.text,
duration: `${duration}ms`,
timestamp: new Date()
});
}
});
Optimization Checklist
Database Performance Audit:
- Run EXPLAIN ANALYZE on slow queries
- Identify missing indexes
- Setup connection pooling
- Implement query result caching
- Denormalize where needed
- Setup monitoring & alerting
- Regular VACUUM & ANALYZE
- Monitor slow query log
- Load test before production
- Document all optimizations
Before & After
BEFORE OPTIMIZATION:
- Query time: 5-10 seconds
- Load: 80% CPU
- Users frustrated π
AFTER OPTIMIZATION:
- Query time: 50-100ms β‘
- Load: 10% CPU
- Users happy π
Resources: