Learning objectives
After reading this article you will be able to:
- Understand what a shard is and how Discord spreads servers across shards
- Know when your bot needs sharding and how many shards to use
- Enable sharding in discord.js and discord.py and adapt your code
On this page
- What is sharding on Discord?
- How does Discord decide which shard gets each server?
- When does your bot need sharding?
- Internal sharding or one process per shard?
- How do you enable sharding in discord.js and discord.py?
- What changes in your code once the bot has shards?
- How many resources does sharding use?
- How to do this on Square Cloud
- FAQs
A Discord bot receives almost everything through a WebSocket connection to the Gateway: messages, server joins, role changes, voice events. While the bot is in a few servers, one connection is enough. As it grows, the event volume on a single session becomes a problem, and Discord starts requiring you to split the load.
That split is called sharding. It tends to show up at the worst moment: the bot grows, stops connecting, and the log shows an error code nobody has seen before. Knowing how it works ahead of time saves you the scramble.
What is sharding on Discord?#
Sharding means opening several sessions with the Gateway instead of one. Each session is a shard, identified by a number starting at 0, and each shard receives the events for a slice of the bot's servers.
In practice, when the bot identifies itself to the Gateway, it sends a [shard_id, num_shards] pair. A bot with three shards opens three connections and sends [0, 3], [1, 3] and [2, 3]. Nothing changes for users: it is the same bot, with the same token and the same commands. Only the way events arrive is split.
A shard is not the same as a process. Several shards can run inside one process, or each shard can have its own process. That choice is yours, and it affects memory and isolation, as you will see below.
How does Discord decide which shard gets each server?#
It uses the formula from the Gateway documentation:
shard_id = (guild_id >> 22) % num_shardsA server ID is a snowflake. The shifted bits (>> 22) encode when the server was created, and the remainder of the division by the shard count picks the destination. Because IDs are too large for regular JavaScript numbers, use BigInt:
// Works out which shard receives a server's events
function shardForGuild(guildId, numShards) {
return Number((BigInt(guildId) >> 22n) % BigInt(numShards));
}
console.log(shardForGuild("197038439483310086", 4)); // 2Two details matter. First, events without a guild_id, such as direct messages, go only to shard 0. Second, the formula guarantees a server always lands on the same shard as long as the total does not change. If you go from 4 to 8 shards, servers are redistributed.
When does your bot need sharding?#
The official rule is clear: each shard supports at most 2,500 servers, and apps in 2,500 servers or more must enable sharding. If the bot tries to connect with a session that is too large, the Gateway closes the connection with this code:
4011 Sharding required
The session would have handled too many guilds - you are required to shard your connection in order to connect.This code does not allow reconnecting: the bot stays offline until you enable sharding. The discord.js guide recommends preparing your code at around 2,000 servers, so you are not caught off guard, and using about 1,000 servers per shard.
To know how many shards to use, ask Discord. The GET /gateway/bot endpoint, authenticated with the bot token, returns:
shards: the recommended number of shards.session_start_limit: how many sessions you can still start (total,remaining,reset_after) andmax_concurrency, how many shards can identify every 5 seconds.
Libraries run this query for you in automatic mode. Below 2,500 servers sharding is optional, and for most small bots it brings no benefit at all. An app that receives interactions only over HTTP, without opening the Gateway, does not need it either.
Internal sharding or one process per shard?#
Libraries offer two models:
| Internal sharding | One process per shard | |
|---|---|---|
| How it works | Several connections in the same process | A parent process starts one child process per shard |
| discord.js | shards: "auto" in the Client options |
ShardingManager |
| discord.py | AutoShardedClient |
Several processes, each with its own shard_ids |
| Code changes | Almost none | Data from other shards only via messages between processes |
| CPU cores | One process, your bot code runs on one thread | Each process uses its own core |
| Failure | One exception takes down every shard | One process crashes, the others keep running |
The discord.js guide warns that internal sharding is not ideal for bigger bots because of memory usage. For bots approaching 2,500 servers, ShardingManager is the most common route in Node.js.
How do you enable sharding in discord.js and discord.py?#
In discord.js v14, your bot file stays almost the same. Rename it to bot.js and create an index.js that starts the shards (the examples use import, so your package.json needs "type": "module"):
// index.js: starts one process per shard
import { ShardingManager } from "discord.js";
const manager = new ShardingManager("./bot.js", {
token: process.env.DISCORD_TOKEN,
totalShards: "auto", // asks Discord how many shards to use
});
manager.on("shardCreate", (shard) => console.log(`Shard ${shard.id} created`));
await manager.spawn();// bot.js: your usual bot, now running as one shard
import { Client, Events, GatewayIntentBits } from "discord.js";
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once(Events.ClientReady, () => {
console.log(`Shard ${client.shard.ids[0]} ready with ${client.guilds.cache.size} servers`);
});
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand() || interaction.commandName !== "servers") return;
// each shard only knows its own servers: add them all up
const perShard = await client.shard.fetchClientValues("guilds.cache.size");
const total = perShard.reduce((sum, n) => sum + n, 0);
await interaction.reply(`I am in ${total} servers.`);
});
client.login(process.env.DISCORD_TOKEN);The example assumes a /servers command is already registered. Attach the shardCreate listener before calling spawn(), as the guide recommends.
In discord.py 2.x, swap discord.Client for discord.AutoShardedClient (or commands.Bot for commands.AutoShardedBot). Without shard_count, the library asks the Gateway and decides how many shards to open, all in one process:
import os
import discord
intents = discord.Intents.default()
client = discord.AutoShardedClient(intents=intents)
@client.event
async def on_ready():
print(f"{client.shard_count} shards, {len(client.guilds)} servers")
for shard_id, latency in client.latencies:
print(f"shard {shard_id}: {latency * 1000:.0f} ms")
client.run(os.environ["DISCORD_TOKEN"])If the bot does not exist yet, start with how to host a discord.js bot or how to host a discord.py bot.
What changes in your code once the bot has shards?#
With internal sharding, almost nothing: the process still sees every server. With one process per shard, a few assumptions break:
- Global counts.
client.guilds.cache.sizeonly shows that shard's servers. UsefetchClientValuesorbroadcastEvalto add them up. - In-memory state. A cache, counter or queue in memory exists once per process. State that must be shared belongs in a database or Redis.
- DMs. Only shard 0 receives them. Logic that depends on direct messages runs there.
- Startup. Shards identify in groups of
max_concurrencyevery 5 seconds, so a bot with many shards takes a while to be fully online. - Restarts. Every session you start counts against
session_start_limit. The daily limit is usually 1,000 sessions, and a bot stuck in a restart loop can exhaust it: when that happens, Discord terminates every session and resets the bot token. See Discord's 429 error.
Very large bots, in more than 150,000 servers, move to large bot sharding: Discord gives you a number, and your total shard count must be a multiple of it, or the connection closes with 4010 Invalid shard.
How many resources does sharding use?#
Sharding does not create new work: the same events arrive, just split up. What grows is the fixed baseline. With one process per shard, each process loads its own runtime, library and caches, so four processes use more baseline memory than one process with four internal shards.
So measure before you pick a model. Run the bot under real load, note each process's peak memory and add them up. The article on how much RAM a Discord bot needs shows how to measure and how to trim the cache, which usually weighs more than the shards themselves.
How to do this on Square Cloud#
On Square Cloud, Discord bots run in isolated containers with discord.js, discord.py, JDA, Discord.Net or any other Gateway library, with sharding and voice. Both internal sharding and ShardingManager work inside the same application, and the average latency to the Discord Gateway is about 30 ms.
Your plan's RAM is a pool shared across your applications, with a minimum of 256 MB per bot, and a single application can use up to 32 GB. When the bot grows, you raise its RAM yourself in the settings or through the API, based on the CPU and RAM metrics in the dashboard. There is no autoscaling: the adjustment is your call.
Containers are always on, with automatic restart (on by default for dashboard deploys) when the process exits with an error, and real-time logs show each shard connecting. See the details on Discord bot hosting.
Bot hosting
Keep your bot online 24/7 with automatic restarts
FAQs
How many servers does a Discord bot need before sharding?
Sharding is required from 2,500 servers, because each shard handles at most 2,500. Below that it is optional, and the discord.js guide suggests getting ready at around 2,000.
How many servers should each shard handle?
The discord.js guide recommends about 1,000 servers per shard. The safest way is to ask Discord: the GET /gateway/bot endpoint returns the recommended number of shards in the shards field.
Does sharding make a bot faster?
Not by itself. It splits the event volume across connections and, with several processes, across CPU cores. A small bot does not get faster with more shards.
Which shard receives direct messages (DMs)?
Events without a guild_id, such as DMs, go only to shard 0. If your bot answers DMs, that shard must always be connected.
Does a bot that only uses slash commands over HTTP need sharding?
No. Sharding applies to Gateway connections. An app that receives interactions only through an HTTP endpoint, without opening the Gateway, has nothing to split.
More in Bots
See all 33 articles- How much does it cost to host a Discord bot?The cost of hosting a Discord bot depends on RAM, uptime, database and outside services. Learn how to estimate your own bill and where the money goes.
- Running a bot on your phone or PC vs hosting itA bot on your PC or phone (Termux) goes offline when the device shuts down, sleeps or loses its network. Compare the three options and when each one fits.
- How to host a Discord bot 24/7To keep a Discord bot online 24/7, run its process on an always-on machine with automatic restarts. Compare your PC, a VPS with pm2 or systemd, and bot hosting.
- Why your Discord bot keeps going offline (and how to fix it)A Discord bot goes offline when the process dies, the token is invalid, an intent is disabled or memory runs out. Learn to diagnose each cause and fix it.