惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
Vercel News
Vercel News
C
Check Point Blog
G
Google Developers Blog
博客园 - 司徒正美
量子位
Engineering at Meta
Engineering at Meta
S
SegmentFault 最新的问题
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
A
About on SuperTechFans
美团技术团队
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
Jina AI
Jina AI
Y
Y Combinator Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
J
Java Code Geeks
MongoDB | Blog
MongoDB | Blog
人人都是产品经理
人人都是产品经理
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The Cloudflare Blog
U
Unit 42

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
The Node.js Patterns I Wish I Knew 3 Years Ago
Muhammad Zul · 2026-05-08 · via DEV Community

Muhammad Zulqarnain

Node.js is amazing for shipping fast. It's also amazing at letting you ship broken things fast.

I've built a lot of broken things. Here are the patterns that make Node.js systems not break.

Pattern 1: EventEmitter for Internal Pub/Sub

import { EventEmitter } from 'events';
const orderEvents = new EventEmitter();

async function createOrder(userId, items) {
  const order = await db.orders.create({ userId, items });
  orderEvents.emit('order:created', order);
  return order;
}

orderEvents.on('order:created', async (order) => {
  await sendConfirmationEmail(order).catch(err => logger.error('Email failed', err));
});

orderEvents.on('order:created', async (order) => {
  await logAnalytics('order_created', order).catch(err => logger.error('Analytics failed', err));
});

Enter fullscreen mode Exit fullscreen mode

Result: Order creation returns in 50ms. Side effects async. If email fails, order still succeeded.

Pattern 2: Worker Threads for CPU-Bound Tasks

import { Worker } from 'worker_threads';
const workers = Array(os.cpus().length).fill(null).map(() => new Worker('./worker.js'));
let currentWorker = 0;

function processImage(imageBuffer) {
  return new Promise((resolve, reject) => {
    const worker = workers[currentWorker];
    currentWorker = (currentWorker + 1) % workers.length;
    const timer = setTimeout(() => reject(new Error('Worker timeout')), 30000);
    worker.once('message', (result) => { clearTimeout(timer); resolve(result); });
    worker.once('error', reject);
    worker.postMessage({ imageBuffer });
  });
}

Enter fullscreen mode Exit fullscreen mode

Result: Heavy computation doesn't block the main thread.

Pattern 3: Domain-Specific Error Classes

class AppError extends Error {
  constructor(message, statusCode, code) {
    super(message);
    this.statusCode = statusCode;
    this.code = code;
  }
}

class NotFoundError extends AppError {
  constructor(message) { super(message, 404, 'NOT_FOUND'); }
}

class ValidationError extends AppError {
  constructor(message) { super(message, 400, 'VALIDATION_ERROR'); }
}

app.get('/users/:id', async (req, res, next) => {
  try {
    const user = await getUser(req.params.id);
    res.json(user);
  } catch (err) {
    if (err instanceof AppError) {
      res.status(err.statusCode).json({ error: err.message });
    } else {
      res.status(500).json({ error: 'Internal server error' });
    }
  }
});

Enter fullscreen mode Exit fullscreen mode

Pattern 4: Connection Pooling

const pool = new pg.Pool({
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

async function getUser(id) {
  const result = await pool.query('SELECT * FROM users WHERE id = $1', [id]);
  return result.rows[0];
}

Enter fullscreen mode Exit fullscreen mode

Pattern 5: Circuit Breaker

class CircuitBreaker {
  constructor(fn, options = {}) {
    this.fn = fn;
    this.failureThreshold = options.failureThreshold || 5;
    this.resetTimeout = options.resetTimeout || 60000;
    this.state = 'CLOSED';
    this.failureCount = 0;
    this.lastFailureTime = null;
  }

  async call(...args) {
    if (this.state === 'OPEN') {
      if (Date.now() - this.lastFailureTime > this.resetTimeout) {
        this.state = 'HALF_OPEN';
      } else {
        throw new Error('Circuit breaker is OPEN');
      }
    }
    try {
      const result = await this.fn(...args);
      this.failureCount = 0;
      this.state = 'CLOSED';
      return result;
    } catch (err) {
      this.failureCount++;
      this.lastFailureTime = Date.now();
      if (this.failureCount >= this.failureThreshold) this.state = 'OPEN';
      throw err;
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Pattern 6: Graceful Shutdown

async function gracefulShutdown() {
  server.close(async () => {
    logger.info('Server closed');
  });
  const forceShutdown = setTimeout(() => process.exit(1), 30000);
  try {
    await db.close();
    await redis.quit();
    clearTimeout(forceShutdown);
    process.exit(0);
  } catch (err) {
    process.exit(1);
  }
}
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);

Enter fullscreen mode Exit fullscreen mode

The Meta Pattern: Async Error Handling

function asyncHandler(fn) {
  return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
}

app.get('/users/:id', asyncHandler(async (req, res) => {
  const user = await db.getUser(req.params.id);
  res.json(user);
}));

app.use((err, req, res, next) => {
  logger.error('Unhandled error', err);
  res.status(500).json({ error: 'Internal server error' });
});

Enter fullscreen mode Exit fullscreen mode

These aren't fancy patterns. They're the ones that keep systems running at 3am without pages.

zunain.com