'Will heroku crash if I run multiple instances of puppeteer?

So I created a simple node.js app to automatically generate and email PDFs using puppeteer. Everything is working perfectly on my local server but once I deploy to heroku the server will timeout if I try to create more than 2 PDFs. So if I only create 2 PDFs on my heroku app it works without an issue, but as soon as I try generate more than that the app times out.

Here is the loop I use to generate each PDF:

for (let x = 1; x <= numTickets; x++) {
console.log(x, " / ", numTickets);
try {
  const browser = await puppeteer.launch({
    headless: true,
    args: ["--no-sandbox", "--disable-setuid-sandbox"],
  });
  const page = await browser.newPage();

  //compile html
  const content = await compile(template, {
    billing,
    id: id + "-" + `${x}`,
    campaign,
  });
  
  options.attachments.push({
    filename: `${billing.first_name}-housedoubleup-${id}-${x}.pdf`,
    path: `./${billing.first_name}-housedoubleup-${id}-${x}.pdf`,
    contentType: "application/pdf",
  });

  await page.setContent(content);
  await page.emulateMediaType("screen");
  await page.pdf({
    path: `${billing.first_name}-housedoubleup-${id}-${x}.pdf`,
    format: "a5",
    printBackground: true,
    landscape: true,
  });

  console.log("done");
} catch (e) {
  console.log("Error -> ", e);
}

if (x === numTickets) {
  sendEmail(options);
}
  }

I'm wondering if the 512MB of RAM on my heroku free tier is maybe limiting the rest of the PDFs being generated.

If anyone has any idea how to help or what could be going wrong I'd really appreciate it :)



Solution 1:[1]

Every single iteration, your loop creates a new browser instance with a new page. Try using,

  1. a single browser instance
  2. a single page instance throughout the loop.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tharinda Prabhath