Once your Discord bot joins more than 2,500 servers, Discord forces you to use sharding. But even before that threshold, sharding can improve performance. Here is what you need to know.
What Is Sharding?
Sharding splits your bot across multiple WebSocket connections to Discord. Each shard handles a subset of guilds (servers). Discord requires sharding at 2,500 guilds, but you can start earlier.
When to Shard
The 2,500 server mark is a hard requirement, but consider sharding earlier if:
- Your bot's memory usage exceeds 1.5GB
- Event processing causes noticeable delays
- Voice connections are slow to establish
- Guild cache lookups are becoming slower
Sharding in discord.js
Discord.js has built-in sharding support through the ShardingManager:
// index.js - Shard manager
const { ShardingManager } = require('discord.js');
const manager = new ShardingManager('./bot.js', {
token: process.env.DISCORD_TOKEN,
totalShards: 'auto'
});
manager.on('shardCreate', shard => {
console.log(`Shard ${shard.id} launched`);
});
manager.spawn();
The auto setting lets Discord tell your bot how many shards to use. For manual control, set a specific number.
Sharding in discord.py
Python bots use AutoShardedBot or AutoShardedClient:
import discord
bot = discord.AutoShardedBot(command_prefix='!')
@bot.event
async def on_ready():
print(f'Running {bot.shard_count} shards')
Hosting Requirements for Sharded Bots
Each shard typically needs 100-300MB of RAM plus your bot's base memory. A 10-shard bot might need 2-4GB total.
For hosting, you need a plan with enough RAM to hold all shards plus room for the database. Space-Node's Large plan (4GB RAM, 2 cores) comfortably handles most sharded bots up to ~20 shards.
Cross-Shard Communication
The biggest challenge with sharding is that each shard has its own cache. To get total member counts or run commands across all guilds, you need cross-shard communication.
Discord.js provides broadcastEval for this:
// Get total guild count across all shards
const results = await client.shard.broadcastEval(c => c.guilds.cache.size);
const totalGuilds = results.reduce((acc, count) => acc + count, 0);
Best Practices
- Start with auto sharding - Let Discord decide the shard count initially
- Use a shared database - Don't rely on in-memory caches across shards
- Monitor per-shard performance - Some shards may be heavier than others
- Plan your hosting resources - Each shard needs its own memory allocation
- Handle shard disconnects gracefully - Implement reconnection logic
Sharding adds complexity, but it is essential for growing bots. Start simple, monitor your resource usage, and scale up your hosting plan as your bot grows.
