Node.js
Performance
Backend
Node.js Performance Tips: Optimizing Your Backend
Jackson MwangiNovember 10, 20247 min read
Node.js Performance Tips
Performance matters. Here are the techniques I use to keep Node.js applications fast and responsive.
1. Understand the Event Loop
The event loop is the heart of Node.js. Blocking it means slow responses for everyone.
// ❌ Bad: Blocking operation
function processData(data) {
const result = heavyComputation(data); // Blocks event loop
return result;
}
// ✅ Good: Non-blocking with setImmediate
function processData(data, callback) {
setImmediate(() => {
const result = heavyComputation(data);
callback(result);
});
}
2. Use Caching Strategically
import NodeCache from 'node-cache';
const cache = new NodeCache({ stdTTL: 300 }); // 5 min TTL
async function getUser(id) {
const cached = cache.get(`user:${id}`);
if (cached) return cached;
const user = await db.users.findById(id);
cache.set(`user:${id}`, user);
return user;
}
3. Database Optimization
- Use connection pooling
- Add proper indexes
- Paginate large queries
- Use projections to fetch only needed fields
// ❌ Fetching everything
const users = await User.find({});
// ✅ Paginated with projection
const users = await User.find({})
.select('name email avatar')
.skip(page * limit)
.limit(limit)
.lean();
4. Use Streams for Large Data
import { createReadStream } from 'fs';
import { pipeline } from 'stream/promises';
// Stream large files instead of loading into memory
app.get('/download/:file', async (req, res) => {
const stream = createReadStream(`./files/${req.params.file}`);
await pipeline(stream, res);
});
Key Takeaways
- Never block the event loop
- Cache aggressively but invalidate wisely
- Optimize database queries
- Use streams for large data
- Monitor and profile regularly
Happy optimizing!