Discord Bot Memory Leak in Long-Running Process: Fix
🔍 WiseChecker

Discord Bot Memory Leak in Long-Running Process: Fix

If you run a Discord bot for hours or days, you may notice its memory usage climbing steadily. This is a memory leak, where the bot fails to release memory it no longer needs. Over time, it can slow down the bot, cause crashes, or make it unresponsive. This article explains the main causes of memory leaks in long-running Discord bots and provides concrete fixes to keep memory usage stable.

Key Takeaways: Fixing a Discord Bot Memory Leak

  • Disable the default intents for guild members and presences: Reduces memory usage by 30-50% in long-running bots.
  • Add client.users.cache.clear() in a periodic cleanup function: Prevents the user cache from growing without limit.
  • Use setInterval to clear message and channel caches every 10 minutes: Keeps memory footprint under 150 MB even after 24 hours.

Why Discord Bots Leak Memory in Long-Running Processes

Discord.js and similar libraries maintain in-memory caches for users, messages, channels, and guilds. In a long-running bot, these caches grow as the bot processes events. The default cache size is unlimited. If your bot listens to many servers or channels, the cache can balloon to hundreds of MBs within hours.

Another cause is event listeners that are not properly removed. When your bot subscribes to events like messageCreate or guildMemberAdd, the library stores references to the callback functions. If you attach new listeners without removing old ones, the references accumulate and prevent garbage collection.

A third cause is storing large objects in global variables or collections. For example, collecting every message in a channel into an array without clearing it will cause memory to grow linearly with time.

How Caching Works in Discord.js

Discord.js v13 and v14 use a Collection class (which extends Map) for caching. When a user sends a message, the library adds the user object to client.users.cache if it is not already there. The same happens for messages, channels, and guilds. The cache never removes entries unless you manually call .delete() or .clear().

The Role of Intents

Intents control which events your bot receives. If you enable the GuildMembers intent, Discord sends member list updates for every guild. For a bot in 100 servers with 500 members each, that means 50,000 member objects in cache. Disabling unused intents reduces the data your bot must store.

Steps to Fix a Discord Bot Memory Leak

  1. Disable unnecessary intents
    Open your bot code and locate the Client constructor. Remove GatewayIntentBits.GuildMembers and GatewayIntentBits.GuildPresences unless your bot specifically needs them. These two intents cause the largest memory consumption. After disabling, restart the bot and monitor memory usage.
  2. Limit the message cache size
    In the Client constructor, set sweepers: { messages: { interval: 600, lifetime: 1800 } } (Discord.js v14). This removes messages older than 30 minutes from the cache every 10 minutes. For v13, use messageCacheLifetime: 1800 and messageSweepInterval: 600 in the options object.
  3. Clear the user cache periodically
    Add a function that runs every 15 minutes using setInterval. Inside it, call client.users.cache.clear(). This removes all cached user objects. Do the same for client.channels.cache and client.guilds.cache if your bot does not need to keep them in memory.
  4. Remove unused event listeners
    If your bot dynamically adds event listeners, store the reference and call client.removeListener(event, callback) when the listener is no longer needed. For example, if you listen to messageCreate in a specific channel, remove the listener when the bot leaves that channel.
  5. Use WeakRef or FinalizationRegistry for large data
    If your bot stores large objects like voice connection data or custom user data, use WeakRef to allow garbage collection when the object is no longer referenced. Avoid storing data in global arrays or maps unless you clear them regularly.
  6. Monitor memory with process.memoryUsage()
    Add a log every 10 minutes that prints process.memoryUsage().heapUsed. If the value increases by more than 5% per hour, a leak is present. Use this to verify your fixes.

If the Bot Still Has a Memory Leak After the Main Fix

Bot Crashes with Out of Memory Error

If your bot crashes with a JavaScript heap out of memory error, increase the Node.js memory limit. Run the bot with node --max-old-space-size=512 bot.js (512 MB). This is a temporary workaround. The real fix is to reduce cache size as described above.

Memory Grows Even After Clearing Caches

Check for circular references. If your code creates objects that reference each other, they cannot be garbage collected. Use the --inspect flag with Chrome DevTools to take heap snapshots. Look for objects with a large retained size that are not supposed to be there.

Bot Slows Down Over Time

High memory usage forces the garbage collector to run more frequently, which blocks the event loop. If your bot responds slowly after hours of uptime, the memory leak is likely severe. Apply all fix steps above and restart the bot.

Discord Bot Memory Management: Manual Cache vs Sweeper vs External Database

Item Manual Cache Clear Built-in Sweeper External Database (Redis)
Implementation Add setInterval with .clear() calls Set sweepers in Client options Store data in Redis, query on demand
Memory reduction Reduces heap by 50-70% Reduces heap by 30-50% Bot memory stays under 100 MB
Performance impact Brief pause during clear No noticeable pause Network latency on each query
Data persistence Lost on clear Lost after sweep interval Persistent across restarts

Now you can identify and fix memory leaks in your Discord bot. Start by disabling unused intents and setting up a sweeper. If the problem persists, add a periodic cache clear and monitor heap usage with process.memoryUsage(). For bots that must stay online for weeks, consider moving persistent data to an external database like Redis. This reduces the bot’s memory footprint to near zero and prevents crashes.