The async_hooks module tracks the lifecycle of asynchronous resources. Here's how to use it.
Basic Usage
Execution Context Tracking
AsyncLocalStorage
Request Tracing
Logger with Context
Database Connection Tracking
Performance Monitoring
Error Tracking
Best Practices
Usage:
✓ Prefer AsyncLocalStorage over raw hooks
✓ Use for request context propagation
✓ Use for transaction management
✓ Use for distributed tracing
Performance:
✓ Minimize work in hook callbacks
✓ Use writeSync for debugging
✓ Clean up resources in destroy
✓ Disable hooks when not needed
Patterns:
✓ Logger with request context
✓ Transaction scoping
✓ Error tracking with breadcrumbs
✓ Performance monitoring
Avoid:
✗ Storing large objects
✗ Synchronous operations in hooks
✗ Memory leaks from missing cleanup
✗ Using for simple use cases
Conclusion
The async_hooks module enables tracking asynchronous operations in Node.js. Use AsyncLocalStorage for request context propagation, logging correlation, and transaction management. Raw async hooks are useful for debugging, profiling, and building custom instrumentation. Always clean up resources properly to prevent memory leaks.