Skip to content

@lunibee/sharding

The @lunibee/sharding package helps large Discord bots split Gateway connections across multiple shards and communicate between them.

Terminal window
bun add @lunibee/sharding @lunibee/types
import { ShardManager } from "@lunibee/sharding";
import { IntentBits } from "@lunibee/types";
const manager = new ShardManager({
token: process.env.DISCORD_TOKEN!,
intents: [IntentBits.guilds, IntentBits.guildMessages],
shardCount: "auto",
});
await manager.connect();

Use automatic shard counts unless you have a reason to control the count yourself.

Discord permits one IDENTIFY every 5 seconds, so spawnDelay defaults to ShardManager.IDENTIFY_INTERVAL (5000 ms). With a max_concurrency of 1, an N-shard bot therefore takes about (N - 1) × 5s to finish connecting (larger max_concurrency values start that many shards per round); starting shards faster earns close code 4008 and invalid-session churn. Pass spawnDelay: 0 only when something else already paces your handshakes.

For multi-process deployments, ClusterManager distributes shards across child processes and supervises them: a cluster that exits unexpectedly is re-forked with the same shard assignment after restartDelay (5000 ms by default), and onClusterExit reports every exit.

import { ClusterManager } from "@lunibee/sharding";
const cluster = new ClusterManager({
token: process.env.DISCORD_TOKEN!,
script: "./dist/bot.js",
shardCount: "auto",
onClusterExit: (info, code) => console.warn(`cluster ${info.id} exited`, code),
});
await cluster.spawn();

Clustering uses child_process.fork() with IPC, which works under both Bun and Node.js. See the ShardManager reference for the full option list.

Use ShardBus when shards need to send application-level messages to each other.

import { ShardBus } from "@lunibee/sharding";
const bus = new ShardBus(0, "lunibee-bot");
bus.on("RELOAD_CONFIG", (message) => {
console.log("Reload requested by shard", message.source);
});
bus.broadcast("RELOAD_CONFIG", { reason: "admin_request" });

bus.onError(fn) receives handler failures. bus.respond(type, fn) answers requests, and bus.request(shard, type, data) / bus.broadcastRequest(type, data, { expected }) collect replies. See Sharding.

A small bot normally starts with a single Client. Sharding becomes useful when the bot grows enough that Discord requires multiple Gateway sessions or when you want to distribute Gateway work across processes.

Startup in rounds of max_concurrency paced by sent IDENTIFYs (maxConcurrency, handshakeTimeout), session-start-limit check that keeps live shards, fetchGatewayInfo() and health().