MCPInstall

performance-optimization

Optimize Node.js application performance with caching, clustering, profiling, and monitoring techniques

Installs
64
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill performance-optimization
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads performance-optimization automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Performance Optimization Skill

Master Node.js performance optimization for fast, scalable, and efficient backend applications.

Quick Start

Optimize in 4 areas:

  1. Caching - Redis/in-memory caching
  2. Clustering - Use all CPU cores
  3. Profiling - Find bottlenecks
  4. Monitoring - Track performance

Core Concepts

Caching with Redis

const redis = require('redis');
const client = redis.createClient({ url: process.env.REDIS_URL });

// Cache middleware
async function cacheMiddleware(req, res, next) {
  const key = `cache:${req.originalUrl}`;

  const cached = await client.get(key);
  if (cached) {
    return res.json(JSON.parse(cached));
  }

  // Override res.json to cache response
  const originalJson = res.json.bind(res);
  res.json = (data) => {
    client.setEx(key, 3600, JSON.stringify(data)); // 1 hour
    originalJson(data);
  };

  next();
}

// Usage
app.get('/api/users', cacheMiddleware, getUsers);

Clustering (Use All CPU Cores)

const cluster = require('cluster');
const os = require('os');

if (cluster.isMaster) {
  const numCPUs = os.cpus().length;

  console.log(`Master ${process.pid} starting ${numCPUs} workers`);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker) => {
    console.log(`Worker ${worker.process.pid} died, restarting...`);
    cluster.fork();
  });
} else {
  // Worker process - start Express server
  const app = require('./app');
  app.listen(3000, () => {
    console.log(`Worker ${process.pid} started`);
  });
}

Learning Path

Beginner (2-3 weeks)

  • ✅ Implement basic caching
  • ✅ Use compression middleware
  • ✅ Optimize database queries
  • ✅ Enable production mode

Intermediate (4-5 weeks)

  • ✅ Setup Redis caching
  • ✅ Implement clustering
  • ✅ Database indexing
  • ✅ Response pagination

Advanced (6-8 weeks)

  • ✅ CPU/memory profiling
  • ✅ Load balancing
  • ✅ CDN integration
  • ✅ Performance monitoring

Database Optimization

Connection Pooling

// PostgreSQL pool
const { Pool } = require('pg');

const pool = new Pool({
  max: 20,  // Max connections
  min: 5,   // Min connections
  idleTimeoutMillis: 30000
});

// MongoDB with Mongoose
mongoose.connect(uri, {
  maxPoolSize: 10,
  minPoolSize: 5
});

Query Optimization

// ❌ Bad: N+1 query problem
const users = await User.find();
for (const user of users) {
  user.posts = await Post.find({ userId: user.id }); // N queries
}

// ✅ Good: Single query with join
const users = await User.find().populate('posts'); // 1 query

// Add indexes
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ createdAt: -1 });

// Use lean() for read-only queries (faster)
const users = await User.find().lean(); // Returns plain objects

Pagination

async function getUsers(req, res) {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  const skip = (page - 1) * limit;

  const [users, total] = await Promise.all([
    User.find().limit(limit).skip(skip),
    User.countDocuments()
  ]);

  res.json({
    data: users,
    pagination: {
      page,
      limit,
      total,
      pages: Math.ceil(total / limit)
    }
  });
}

Response Optimization

Compression

const compression = require('compression');

app.use(compression({
  level: 6,
  threshold: 1024  // Only compress > 1KB
}));

Response Caching Headers

app.get('/api/static-data', (req, res) => {
  res.set('Cache-Control', 'public, max-age=3600'); // Cache 1 hour
  res.json(data);
});

// For frequently changing data
res.set('Cache-Control', 'public, max-age=60'); // Cache 1 minute

Async Optimization

Parallel Execution

// ❌ Sequential (300ms)
const users = await getUsers();    // 100ms
const posts = await getPosts();    // 100ms
const comments = await getComments(); // 100ms

// ✅ Parallel (100ms)
const [users, posts, comments] = await Promise.all([
  getUsers(),
  getPosts(),
  getComments()
]);

Stream Large Files

const fs = require('fs');

// ❌ Bad: Load entire file into memory
app.get('/large-file', async (req, res) => {
  const data = await fs.promises.readFile('large.txt');
  res.send(data);
});

// ✅ Good: Stream file
app.get('/large-file', (req, res) => {
  const stream = fs.createReadStream('large.txt');
  stream.pipe(res);
});

CPU Profiling

Built-in Profiler

# Start with profiler
node --prof app.js

# Generate readable output
node --prof-process isolate-0x*.log > profile.txt

Performance Measurement

const { performance } = require('perf_hooks');

const start = performance.now();
await heavyOperation();
const end = performance.now();
console.log(`Operation took ${end - start}ms`);

