Node microservices, hooks and correlation ids

I once gave a talk on microservices using Node.js which you can watch here and complained about the difficulty in passing headers such as a correlation id onto downstream services when making http requests. Since there is no ThreadLocale like in Java and Node.js is single threaded my inkling at the time was that I had to pass the headers I wished to propagate down into the functions making the requests and then explicitly set them in request headers. This led to our code getting ugly, my development team forgetting to do it on occasion and our centralised logs in ELK not being so helpful. Well I was wrong.

Thankfully Node 8 has added a nice library called async_hooks which allows you grab the current ‘async id’:

const asyncHooks = require('async_hooks');

My rather clever colleague Pierre Meunier has written a nice NPM module which instruments the underling http library and passes headers along, see here

All you have to do when starting up your service is add this line:


and you can override the headers you wish to handle like so:

headersToPropagate: [

Hope this really helps your logging and tracing of errors in your microservices stack