Skip to content

Pattern trong hệ sinh thái Node.js

Node.js, Redux và XState minh hoạ các pattern hướng sự kiện và quản lý state ở quy mô lớn.

PatternDự ánỞ đâuTác dụng
Observer / Pub-SubNode.jslib/events.jsEventEmitter — nền tảng của kiến trúc hướng sự kiện trong Node
Observer / Pub-SubReduxcreateStore.tssubscribe() + dispatch() — thông báo thay đổi state
State MachineXStateStateMachine.tsThư viện finite state machine tiêu chuẩn ngành
BackpressureNode.jswritable.jswriteOrBuffer() — kiểm soát luồng highWaterMark + sự kiện drain
Iterator / Đánh giá lườiNode.jslib/internal/streams/Async iterator cho stream — for await (const chunk of stream)
Retry BackoffNode.jsdns, httpRetry phân giải DNS với backoff cấp số nhân
Dependency Graphpnpmgraph-sequencerSắp xếp topo các package workspace để xác định thứ tự build
Rate LimiterExpressexpress-rate-limitMiddleware token bucket cho rate limit API
Circuit Breakeropossumlib/circuit.jsCircuit breaker Node.js cho phục hồi microservice
Event LoopNode.js (libuv)deps/uv/src/unix/core.cuv_run() — ghép kênh I/O đơn luồng qua epoll/kqueue
Middleware ChainKoa.jskoa-composeGhép middleware thành pipeline mô hình hành tây với async/await

Cách chúng kết hợp: Một request HTTP

Khi server Express/Koa xử lý một request, các pattern kết hợp từ lớp mạng cho tới response:

Incoming HTTP request
1
Event Loop

libuv's uv_run() picks up the socket event from epoll/kqueue. The request is dispatched to the JS callback on the main thread. No threads blocked.

2
Rate Limiter

express-rate-limit checks the token bucket. If the client exceeded their quota, respond 429 immediately.

3
Middleware Chain

Koa-compose runs middleware in onion order: auth → validate → handler → log. Each calls next() to proceed or short-circuits on error.

4
Observer

The handler emits events (e.g., 'userCreated'). EventEmitter notifies all subscribers: cache invalidation, audit log, notification service — all decoupled.

5
Backpressure

If the response streams a large file, the Writable stream applies highWaterMark. When the client reads slowly, the 'drain' event pauses the producer to prevent memory blowup.

Event loop là nền tảng: mọi thứ chạy trên một thread duy nhất và I/O không bao giờ block. Đó là lý do Node.js có thể xử lý hàng nghìn kết nối đồng thời — mỗi request dùng các pattern (middleware, observer, backpressure) thay vì sinh thêm thread.

Đọc thêm

Released under the MIT License.