1

I am using AsyncLocalStorage in a project, and I think we have a memory leak related to it. So, my understanding from the documentation is I can start a new context using run or enterWith (I don't know the difference between them). It is not clear to me how I can update the values. Currently, I am doing this:

const values = als.getStore();
const newValues = { // merge metadata
    ...values,
    ...additionalValues
};
als.enterWith(newValues);
return newMetadata;

Should I disable the AsyncLocalStorage before updating the value? I am using Node 18.

cmaluenda
  • 2,099
  • 1
  • 14
  • 15

1 Answers1

0

You don't need to disable AsyncLocalStorage before updating the values. Rather, you should ensure that you are using als.enterWith() correctly to establish a new context with the updated values.
It is absolutely essential to exit the context properly after you've finished using it within a specific asynchronous operation. If you're entering a new context using als.enterWith(newValues), make sure you also use als.exit() when you're done with that operation to prevent memory leaks. I hope this will explain,

// Assuming this function is returning the new context with values
function createNewContextWithValues() {
    const values = als.getStore()
    const newValues = {
        ...values,
        ...additionalValues
    }
    return newValues
}

// Using the new context 
async function someAsyncFunction() {
    const newContext = createNewContextWithValues()
    
    // Enter the new context with values
    als.enterWith(newContext)

    try {
        // Your asynchronous operations that use the new context
    } finally {
        als.exit() // Exit the context when done, even if an error occurs
    }
}

// Calling the function
someAsyncFunction()

If you are using AsyncLocalStorage in a long-running application (like a server), periodically check for any unnecessary or expired contexts and values and clean them up.

Nazrul Chowdhury
  • 1,483
  • 1
  • 5
  • 11