What is thread-local storage (TLS):

It is functionality that allows you to attach and retrieve data to the current processing thread from anywhere at anytime. It works by allocating specific memory to that thread.

In Python it looks like this: threading.local(). Using this you can set/get data that persists for that thread alone.

NodeJS and CPS:

Node and (more explicitly the Express framework) make use of a functional style called CPS (continuation passing-style) to move variables around. Express utilises middleware signatures to pass certain objects all the way through the calling stack. I won’t go into more detail on that here (a great thorough explanation exists from Dr Axel R here) but it’s a great approach to take control of what is going to be called next. Also it is typically easy for an engine to optimise as it makes heavy usage of tail calls.

With Express the typical way to move data throughout a runtime process is to assign to the response locals object e.g. response.locals.myParam = ‘value’;

The problem with this is that you have direct access to the response object. What if you want to set/get some data from a module not connected to middleware or the response object? You have to pass variables around and it can become very troublesome and painful.

There is a great library called Continuation-Local Storage which solves this issue for NodeJS, but today we are going to try and solve it on our own to get an understanding what is going on. First there are a couple of things to be (or get) familiar with.

Event loop:

We all know how great this is. The event loop delegates async actions and processes responses from its queue. All on a single-thread and at a rapid pace.

AsyncListener API:

API available from Node 0.11, allows you to trigger events based on actions in the event loop. Including creation of an event in the queue, the start of processing an event in the queue, and the finish of processing of that event.