Skip to content

Memory leak-like behavior caused by node-addon-api not doing GC synchronously #2436

Open

Description

@H3r3zy

In the node-canvas@3.0.0-rc2 there is a big memory leak on the loadImage function.
The image loaded is never released.

reverting to 2.11.2 fixed my issue

Activity

  1. SystemR commented on Apr 10, 2025

    @SystemR

    I can confirm it still happens. I believe it only happens when you pass a path to loadImage and the file descriptor not being closed.

    Image::GetSource(const Napi::CallbackInfo& info){

    Passing in buffer from readFileSync also causes memory leak somehow.

    My workaround is to use readFile and pass in the buffer:

    readFile(file, async (err, data) => {
          let img = await loadImage(data);
  2. chearon commented on Apr 10, 2025

    @chearon
    Collaborator

    Can you provide a small repro? Something that loops and calls global.gc() and logs process.memoryUsage() to show it increasing. I can't find anything wrong with the code after a quick look.

  3. SystemR commented on Apr 10, 2025

    @SystemR

    This one will have increased memory usage over time (seeing htop):

    import { loadImage } from "canvas";
    import { readdirSync } from "fs";
    
    const FOLDER = "./img";
    
    const processFiles = readdirSync(FOLDER, { recursive: true });
    
    await main();
    
    async function main() {
      for (const p of processFiles) {
        if (p.indexOf(".png") >= 0) {
          let img = await loadImage(FOLDER + "/" + p);
          console.log(img.width, img.height);
        }
      }
    }

    This one doesn't:

    import { loadImage } from "canvas";
    import { readdirSync, readFile } from "fs";
    
    const FOLDER = "./img";
    
    const processFiles = readdirSync(FOLDER, { recursive: true });
    
    await main();
    
    async function main() {
      for (const p of processFiles) {
        if (p.indexOf(".png") >= 0) {
          const buff = await getBuff(FOLDER + "/" + p);
          const img = await loadImage(buff);
          console.log(img.width, img.height);
        }
      }
    }
    
    function getBuff(path) {
      return new Promise((res, rej) => {
        readFile(path, (err, data) => {
          if (err) {
            return rej(err);
          }
          return res(data);
        });
      });
    }

    With readFileSync it also has increased memory usage over time:

    import { loadImage } from "canvas";
    import { readdirSync, readFileSync } from "fs";
    
    const FOLDER = "./img";
    
    const processFiles = readdirSync(FOLDER, { recursive: true });
    
    await main();
    
    async function main() {
      for (const p of processFiles) {
        if (p.indexOf(".png") >= 0) {
          const buff = readFileSync(FOLDER + "/" + p);
          const img = await loadImage(buff);
          console.log(img.width, img.height);
        }
      }
    }

    Folder has 7000+ photos. I did the expose gc as well and it didn't make a difference.

  4. chearon commented on Apr 11, 2025

    @chearon
    Collaborator

    Thanks! I've spent a while on it but I'm not sure if I'm able to reproduce a leak or not. All code paths look correct. The only thing I can find is that we might not be giving accurate memory notifications to the JS engine, but that would not be new in 3.0.

    It does seem to go up quickly with PNG, and not JPG, but eventually it levels out. That's if I add a small delay to allow GC. Can you try adding a delay as well and see if memory reduces?

    Here's my latest results

    examples/leak.js

    const {loadImage} = require("..");
    const {readFileSync, readdirSync} = require("fs");
    
    const FOLDER = "./img";
    
    const processFiles = readdirSync(FOLDER, {recursive: true});
    
    let rss = 0;
    
    (async function main() {
      for (const p of processFiles.concat(processFiles)) {
        if (p.endsWith(".png")) {
          let img = await loadImage(FOLDER + "/" + p);
          await new Promise(resolve => setTimeout(resolve, 1e3));
          const nrss = process.memoryUsage().rss;
          console.log(Math.round((nrss - rss) / 1024) + 'KiB');
          rss = nrss;
        }
      }
    })();

    Output:

    87536KiB
    34764KiB
    39412KiB
    -9192KiB
    44284KiB
    -10188KiB
    10244KiB
    9348KiB
    -10200KiB
    16KiB
    34344KiB
    -10212KiB
    10232KiB
    10284KiB
    -10208KiB
    10236KiB
    10236KiB
    -10216KiB
    10236KiB
    -4KiB
    -10216KiB
    10236KiB
    348KiB
    -10224KiB
    10232KiB
    -4KiB
    -10216KiB
    10236KiB
    72KiB
    -10216KiB
    10232KiB
    4KiB
    -10216KiB
    10236KiB
    
  5. SystemR commented on Apr 18, 2025

    @SystemR

    I just got around to this. Adding the setTimeout() delay works but makes it slower than using readFile().

    Using the promise without setTimeout() in the code above also increases memory usage over time.

    I think it's just node. Node doesn't seem release the memory in between the loop when using readFileSync() or native api. It also doesn't seem to release in between the promise microtask. Manually doing global.gc() inside the loop doesn't help either. Maybe it just doesn't have enough time to release.

    I think node just looks for time when you're waiting for async macrotask to release the memory and maybe in the case of readFile() there's another thread that runs the gc.

  6. chearon commented on Apr 21, 2025

    @chearon
    Collaborator

    Node only GCing in between macro tasks is a good guess. Thanks for looking. I'll double check that our external memory tracking is accurate and then close this.

  7. H3r3zy commented on May 21, 2025

    @H3r3zy
    ContributorAuthor

    I didn't have the issue in 2.X (or minimal leak ?) but when I tried the 3.X my memory consumption had skyrocket

  8. connorhsm commented on Aug 21, 2025

    @connorhsm

    I am also experiencing a significant memory leak when moving from canvas ^2.11 to ^3.0. I do not make use of the loadImage function originally mentioned. Tracking here.

  9. chearon commented on Aug 21, 2025

    @chearon
    Collaborator

    It does seem like there is something to fix. My other idea (vs blaming node) is that there is a handle to memory that we aren't releasing until after the macrotask is done. I'll try to use Valgrind or similar when I get some time.

  10. wug-ge commented on Jan 20, 2026

    @wug-ge

    I was also experiencing memory leaks causing nodes to become OOM.
    Removing loadImage solved it, would be cool if someone could have a look at it.
    Using 3.2

  11. kayahr commented on Feb 3, 2026

    @kayahr
    Contributor

    Ran into the same issue and tried the workaround with the macro-sleep. But this just converted the memory leak into a crash. Sometimes it just segfaults without output, sometimes it crashes with this output:

    FATAL ERROR: Error::New napi_get_last_error_info
    ----- Native stack trace -----
    
     1: 0x72dd82 node::OnFatalError(char const*, char const*) [node]
     2: 0x84ca45  [node]
     3: 0x7f52d027c256  [/tmp/node_modules/canvas/build/Release/canvas.node]
     4: 0x7f52d027c559 Napi::Error::New(napi_env__*) [/tmp/node_modules/canvas/build/Release/canvas.node]
     5: 0x7f52d02e26bf clearMimeData(void*) [/tmp/node_modules/canvas/build/Release/canvas.node]
     6: 0x7f52d0119ebe  [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
     7: 0x7f52d00bdcd7  [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
     8: 0x7f52d011b26d  [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
     9: 0x7f52d011b3b5 cairo_surface_destroy [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
    10: 0x7f52d0105b89  [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
    11: 0x7f52d0119f62  [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
    12: 0x7f52d011b3d8 cairo_surface_destroy [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
    13: 0x7f52d00e9da5  [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
    14: 0x7f52d011c852 cairo_surface_show_page [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
    15: 0x7f52d00d68d0  [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
    16: 0x7f52d0128685 cairo_show_page [/tmp/node_modules/canvas/build/Release/libcairo.so.2]
    17: 0x7f52d02d0f3f Context2d::AddPage(Napi::CallbackInfo const&) [/tmp/node_modules/canvas/build/Release/canvas.node]
    18: 0x7f52d02d9024 napi_value__* Napi::details::TemplatedInstanceVoidCallback<Context2d, &Context2d::AddPage>(napi_env__*, napi_callback_info__*) [/tmp/node_modules/canvas/build/Release/canvas.node]
    19: 0x81aa01  [node]
    20: 0x7f52b2d8f08d 
    
    ----- JavaScript stack trace -----
    
    1: file:///tmp/lib/sandbox/test.js:21:13
    

    My test script is this:

    import { createWriteStream } from "node:fs";
    
    import { createCanvas, Image } from "canvas";
    
    async function sleep(): Promise<void> {
        return new Promise(resolve => setTimeout(resolve));
    }
    
    async function loadImage(src: string): Promise<Image> {
        return new Promise((resolve, reject) => {
            const image = new Image();
            image.dataMode = Image.MODE_MIME | Image.MODE_IMAGE;
            image.onload = () => resolve(image);
            image.onerror = reject;
            image.src = src;
        });
    }
    
    const pageWidth = 842;
    const pageHeight = 595;
    const canvas = createCanvas(pageWidth, pageHeight, "pdf");
    const ctx = canvas.getContext("2d");
    
    for (let page = 0; page < 10; page++) {
        if (page > 0) {
            ctx.addPage();
        }
        console.log("Rendering page", page);
    
        for (let i = 0; i < 15; i++) {
            const image = await loadImage("/tmp/test.jpeg");
            ctx.save();
            ctx.translate(0, 0);
            ctx.scale(pageWidth / image.width, pageHeight / image.height);
            ctx.drawImage(image, 0, 0);
            ctx.restore();
        }
    
        await sleep();
    }
    
    await new Promise<void>((resolve, reject) => {
        const outStream = createWriteStream("/tmp/test.pdf");
        outStream.on("error", reject);
        outStream.on("finish", () => {
            resolve();
        });
        const pdfStream = canvas.createPDFStream();
        pdfStream.on("end", () => {
            outStream.end();
        });
        pdfStream.on("error", (e: unknown) => {
            reject(e);
        });
        pdfStream.pipe(outStream);
    });

    The used test.jpeg is a 4032x3024 photo.

    This script generates 10 PDF pages with 15 embedded photos per page (in this simplified test always the same photo). After each page a sleep is performed to give node-canvas time for garbage collection. Without this sleep the program runs into a memory leak. With this sleep it crashes at some random page (sometimes it works for all pages, then just run it again, eventually it will crash).

    The image data mode in this case seems to be important. When not embedding the images, then node-canvas does not crash. With node-canvas v2 it doesn't crash with embedding enabled and even without the sleep it works fine without memory leak.

    When moving the sleep inside the inner for loop then it works reliably but this isn't practical because the rendering of a page in my real application is done in a synchronous process and the implementation of this rendering is out of my scope. I can only sleep AFTER rendering a single page.

    Environment:

    Node.js 24.13.0
    Canvas 3.2.1 and 2.11.2
    Debian Linux 13 with 64 GB RAM

  12. kayahr commented on Feb 4, 2026

    @kayahr
    Contributor

    I think my problem with embedding images in PDF is a separate problem to the memory leak described here. So I extracted it with additional data into a new issue #2550

  13. iurisilvio commented on Apr 6, 2026

    @iurisilvio
    Contributor

    I'm being hugely affected by this issue, long running firebase function never release memory after I upgraded to canvas 3. 😢

    I have some investigation and a potential fix in #2562! 🎉

  14. changed the title [-]Memory leak in 3.0.0-rc2[/-] [+]Memory leak-like behavior caused by node-addon-api not doing GC synchronously[/+] on Jun 30, 2026
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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions