Discord mandates sharding once your bot reaches 2,500 guilds. Without it, Discord's API will refuse to let your bot connect. Sharding splits your bot's guild management across multiple WebSocket connections - understanding it before you need it prevents an emergency migration at 2,499 guilds.
What Sharding Does
Discord's gateway has a limit on guilds per connection. Sharding divides your guilds across multiple "shards" - each shard is an independent WebSocket connection that handles a subset of your guilds.
A bot with 5,000 guilds on 2 shards: Shard 0 handles guilds 0 - 2,499, Shard 1 handles 2,500 - 4,999.
Events from guilds arrive to their assigned shard. Commands running in a guild arrive on that guild's shard.
discord.js Sharding
discord.js provides a built-in ShardingManager:
// shard_manager.js (entry point instead of index.js)
const { ShardingManager } = require('discord.js');
const manager = new ShardingManager('./src/index.js', {
token: process.env.DISCORD_TOKEN,
totalShards: 'auto', // Discord tells you how many shards you need
mode: 'process' // Each shard is a separate process (most stable)
});
manager.on('shardCreate', shard => {
console.log(`Launched shard ${shard.id}`);
});
manager.spawn();
Your existing index.js works without modification - the ShardingManager passes the shard ID and total shards automatically.
Cross-Shard Communication
The tricky part: guilds on different shards can't share data directly. Use ShardingManager's broadcastEval:
// Run on ALL shards and collect results:
const results = await client.shard.broadcastEval(c => c.guilds.cache.size);
const totalGuilds = results.reduce((acc, val) => acc + val, 0);
// Run on specific shard:
await client.shard.fetchClientValues('guilds.cache.size');
Preparing Your Code for Sharding Before You Need It
Write code that doesn't assume all guilds are accessible from a single instance:
- Don't store guild objects in global variables
- Don't iterate all guilds for cross-guild features without shard broadcasting
- Use a database for shared state rather than in-memory collections
Doing this refactor before you hit 2,500 guilds is far easier than doing it in production emergency mode.