Node.js9 min read

Performance Optimization

Optimize Node.js performance. Learn caching and database optimization.

Sarah Chen
December 19, 2025
0.0k0

Performance Optimization

Caching with Redis

const redis = require('redis');
const client = redis.createClient();

await client.connect();

async function getUser(id) {
  const cacheKey = `user:${id}`;
  
  const cached = await client.get(cacheKey);
  if (cached) {
    return JSON.parse(cached);
  }
  
  const user = await User.findById(id);
  
  await client.setEx(cacheKey, 3600, JSON.stringify(user));
  
  return user;
}

Database Optimization

productSchema.index({ category: 1, price: -1 });

const products = await Product.find().lean();

const users = await User.find().select('name email');

const [user, posts] = await Promise.all([
  User.findById(id),
  Post.find({ userId: id })
]);

Compression

const compression = require('compression');

app.use(compression());

Clustering

pm2 start app.js -i max

Key Takeaway

Cache with Redis. Add database indexes. Use lean() for reads. Enable compression. Run parallel operations with Promise.all(). Use clustering.

#Node.js#Performance#Optimization#Caching