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.
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,
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.