Skip to main content

What's Async Local Storage in Node.js v14?

Node.js 14 is out now, and with that release, it brings in Async Local Storage support. Now you might thing, "Meh, okay. Local storage has been around for awhile," but this time, it's different.

For starters, this is the Node runtime we're talking about and not the browser. Thus, having a "localStorage" browser-like concept doesn't really make sense for Node. And the fact is, it is not the localStorage you're probably thinking of either. So what is it then?

Introducing Async Local Storage – Storage for asynchronous tasks

Consider a web server like Apache running PHP for hosting a website. When PHP receives a request from a client, your web server makes sure to spin off a new thread. It lets that thread manage all the resources, local variables, function call stack, and so on for that particular request. Simple and easy. But a problem arises with JavaScript.

JavaScript is single threaded – that means you cannot have multiple threads of JS running together under a same parent process. But don't let that fool you – JS is as fast (even faster) as mature solutions like a Java backend in handling web server requests.

How does that happen? Well, that's something for another article. But the important thing here is that Node is single threaded, so you do not have the benefits of thread local storage. Thread local storage is nothing but variables and functions local to a particular thread - in our case, for handling a particular user on the webpage.

Why is single thread a problem?

Single thread is a problem in this case as Node keeps executing synchronous code in one go as long as it doesn't exhaust all synchronous operations in the event loop. Then it'll keep a check on events and callbacks and execute that code whenever necessary.

In Node, a simple HTTP request is nothing but an event fired by the http library to the node to handle the request – hence it is asynchronous.

Now let's say you want to associate some data with this asynchronous operation. How would you do that?

Well, you can create some sort of "global" variable and assign your special data to it. Then, when another request comes from the same user, you can use the global variable to read whatever you had stored earlier.

But it would fail spectacularly when you have more than one request on hand as Node would not execute asynchronous code serially (of course, that's the definition of asynchronous!).

Let's consider this dummy code (assume Node runtime):

server.listen(1337).on('request', (req) => {
  // some synchronous operation (save state)
  // some asynchronous operation
  // some asynchronous operation
})

Consider this sequence of events:

  1. User 1 hits the server on port 1337
  2. Node starts running the synchronous operation code
  3. While node was running that synchronous code, another User 2 hits the server.
  4. Node would keep on executing the synchronous code, meanwhile the request to process the second HTTP request is waiting in the task queue.
  5. When Node finishes the synchronous operation and comes to the asynchronous operation, it throws it off in the task queue and then starts processing the first task sitting in the task queue – the second HTTP request.
  6. This time it's running that synchronous piece of code, but on the behalf of User 2's request. When that synchronous code for User 2 is done, it resumes the asynchronous execution of User 1, and so on.

Now what if you want to persist specific data with that specific user whenever the asynchronous code specific to them is being called? Here's when you use AsyncStorage – storage for asynchronous flows in Node.

Consider this example straight from the official docs:

const http = require('http');
const { AsyncLocalStorage } = require('async_hooks');

const asyncLocalStorage = new AsyncLocalStorage();

function logWithId(msg) {
  const id = asyncLocalStorage.getStore();
  console.log(`${id !== undefined ? id : '-'}:`, msg);
}

let idSeq = 0;
http.createServer((req, res) => {
  asyncLocalStorage.run(idSeq++, () => {
    logWithId('start');
    // Imagine any chain of async operations here
    setImmediate(() => {
      logWithId('finish');
      res.end();
    });
  });
}).listen(8080);

http.get('http://localhost:8080');
http.get('http://localhost:8080');
// Prints:
//   0: start
//   1: start
//   0: finish
//   1: finish

This example is showing nothing but the "stickyness" of the idSeq with the respective request. You can imagine how express populates the req.sessionobject with the correct user every time. In a similar fashion, this is a low level API using a lower level construct in Node called async_hooks which is still experimental, but is pretty cool to know!

Performance

Before you try to roll this out in production, beware – this is not something I would really recommend anybody do if not absolutely needed. This is because it comes with a non-negligible performance hit on your application. This is primarily because the underlying API of async_hooks is still a WIP, but the situation should improve gradually.

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...