Sharding Your Discord Bot
Sharding is a method of splitting your bot into multiple processes, or "shards". This is useful for large bots that have a lot of guilds, as it allows you to distribute the load across multiple processes. Discord actually requires sharding for bots in more than 2,500 guilds, so understanding how to implement it is crucial as your bot grows.
Sharding is a built-in feature of discord.js, and CommandKit does not alter the way sharding works. While this guide covers how to shard your bot using CommandKit, you can learn more about sharding in discord.js by checking out the discord.js guide.
When to use sharding
You should consider implementing sharding in the following scenarios:
- Your bot is in, or approaching, 2,500 guilds (required by Discord)
- You're experiencing memory or performance issues with a single process
- You want to distribute your bot's workload across multiple cores/machines
- You're considering scaling your bot in the future
Creating a sharding manager file
You can simply create a new file in your source directory named
sharding-manager.ts
(or sharding-manager.js
if you're using
JavaScript) and CommandKit will automatically detect it and use it as
the sharding manager. This file will be responsible for creating the
shards and managing them.
import { ShardingManager } from 'discord.js';
import { join } from 'node:path';
process.loadEnvFile('./.env');
const manager = new ShardingManager(
join(import.meta.dirname, 'index.js'),
{
token: process.env.DISCORD_TOKEN,
totalShards: 2,
mode: 'worker',
},
);
manager.on('shardCreate', (shard) =>
console.log(`Launched shard ${shard.id}`),
);
await manager.spawn();
If you're confused about index.js
being used, this is an
autogenerated entrypoint file that sets up the CommandKit environment.
When running commandkit start
or commandkit dev
, CommandKit
automatically detects the entrypoint file (either
sharding-manager.js
or index.js
) and loads it.