Guide
Discord bot sharding: when you need it and how to set it up
A shard is one gateway connection that handles a slice of your bot's servers. Discord requires sharding once a bot is in 2,500 servers, and recommends a shard count through its API. Until then, one connection is fine.
How it works
- Each server is assigned to a shard by its ID:
shard_id = (guild_id >> 22) % shard_count. - Discord's
GET /gateway/botendpoint returns the recommended number of shards, roughly one per 1,000 servers. Libraries can ask for it automatically. - Shards can run in one process (discord.py, JDA) or one process per shard (discord.js ShardingManager). Separate processes cost more memory but isolate crashes.
discord.js: ShardingManager
Keep your bot in bot.js and start this file instead. It spawns one child process per shard with totalShards: 'auto'.
import 'dotenv/config';
import { ShardingManager } from 'discord.js';
const manager = new ShardingManager('./bot.js', {
token: process.env.DISCORD_TOKEN,
totalShards: 'auto',
});
manager.on('shardCreate', (shard) => console.log(`Launched shard ${shard.id}`));
manager.spawn();Inside bot.js, values that span shards (total server count) need client.shard.fetchClientValues('guilds.cache.size').
discord.py: AutoShardedClient
client = discord.AutoShardedClient(intents=discord.Intents.default())
# or, with the commands extension:
# bot = commands.AutoShardedBot(command_prefix='!', intents=intents)All shards run in one process and share one cache, so the extra memory per shard is small.
How much memory per shard?
Rough ballparks, not guarantees: a minimal-cache discord.js shard process often uses around 80 to 150 MB before its cache, plus the cache for its ~1,000 servers. In one shared process (discord.py, JDA) each extra shard adds little on its own; the cache for the servers dominates. The RAM calculator puts these together.
Lower memory by caching less: in discord.js, limit caches with makeCache: Options.cacheWithLimits({...}), and avoid the Server Members and Presence intents unless you need them.