Backend

Tối ưu hiệu suất Node.js - 10 kỹ thuật quan trọng

Hướng dẫn chi tiết các kỹ thuật tối ưu hiệu suất cho ứng dụng Node.js trong production

Dũng QB5 phút đọc11 lượt xem
Tối ưu hiệu suất Node.js - 10 kỹ thuật quan trọng

Node.js là một platform mạnh mẽ cho việc xây dựng ứng dụng server-side. Tuy nhiên, để đạt được hiệu suất tối ưu trong production, bạn cần áp dụng các kỹ thuật optimization phù hợp.

1. Sử dụng Cluster Module

Node.js chạy single-threaded, nhưng bạn có thể tận dụng multi-core CPU với cluster module:

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

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

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died`);
    cluster.fork(); // Restart worker
  });
} else {
  // Workers can share any TCP connection
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello world\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}

2. Caching Strategy

Memory Caching với Redis

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

async function getCachedData(key) {
  const cached = await client.get(key);
  if (cached) {
    return JSON.parse(cached);
  }
  
  // Fetch from database
  const data = await fetchFromDatabase(key);
  
  // Cache for 1 hour
  await client.setex(key, 3600, JSON.stringify(data));
  
  return data;
}

In-Memory Caching

const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 600 });

function getCachedResponse(key) {
  const value = cache.get(key);
  if (value) {
    return value;
  }
  
  const data = expensiveOperation();
  cache.set(key, data);
  return data;
}

3. Database Query Optimization

Connection Pooling

const { Pool } = require('pg');

const pool = new Pool({
  max: 20, // Maximum number of clients
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

async function query(text, params) {
  const start = Date.now();
  const res = await pool.query(text, params);
  const duration = Date.now() - start;
  console.log('Query executed in', duration, 'ms');
  return res;
}

Indexing và Query Optimization

// 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: Use eager loading
const users = await User.findAll({
  include: [{
    model: Post,
    as: 'posts'
  }]
});

4. Async/Await và Promise Optimization

Parallel Processing

// Bad: Sequential processing
const user = await fetchUser(userId);
const posts = await fetchPosts(userId);
const comments = await fetchComments(userId);

// Good: Parallel processing
const [user, posts, comments] = await Promise.all([
  fetchUser(userId),
  fetchPosts(userId),
  fetchComments(userId)
]);

Error Handling

async function processData(data) {
  try {
    const results = await Promise.allSettled(
      data.map(item => processItem(item))
    );
    
    const successful = results
      .filter(r => r.status === 'fulfilled')
      .map(r => r.value);
      
    const failed = results
      .filter(r => r.status === 'rejected')
      .map(r => r.reason);
      
    return { successful, failed };
  } catch (error) {
    console.error('Processing failed:', error);
    throw error;
  }
}

5. Memory Management

Avoid Memory Leaks

// Bad: Event listener not removed
class DataProcessor {
  constructor() {
    process.on('message', this.handleMessage.bind(this));
  }
  
  handleMessage(msg) {
    // Process message
  }
}

// Good: Clean up listeners
class DataProcessor {
  constructor() {
    this.handleMessage = this.handleMessage.bind(this);
    process.on('message', this.handleMessage);
  }
  
  destroy() {
    process.removeListener('message', this.handleMessage);
  }
  
  handleMessage(msg) {
    // Process message
  }
}

Stream Processing cho Large Data

const fs = require('fs');
const zlib = require('zlib');

// Process large file with streams
fs.createReadStream('large-file.txt')
  .pipe(zlib.createGzip())
  .pipe(fs.createWriteStream('large-file.txt.gz'))
  .on('finish', () => console.log('File compressed'));

6. Compression và Minification

const compression = require('compression');
const express = require('express');
const app = express();

// Enable gzip compression
app.use(compression({
  level: 6,
  threshold: 100 * 1024 // Only compress files larger than 100KB
}));

7. Load Balancing với PM2

// ecosystem.config.js
module.exports = {
  apps: [{
    name: 'api',
    script: './server.js',
    instances: 'max',
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'production'
    },
    error_file: './logs/err.log',
    out_file: './logs/out.log',
    log_file: './logs/combined.log',
    time: true
  }]
};

8. Monitoring và Profiling

Performance Monitoring

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

function measurePerformance(fn, name) {
  return async (...args) => {
    const start = performance.now();
    try {
      const result = await fn(...args);
      const end = performance.now();
      console.log(`${name} took ${end - start}ms`);
      return result;
    } catch (error) {
      const end = performance.now();
      console.error(`${name} failed after ${end - start}ms`);
      throw error;
    }
  };
}

9. Security Best Practices

const helmet = require('helmet');
const rateLimit = require('express-rate-limit');

// Security headers
app.use(helmet());

// Rate limiting
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
});

app.use('/api/', limiter);

10. Code Optimization Tips

Use Built-in Methods

// Bad: Manual loop
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

// Good: Built-in reduce
const sum = numbers.reduce((acc, num) => acc + num, 0);

Avoid Blocking Operations

// Bad: Synchronous file read
const data = fs.readFileSync('file.txt', 'utf8');

// Good: Asynchronous file read
const data = await fs.promises.readFile('file.txt', 'utf8');

Kết luận

Tối ưu hiệu suất Node.js là một quá trình liên tục. Hãy luôn monitor, measure và improve ứng dụng của bạn. Sử dụng các công cụ như New Relic, DataDog hoặc PM2 để theo dõi performance metrics và đưa ra quyết định optimization phù hợp.

Cần người làm giúp?Dịch vụ bảo trì hệ thống

Dũng QB

Lập trình viên fullstack ở Sài Gòn, viết code từ 2014. Chủ yếu viết phần mềm cho người làm marketing và bán hàng trên Facebook, TikTok, Telegram.

Về mình

Bình luận

Chưa có bình luận nào. Bạn là người đầu tiên.