Home > Software design >  Is there a point where Node.js becomes the bottleneck for a Discord bot?
Is there a point where Node.js becomes the bottleneck for a Discord bot?

Time:06-05

I recently coded a discord bot which can track the user engagement on a server once the user has opted in. I coded it primarily using the Discord.js framework It accepts events emitted from the Discord API when users of a server are active under certain conditions (message send, message reaction, etc.)

How would I be able to tell when, if ever, the single threaded nature of Node.js becomes the bottleneck for this application? Alternatively, how could I test the speed of my application response time to see if my actual code is the inefficient section? While the event-based nature of the application seems like a perfect fit for Node, I want to understand a bit more about the theory behind it and when it'd be a good idea to use another framework.

CodePudding user response:

As you have said, nodejs scales up really well for this kind of application. So, as long as your code runs on a machine with a decent amount of CPU power it will be a long time until you hit a bottleneck. It will run fine with one or two vCPUs, but if your cloud provider throttles the cpu allocated to the virtual machine you're renting, your bot might not keep up with a heavy workload.

If your event handlers use a database, that is just as likely to become a bottleneck as discord.js. Nodejs itself can handle hundreds of concurrent event processors without breaking a sweat (as long as your vendor doesn't throttle your CPU).

How to know you're not keeping up with events? Try this. Each event is processed by a function looking something like this (your code style will certainly be different, this is just the general idea).

    execute(client) {
      try {
        await someOperation(client)
        await someOtherOperation(client)
      } 
      catch (err) {
        /* handle the error */
      }
    }

You can time these event handlers like so

    execute(client) {
      const startTime = Date.now()
      try {
        await someOperation(client)
        await someOtherOperation(client)
      } 
      catch (err) {
        /* handle the error */
      }
      finally {
        const elapsedTime = Date.now() - startTime
        if (elapsedTime > 1000){ /*one second, you may want another value */
          /* report it somehow */
        }
    }

This will keep track of event handlers taking more than a second.

If your bot does get busy enough to require refactoring, I suspect your best approach will be to shard your application; direct some clients to nodejs instance and others to another.

  • Related