Skip to content

Excessive memory usage with AsyncLocalStorage and debugger attached in Node < v18 #47406

Closed as not planned

Description

@timfish

Version

v16.20.0

Platform

macOS

Subsystem

No response

What steps will reproduce the bug?

Using express@4.17.1 although I doubt it matters:

app.js

const express = require("express");
const { AsyncLocalStorage } = require("async_hooks");

const asyncLocalStorage = new AsyncLocalStorage();
const app = express();

setInterval(() => {
  console.log("Memory usage: ", process.memoryUsage().rss / 1024 / 1024);
}, 1000);

app.use((req, res, next) => {
  asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore().set("request", req);
    next();
  });
});

async function random() {
  return new Promise((resolve) => {
    setImmediate(() => {
      resolve(Math.random());
    });
  });
}

app.get("/async", async function (req, res) {
  res.send("Ok" + (await random()));
});

app.listen(3001, function () {
  console.log("Web server listening on port 3001");
});
  • Run node --inspect-brk app.js
  • Attach the Chrome debugger and click Resume
  • Load test the async endpoint (autocannon http://localhost:3001/async)

How often does it reproduce? Is there a required condition?

Every time

What is the expected behavior? Why is that the expected behavior?

No response

What do you see instead?

With the default settings for autocannon, memory peaks when the load test stops at over 1.2GB.

If I do any of the following, the displayed memory usage never goes above 200MB.

  • Use Node v18
  • Don't attach the debugger
  • Avoid async

If you disconnect the debugger and run the load test again, the memory doesn't increase uncontrollably.

Additional information

No response

Activity

  1. bnoordhuis commented on Apr 5, 2023

    @bnoordhuis
    Member

    I'm 85% sure this is the V8 issue where the inspector retains references to any and all JS functions, including closures.

    If I'm right then don't hold your breath waiting for this to get fixed. I don't think there is much that can be done on the Node.js side and the V8 changes can't reasonably be back-ported to v16.x (which is going EOL in a few months anyway.)

  2. added
    inspector
    async_hooks
    on Apr 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    async_hooksinspector

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions