If your Discord bot is connected to a large number of servers and you notice it becoming slow, unresponsive, or failing to connect, the problem might be that it has exceeded Discord’s gateway connection limits. Discord enforces a hard limit on how many servers a single bot connection can handle efficiently. This article explains what sharding is, why your bot needs it when it reaches around 2,500 servers, and provides a clear step-by-step guide to implement sharding using discord.js. You will learn how to configure your bot to split its workload across multiple connections, known as shards, and how to test that the setup works correctly.
Key Takeaways: Discord Bot Sharding Setup
- Discord Gateway Intents > Guild Members Intent: Sharding is required when your bot is in over 2,500 servers to stay within Discord’s rate limits.
- discord.js ClientOptions > shards: Set the shards property to ‘auto’ to let discord.js calculate the correct number of shards automatically.
- Client.shard.broadcastEval: Use this method to send commands or fetch data across all shards from a single location.
Why Discord Bot Sharding Is Necessary
Discord limits the number of servers a single bot connection can serve. This limit is approximately 2,500 servers per gateway connection. Once your bot joins more than 2,500 servers, Discord’s API will begin to reject connections or throttle your bot’s requests. Sharding solves this by splitting your bot into multiple separate processes, each handling a subset of servers. Each shard maintains its own WebSocket connection to Discord, staying under the server limit per connection. Sharding also improves performance because each shard only processes events for its assigned servers, reducing memory and CPU usage per process. Without sharding, a bot in 5,000 servers would simply stop working after crossing the 2,500 threshold.
How Discord’s Gateway Limit Works
Discord’s Gateway API assigns each bot a unique session ID. When your bot connects, Discord checks how many guilds the bot is in. If the count exceeds 2,500, Discord sends a GUILD_CREATE event for each guild, but the connection is unstable and may be terminated. Sharding tells Discord that your bot is using multiple connections, and Discord then distributes the guilds across those connections evenly. The API also provides a shard property in the identify payload that tells Discord which shard this connection represents.
When You Need to Start Sharding
You should implement sharding before your bot reaches 2,500 servers. Waiting until after the limit is hit can cause downtime and connection errors. Many bot developers enable sharding as soon as the bot reaches 1,500 servers to prepare for growth. Discord’s documentation recommends sharding for any bot in more than 2,500 servers. If your bot uses gateway intents that require privileged access, such as the Guild Members intent, sharding becomes mandatory at 2,500 servers because those intents increase the load on a single connection.
Steps to Set Up Sharding in discord.js
These instructions assume you are using discord.js version 13 or 14. The sharding process involves creating a separate shard manager file that launches your main bot file multiple times.
- Create a Shard Manager File
Create a new file namedindex.jsin your bot project root. This file will be the entry point for your bot, replacing your original main file. Write the following code:const { ShardingManager } = require('discord.js');
const manager = new ShardingManager('./bot.js', {
token: 'YOUR_BOT_TOKEN',
totalShards: 'auto'
});
manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`));
manager.spawn();
ReplaceYOUR_BOT_TOKENwith your actual bot token. ThetotalShards: 'auto'setting tells discord.js to calculate the correct number of shards based on your bot’s guild count. - Move Your Bot Code to a Separate File
Rename your original bot file tobot.js. This file should contain your client setup, event listeners, and command handling. The shard manager will launch multiple instances of this file. Ensure that yourbot.jsfile does not callclient.login()directly because the shard manager handles login automatically. - Update Your Client Options
Inbot.js, modify yourClientconstructor to include theshardsproperty. This property tells each instance which shard it is. For discord.js v13 and v14, set it toshards: 'auto'as well. Example:const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
shards: 'auto'
});
If you use a custom shard count, setshardsto the specific shard ID and total count, but ‘auto’ is simpler for most bots. - Handle Cross-Shard Data Access
When your bot is sharded, each shard has its own cache of guilds, channels, and users. To access data from another shard, useclient.shard.broadcastEval(). For example, to get the total guild count across all shards:const guildCount = await client.shard.broadcastEval(c => c.guilds.cache.size);
const total = guildCount.reduce((acc, count) => acc + count, 0);
This method sends a function to every shard and collects the results. - Test Your Sharding Setup
Run yourindex.jsfile. You should see log messages for each shard that launches, such as “Launched shard 0” and “Launched shard 1”. If you have fewer than 2,500 servers, discord.js will still create at least one shard. Verify that your bot responds to commands and that events likeguildCreatework correctly. Useclient.shard.countto see how many shards are active.
Common Issues After Enabling Sharding
Commands Stop Working on Some Servers
If your slash commands or message commands only work on some servers, the problem is likely that your command registration code runs only on one shard. Register global commands using client.application.commands.set() inside a ready event, but ensure it runs only once. Use client.shard.broadcastEval to check if the current shard is the first shard (shard 0) and only register commands there. Alternatively, register commands outside of the shard manager by using a separate script that uses the REST API directly.
Memory Usage Increases Unexpectedly
Each shard runs as a separate Node.js process, so memory usage multiplies by the number of shards. If your bot had 100 MB of memory before sharding, with 5 shards it will use approximately 500 MB. To reduce memory, minimize cached data by disabling unnecessary intents and using partials only when needed. Consider using external caching like Redis for cross-shard data that does not need to be in memory on every shard.
Shard Reconnection Loops
If a shard keeps disconnecting and reconnecting, your bot token may be invalid, or the shard count is miscalculated. Check that your token is correct and that you are not exceeding Discord’s rate limits. If you set totalShards manually to a number that is too low for your guild count, Discord may reject the connection. Always use 'auto' unless you have a specific reason to set a custom number.
Discord Bot Sharding Comparison: Manual vs Auto Shard Count
| Item | Manual Shard Count | Auto Shard Count |
|---|---|---|
| Configuration | You set totalShards to a fixed number like 5 |
discord.js calculates the shard count from your guild count |
| Scalability | Requires manual updates when your bot grows | Automatically adjusts as your bot joins more servers |
| Risk of Errors | High if you guess the wrong number | Low because the library queries Discord’s API for the recommended count |
| Best For | Bots with a stable, known guild count | Bots that are actively growing or have unpredictable guild counts |
Sharding is a requirement for any Discord bot that serves more than 2,500 servers. By following the steps above, you can set up sharding with discord.js using the auto shard count option, which minimizes configuration errors and keeps your bot running smoothly as it grows. After sharding is active, use client.shard.broadcastEval to manage cross-shard data and ensure your commands are registered globally. For advanced performance, consider using a process manager like PM2 to restart individual shards without affecting the entire bot.