Understanding Async Context

Rate this content
Bookmark

The AsyncLocalStorage API in Node.js is a powerful tool that has since been adopted across multiple runtimes. There is even an effort underway to standardize a variation of the API within JavaScript itself. But what is it? And more importantly, how does it work?

This talk has been presented at Node Congress 2024, check out the latest edition of this Tech Conference.

FAQ

Async local storage is an API in Node.js that allows you to associate state and propagate it through callbacks and promise chains without having to manually pass context through every function. It's useful for scenarios where you need to manage context across asynchronous operations.

James Snell is a principal engineer at Cloudflare, a member of the Node.js Technical Steering Committee, and a co-chair and founder of the WinterCG (Web Interoperable Runtimes Community Group). He has been contributing to Node.js since 2015.

Async local storage works by creating a storage frame, which acts like a map to store key-value pairs. When you run a function using async local storage, it sets the value in a new frame and makes it current. This allows you to retrieve the value later without passing it through every function manually.

Using async local storage in Node.js can have performance implications, potentially causing up to a 30% performance hit. This is due to the way Node.js currently implements async hooks, which are expensive to turn on.

Common issues with async local storage include potential memory leaks if references to storage frames are not properly managed. It's important to avoid scenarios where the storage frame captures a reference to itself, which can prevent garbage collection.

Async context is a new TC39 proposal aimed at standardizing async local storage in the JavaScript language. The main differences include async context being a global object and having slightly different methods, such as 'get' instead of 'get store'.

Understanding the internals of async local storage is important for diagnosing issues like memory leaks and performance bottlenecks. It helps developers write more efficient and bug-free code by knowing how the underlying mechanisms work.

In runtimes like Cloudflare Workers, async local storage is implemented using a model where the storage frame is copied every time ALS run is called. This approach is generally more efficient and avoids some of the performance issues seen in Node.js.

Yes, async local storage is starting to be incorporated into various frameworks like Next.js and others, making it more common to find under the covers.

You can pass the async local storage instance down the call stack by declaring it at a top-level scope or by importing it from a module. This way, any code that needs to access it can do so without having to pass it explicitly.

James Snell
James Snell
29 min
04 Apr, 2024

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Async local storage is an API that has been around in Node for quite some time and is gaining popularity in other frameworks and runtimes. It allows for easier logging by eliminating the need to pass values through multiple functions. The storage frame in async local storage acts as a map, storing key-value pairs. Tasks and promise continuations are used to perform the next steps in a promise chain. Async Context is a TC39 proposal that adds async local storage to the JavaScript language.

1. Introduction to async local storage

Short description:

Hello, I'm James Snell, a principal engineer at Cloudflare and a member of the Node Technical Steering Committee. I will be discussing async local storage and how it works, providing insight into this API that has been around in Node for quite some time and is now gaining popularity in frameworks and runtimes like Deno and Workers. Let's delve into the details.

All right, hello Node Congress. I am James Snell. I'm going to be talking to you a little bit about async local storage and how it works. It's an API that's been around in Node for quite some time now, a number of years. And it's starting to be picked up by a number of frameworks, next and a few others, and it's being implemented in a variety of runtimes like Deno and Node and Workers and Bun. So, I kind of want to talk about how it works. Just kind of dig into the covers a little bit so you can kind of get an understanding of what's going on.

For some background on me, I'm James Snell. I'm a principal engineer at Cloudflare. I work on the Workers platform. I've also been on the Node Technical Steering Committee for, oh wow, almost a decade now. I've been contributing to Node since 2015. And I am the co-chair and one of the founders of the WinterCG, that's the Web Interoperable Runtimes Community Group, where we're focused on getting all these different runtimes, Bun and Deno and Workers and all these different things together to talk about standardized APIs across the board. So, that's me. If you've heard of me before, it's probably because some of the things I've contributed to Node over the years, things like the WG URL, web crypto implementation, web streams implementation, that kind of thing. But yeah, let's get into it.

2. Understanding async local storage

Short description:

Let's dive into the details of async local storage and understand how it works under the covers.

