Skip to content

ShardManager

ShardManager from @lunibee/sharding manages multiple Gateway connections (shards) for bots serving more than 2,500 guilds. It supports automatic shard count discovery, per-shard info, and horizontal reconnect logic.

import { ShardManager } from "@lunibee/sharding";
// or via the main package:
import { ShardManager } from "lunibee";
new ShardManager(options: ShardManagerOptions)
Option Type Description
token string Discord bot token.
intents GatewayIntentResolvable Gateway intents for all shards.
shardCount number | "auto" Number of shards. "auto" fetches Discord’s recommendation.
presence GatewayPresence Initial presence for all shards.
autoScale boolean Automatically rescale shards over time.
Property Type Description
shards Map<number, Gateway> Map of shard ID to Gateway instance.

Starts all shards. Uses shardCount: "auto" to query Discord for the recommended count.

await manager.connect();

Closes all shard connections and clears the shard map.

manager.destroy();

Fetches the recommended shard count from Discord’s /gateway/bot endpoint.

const count = await manager.fetchRecommendedShardCount();
console.log(`Recommended shards: ${count}`);

Calculates which shard handles a given guild ID using Discord’s formula:

shardId = (guildId >> 22) % totalShards
const shardId = manager.getShardIdForGuild("123456789012345678");
console.log(`Guild is on shard ${shardId}`);

Sends a raw Gateway payload to all shards.

Returns an array of ShardInfo objects:

const info = manager.info();
for (const shard of info) {
console.log(`Shard ${shard.id}: ${shard.state} — ping ${shard.ping}ms`);
}

ShardInfo shape:

interface ShardInfo {
id: number;
state: GatewayState;
ping: number;
guilds: number; // only available if guild count tracking is enabled
}
import { ShardManager, IntentBits } from "lunibee";
const manager = new ShardManager({
token: process.env.DISCORD_TOKEN!,
intents: [IntentBits.guilds, IntentBits.guildMessages],
shardCount: "auto",
});
await manager.connect();
console.log(`Running ${manager.shards.size} shards.`);
// Graceful shutdown
process.on("SIGINT", () => {
manager.destroy();
process.exit(0);
});

[!NOTE] Sharding is only required for bots in 2,500+ guilds. For smaller bots, use Client directly.

For very large bots (100k+ guilds), use ClusterManager from @lunibee/sharding to distribute shards across multiple processes:

import { ClusterManager } from "@lunibee/sharding";
const cluster = new ClusterManager({
token: process.env.DISCORD_TOKEN!,
script: "./dist/bot.js", // worker script path
shardCount: "auto",
clusterCount: 4, // number of CPU worker processes
});
await cluster.connect();