Memory Optimization

Avoid Memory Leaks

// ❌ Bad: Memory leak
const cache = {};
app.get('/data/:id', (req, res) => {
  cache[req.params.id] = data; // Never cleaned up
  res.json(data);
});

// ✅ Good: Use LRU cache with limits
const LRU = require('lru-cache');
const cache = new LRU({
  max: 500,  // Max 500 items
  maxAge: 1000 * 60 * 60  // TTL: 1 hour
});

Monitor Memory

const used = process.memoryUsage();
console.log({
  rss: `${Math.round(used.rss / 1024 / 1024)}MB`,
  heapTotal: `${Math.round(used.heapTotal / 1024 / 1024)}MB`,
  heapUsed: `${Math.round(used.heapUsed / 1024 / 1024)}MB`
});

Monitoring & APM

Winston Logging

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

// Request logging
app.use((req, res, next) => {
  const start = Date.now();

  res.on('finish', () => {
    logger.info('HTTP Request', {
      method: req.method,
      url: req.url,
      status: res.statusCode,
      duration: Date.now() - start
    });
  });

  next();
});

APM Tools

  • New Relic - Full-stack monitoring
  • Datadog - Infrastructure + APM
  • Dynatrace - AI-powered monitoring
  • PM2 Plus - Node.js specific monitoring

Load Testing

Artillery

# load-test.yml
config:
  target: 'http://localhost:3000'
  phases:
    - duration: 60
      arrivalRate: 10

scenarios:
  - name: "Get users"
    flow:
      - get:
          url: "/api/users"
artillery run load-test.yml

Performance Checklist

  • ✅ Enable Node.js production mode (NODE_ENV=production)
  • ✅ Use clustering (PM2 or cluster module)
  • ✅ Implement caching (Redis)
  • ✅ Database connection pooling
  • ✅ Add database indexes
  • ✅ Compress responses (gzip)
  • ✅ Use CDN for static assets
  • ✅ Optimize images
  • ✅ Paginate large datasets
  • ✅ Stream large files
  • ✅ Monitor with APM tools

Production Optimizations

// production.js
if (process.env.NODE_ENV === 'production') {
  // Trust proxy (for load balancer)
  app.set('trust proxy', 1);

  // Disable x-powered-by header
  app.disable('x-powered-by');

  // Enable compression
  app.use(compression());

  // Use production logger
  app.use(productionLogger());
}

When to Use

Optimize performance when:

  • Application is slow or unresponsive
  • Need to handle high traffic
  • Database queries are bottleneck
  • Memory usage is high
  • Scaling horizontally
  • Preparing for production

Related Skills

  • Express REST API (optimize API performance)
  • Async Programming (async optimization)
  • Database Integration (query optimization)
  • Docker Deployment (production deployment)

Resources

FAQ

What does the performance-optimization skill do?

Optimize Node.js application performance with caching, clustering, profiling, and monitoring techniques

How do I install performance-optimization?

Run npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill performance-optimization in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/performance-optimization/ (personal) or .claude/skills/performance-optimization/ (project).

Which AI agents can use performance-optimization?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is performance-optimization safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains performance-optimization?

It is published by pluginagentmarketplace in pluginagentmarketplace/custom-plugin-nodejs. It has 64 recorded installs.

More from pluginagentmarketplace/custom-plugin-nodejs

View all →

express-rest-api

pluginagentmarketplace/custom-plugin-nodejs

Build production-ready RESTful APIs with Express.js including routing, middleware, validation, and error handling for scalable backend services

Backend & APIs901 installs

mongoose-mongodb

pluginagentmarketplace/custom-plugin-nodejs

Work with MongoDB in Node.js using Mongoose ODM for schema design, CRUD operations, relationships, and advanced queries

Data & Databases694 installs

docker-deployment

pluginagentmarketplace/custom-plugin-nodejs

Containerize and deploy Node.js applications with Docker including multi-stage builds, Docker Compose, and production optimization

DevOps & Cloud523 installs

jwt-authentication

pluginagentmarketplace/custom-plugin-nodejs

Open the skill to read its SKILL.md instructions.

Backend & APIs226 installs

jest-testing

pluginagentmarketplace/custom-plugin-nodejs

Open the skill to read its SKILL.md instructions.

Testing & QA120 installs

async-patterns

pluginagentmarketplace/custom-plugin-nodejs

Open the skill to read its SKILL.md instructions.

Backend & APIs97 installs

Popular code quality & workflow skills

View category →

grill-me

mattpocock/skills

A relentless interview to sharpen a plan or design.

Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.

handoff

mattpocock/skills

Compact the current conversation into a handoff document for another agent to pick up.

domain-modeling

mattpocock/skills

Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR.

codebase-design

mattpocock/skills

Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.

diagnosing-bugs

mattpocock/skills

Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.