All right, so if we look at the async local source documentation on the Node website, this is the very helpful introduction that it gives, talking about, you know, these classes are used to associate state and propagate it through callbacks and promise chains. It doesn't really do a lot to help us understand what this API is doing under the covers. And if you haven't noticed, you know, just Node docs in general don't do a great job of explaining things. So, we're going to dig into the details just a bit more, explain how this works, how it all comes together.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Get rid of your API schemas with tRPC
React Day Berlin 2022React Day Berlin 2022
29 min
Get rid of your API schemas with tRPC
Today's Talk introduces TRPC, a library that eliminates the need for code generation and provides type safety and better collaboration between front-end and back-end. TRPC is demonstrated in a Next JS application integrated with Prisma, allowing for easy implementation and interaction with the database. The library allows for seamless usage in the client, with automatic procedure renaming and the ability to call methods without generating types. TRPC's client-server interaction is based on HTTP requests and allows for easy debugging and tracing. The library also provides runtime type check and validation using Zod.
Step aside resolvers: a new approach to GraphQL execution
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
GraphQL has made a huge impact in the way we build client applications, websites, and mobile apps. Despite the dominance of resolvers, the GraphQL specification does not mandate their use. Introducing Graphast, a new project that compiles GraphQL operations into execution and output plans, providing advanced optimizations. In GraphFast, instead of resolvers, we have plan resolvers that deal with future data. Graphfast plan resolvers are short and efficient, supporting all features of modern GraphQL.
Handling Breaking Changes in GraphQL
GraphQL Galaxy 2022GraphQL Galaxy 2022
22 min
Handling Breaking Changes in GraphQL
Top Content
This Talk discusses handling breaking changes in a GraphQL schema, including the use of the deprecated directive to tag fields that should no longer be used. It also covers the process of deploying GraphQL APIs and mobile apps, highlighting the challenges of mobile app release adoption. The Talk emphasizes the importance of making safe upgrades in mobile apps and provides strategies for detecting and handling breaking changes, such as using TypeScript and GraphQL Inspector. Overall, the Talk emphasizes the need to minimize user impact when introducing breaking changes in GraphQL schemas.
Advanced Patterns for API Management in Large-Scale React Applications
React Advanced Conference 2021React Advanced Conference 2021
20 min
Advanced Patterns for API Management in Large-Scale React Applications
Top Content
This Talk covers advanced patterns for API management in large-scale React applications. It introduces the concept of an API layer to manage API requests in a more organized and maintainable way. The benefits of using an API layer include improved maintainability, scalability, flexibility, and code reusability. The Talk also explores how to handle API states and statuses in React, and provides examples of canceling requests with Axios and React Query. Additionally, it explains how to use the API layer with React Query for simplified API management.
Safely Handling Dynamic Data with TypeScript
Node Congress 2021Node Congress 2021
29 min
Safely Handling Dynamic Data with TypeScript
Top Content
This Talk discusses the safe handling of dynamic data with TypeScript using JSON Schema and TypeBox. Fastify, a web framework, allows developers to validate incoming data using JSON schema, providing type safety and error handling. TypeBox is a powerful library that allows developers to define JSON schemas and derive static types in TypeScript. The combination of JSON schema, TypeBox, and Fastify provides powerful tools for type safety and validation of dynamic data.
APIs are Evolving. Again.
JSNation 2023JSNation 2023
28 min
APIs are Evolving. Again.
Matteo Collina
Luca Maraschi
2 authors
Technology is a spiral, with foundational ideas resurfacing. Java revolutionized enterprise applications. REST and JSON simplified building APIs and websites. Node.js enabled fast and custom development, leading to the microservices revolution. Platformatic aims to fill the gap in building, managing, and scaling microservices painlessly.

Workshops on related topic

Hands-on with AG Grid's React Data Grid
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
WorkshopFree
Sean Landsman
Sean Landsman
Get started with AG Grid React Data Grid with a hands-on tutorial from the core team that will take you through the steps of creating your first grid, including how to configure the grid with simple properties and custom components. AG Grid community edition is completely free to use in commercial applications, so you'll learn a powerful tool that you can immediately add to your projects. You'll also discover how to load data into the grid and different ways to add custom rendering to the grid. By the end of the workshop, you will have created an AG Grid React Data Grid and customized with functional React components.- Getting started and installing AG Grid- Configuring sorting, filtering, pagination- Loading data into the grid- The grid API- Using hooks and functional components with AG Grid- Capabilities of the free community edition of AG Grid- Customizing the grid with React Components
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.
Database Workflows & API Development with Prisma
Node Congress 2022Node Congress 2022
98 min
Database Workflows & API Development with Prisma
WorkshopFree
Nikolas Burk
Nikolas Burk
Prisma is an open-source ORM for Node.js and TypeScript. In this workshop, you’ll learn the fundamental Prisma workflows to model data, perform database migrations and query the database to read and write data. You’ll also learn how Prisma fits into your application stack, building a REST API and a GraphQL API from scratch using SQLite as the database.
Table of contents:
- Setting up Prisma, data modeling & migrations- Exploring Prisma Client to query the database- Building REST API routes with Express- Building a GraphQL API with Apollo Server
Best Practices and Patterns for Managing API Requests and States
React Advanced Conference 2022React Advanced Conference 2022
206 min
Best Practices and Patterns for Managing API Requests and States
Workshop
Thomas Findlay
Thomas Findlay
With the rise of frameworks, such as React, Vue or Angular, the way websites are built changed over the years. Modern applications can be very dynamic and perform multiple API requests to populate a website with fresh content or submit new data to a server. However, this paradigm shift introduced new problems developers need to deal with. When an API request is pending, succeeds, or fails, a user should be presented with meaningful feedback. Other problems can comprise API data caching or syncing the client state with the server. All of these problems require solutions that need to be coded, but these can quickly get out of hand and result in a codebase that is hard to extend and maintain. In this workshop, we will cover how to handle API requests, API states and request cancellation by implementing an API Layer and combining it with React-Query.
Prerequisites: To make the most out of this workshop, you should be familiar with React and Hooks, such as useState, useEffect, etc. If you would like to code along, make sure you have Git, a code editor, Node, and npm installed on your machine.