Node.js · Memory

JavaScript heap out of memory

Your bot used all the memory Node would give it and was stopped. More memory sometimes helps; finding what is growing helps every time.

← All errors

What you are seeing

Node.js

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory

Node.js

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Caches first

In a Discord bot, the usual culprit is not your code but the library's cache. discord.js keeps members, messages, presences and more in memory by default, and on large servers that grows for as long as the bot runs. The memory graph climbs steadily for hours or days, then the bot falls over.

Limiting the caches you do not use, and sweeping old entries, keeps memory flat. So does requesting fewer intents: a bot is only sent, and only caches, what its intents ask for.

discord.js

const { Client, GatewayIntentBits, Options } = require('discord.js');

const client = new Client({
    intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
    makeCache: Options.cacheWithLimits({
        ...Options.DefaultMakeCacheSettings,
        MessageManager: 50,
        PresenceManager: 0,
    }),
    sweepers: {
        ...Options.DefaultSweeperSettings,
        messages: { interval: 3600, lifetime: 1800 },
    },
});

Then leaks

If memory climbs even with caches limited, something in your code holds on to what it no longer needs. The common ones: an array or Map that entries are added to and never removed from, such as a cooldown list keyed by user; an event listener registered inside a command, so every use adds another (Node warns about this with MaxListenersExceededWarning); and a setInterval started on every reconnect.

Log process.memoryUsage().heapUsed every few minutes. A number that levels off is a cache; one that only ever rises is a leak.

How much memory a bot needs

A discord.js bot in a few hundred servers sits comfortably in 256 MB, which is what our free servers have. If your bot has genuinely outgrown it after trimming caches, the paid plan gives it more room on the same server without starting over.

One Node setting is worth knowing. If the process is being killed by the system before Node reports anything, setting --max-old-space-size a little below the server's memory, such as --max-old-space-size=200, makes Node clean up harder as it nears the limit and fail with the readable error above instead of vanishing.

FAQ

Questions

Should I just raise --max-old-space-size?

Only up to the memory the server actually has. Setting it higher than that does not create memory; the system stops the process instead, with no error at all.

The bot restarts itself every few days. Is that this?

Very likely, if the console shows this error before each restart. Our servers restart a crashed bot automatically, which hides the problem rather than fixing it; the memory will keep climbing to the same point.