10 Node.js Performance Tips
Performance matters. Here are 10 tips to make your Node.js applications faster.
1. Use Async Operations
Never use synchronous methods in production:
// Bad
const data = fs.readFileSync('file.txt');
// Good
const data = await fs.promises.readFile('file.txt');
2. Enable Gzip Compression
Reduce response size significantly:
const compression = require('compression');
app.use(compression());
3. Cache Everything Possible
Use Redis for frequently accessed data:
const redis = require('redis');
const client = redis.createClient();
async function getUser(id) {
const cached = await client.get(`user:${id}`);
if (cached) return JSON.parse(cached);
const user = await db.findUser(id);
await client.set(`user:${id}`, JSON.stringify(user), 'EX', 3600);
return user;
}
4. Use Connection Pooling
Database connections are expensive:
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
database: 'myapp'
});
5. Implement Rate Limiting
Protect your API from abuse:
const rateLimit = require('express-rate-limit');
app.use(rateLimit({
windowMs: 15 * 60 * 1000,
max: 100
}));
6. Use Clustering
Utilize all CPU cores:
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isPrimary) {
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
require('./server');
}
7. Stream Large Files
Don't load entire files into memory:
app.get('/download', (req, res) => {
const stream = fs.createReadStream('large-file.zip');
stream.pipe(res);
});
8. Use PM2 for Process Management
PM2 handles restarts and load balancing:
pm2 start app.js -i max
9. Profile Your Application
Find bottlenecks with Node's built-in profiler:
node --prof app.js
node --prof-process isolate-*.log > profile.txt
10. Keep Dependencies Updated
Newer versions often include performance improvements:
npm outdated
npm update
Conclusion
Apply these tips to see immediate performance improvements in your Node.js applications.