Optimizing Node.js Performance
Performance optimization is crucial for building scalable Node.js applications. Here are some proven strategies to boost your app’s performance.
Use Asynchronous Operations#
Always prefer asynchronous operations to avoid blocking the event loop:
// Bad - Blocking
const fs = require('fs');
const data = fs.readFileSync('/file.txt', 'utf8');
// Good - Non-blocking
const fs = require('fs').promises;
const data = await fs.readFile('/file.txt', 'utf8');Implement Caching#
Caching can dramatically improve response times:
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 600 });
async function getUser(userId) {
// Check cache first
const cachedUser = cache.get(`user_${userId}`);
if (cachedUser) {
return cachedUser;
}
// Fetch from database
const user = await db.users.findById(userId);
// Store in cache
cache.set(`user_${userId}`, user);
return user;
}Use Cluster Module#
Leverage multiple CPU cores with the cluster module:
const cluster = require('cluster');
const os = require('os');
const express = require('express');
if (cluster.isMaster) {
const numCPUs = os.cpus().length;
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000);
}Optimize Database Queries#
Use indexes and avoid N+1 queries:
// Bad - N+1 query problem
const users = await User.findAll();
for (const user of users) {
user.posts = await Post.findAll({ where: { userId: user.id } });
}
// Good - Single query with include
const users = await User.findAll({
include: [{ model: Post }]
});Monitor and Profile#
Use tools like clinic.js or built-in profiling:
# Install clinic.js
npm install -g clinic
# Profile your application
clinic doctor -- node app.jsConclusion#
Performance optimization is an ongoing process. Start with these techniques and continuously monitor your application to identify bottlenecks.