Can I require elastic-apm-node twice?

Hi guys,
In my git repo I have an internal logger module that is stored as a git submodule, let's call it logger-module. It looks like this


  • submodules
    • logger-module

The logger-module/index.js requires and starts elastic-apm-node at the very top.
The main app index.js requires logger-module at the very top also.
It all works fine, APM gets all the data captured by the main app.

I also have another app, that also uses logger-module along with other submodules that use it too. It looks like this:


  • submodules
    • logger-module
    • another-submodule
      • submodules
        • logger-module

As you can see logger-module (with elastic-apm-node inside) will be required twice. Will it break my another-application? Will I get two instances of elastic-apm-node?

The elastic-apm-node package acts as a "singleton" and will use a shared state inside the running process. So you can require it as many times as you like, as long as you only start it once.

If you try to start it more than once in the same process, it will throw an error.

However, since all code in the outer scope of a module only runs the first time it's required, you can require your logger-module module multiple times as long as you make sure that you require and start the agent in that outer scope. This way the agent will start only the first time the logger-module is required.

If you find yourself in a situation where you want to conditionally start the agent based on if it's already started, you can use the agent.isStarted() function.

Hi Thomas,
thanks for the answer. Unfortunately in my case the agent is started twice and two agents are running. No error is thrown when the 2nd instance is being started.
It's because each submodule has its own node_modules directory, and therefore I have agents from:

  • another-app / submodules / logger-module / node_modules / elastic-apm-node
  • another-app / submodules / another-submodule / submodules / logger-module / node_modules / elastic-apm-node

I guess from the node point of view these are two different packages.

Anyway I'm setting process.env.ELASTIC_APM_ACTIVE to false after staring 1st instance, to prevent the 2nd one from being started also.

Ah ok, having the agent installed in two different locations on the filesystem for the same app is unfortunately a way to side-step the "singleton" behaviour and isn't officially supported. It might work without any errors in your case, but it's not something I would recommend as it - amongst other things - adds extra overhead to the application. Your approach of using ELASTIC_APM_ACTIVE to control this behaviour sounds like a good hack and should work as expected. But it should probably be something we looked into handling better.

1 Like

Ok, got it.

BTW I love the tool! :clap:

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.