The async_hooks module provides an API to track asynchronous resources in Node.js. Here's how to use it for debugging, tracing, and context propagation.
Basic Setup#
AsyncLocalStorage (Recommended)#
Request Tracing#
Execution Context Tracking#
Performance Monitoring#
Database Transaction Context#
Error Context Propagation#
Resource Cleanup Tracking#
Logging Context#
Best Practices#
AsyncLocalStorage:
✓ Prefer over raw async_hooks
✓ Use for request context
✓ Use for transaction scoping
✓ Use for logging context
Performance:
✓ Minimize hook callbacks
✓ Avoid heavy processing in hooks
✓ Disable when not needed
✓ Use sampling for tracing
Patterns:
✓ Request ID propagation
✓ Transaction management
✓ Performance tracing
✓ Error context enrichment
Avoid:
✗ Storing large objects in context
✗ Modifying context after creation
✗ Relying on context in cleanup
✗ Circular references in context
Conclusion#
The async_hooks module enables powerful async context tracking in Node.js. Use AsyncLocalStorage for request tracing, transaction management, and contextual logging. It automatically propagates context through async boundaries without manual passing. For advanced use cases like resource tracking and debugging, use the lower-level createHook API. Remember that async_hooks has performance overhead, so use it judiciously in production.