Sharding
Shardlens works with every common sharding setup without extra configuration. Create one Shardlens instance per
discord.js Client, in the process where that client runs.
| Setup | Where createShardlens goes |
How events are tagged |
|---|---|---|
| Internal sharding | Your bot file, once | Each event carries its guild’s shard |
ShardingManager |
The shard file (not the manager), once per shard | The shards that process runs |
| discord-hybrid-sharding | The cluster file, once per cluster | The cluster’s shard list |
| Several machines | Each process | source.instance tells hosts apart |
Internal sharding
Section titled “Internal sharding”import { createShardlens } from '@shardlens/discordjs';import { Client, GatewayIntentBits } from 'discord.js';
// Internal sharding: one process, several shards. One Shardlens instance tags every event with its guild's shard.const client = new Client({ intents: [GatewayIntentBits.Guilds], shards: 'auto' });
createShardlens(client, { endpoint: process.env.SHARDLENS_URL!, apiKey: process.env.SHARDLENS_INGEST_KEY!,});
await client.login(process.env.DISCORD_TOKEN);ShardingManager
Section titled “ShardingManager”The manager only spawns processes. Put Shardlens in the file each shard runs, exactly as in the quick start:
// manager.ts: one process per shard. Shardlens runs inside each shard process, not in the manager.import { ShardingManager } from 'discord.js';
const manager = new ShardingManager('./dist/bot.js', { token: process.env.DISCORD_TOKEN!, totalShards: 'auto' });manager.on('shardCreate', (shard) => console.log(`Launched shard ${shard.id}`));await manager.spawn();A complete example is in examples/sharded-bot.
discord-hybrid-sharding
Section titled “discord-hybrid-sharding”Each cluster runs a Client with several shards. Attach Shardlens in the cluster file, after setting
client.cluster: Shardlens reads the cluster’s shard list from it.
// bot.ts: one cluster process with several shards.import { createShardlens } from '@shardlens/discordjs';import { Client, GatewayIntentBits } from 'discord.js';import { ClusterClient } from 'discord-hybrid-sharding';
class ClusteredClient extends Client { readonly cluster: ClusterClient<ClusteredClient>;
constructor() { const info = ClusterClient.getInfo(); super({ intents: [GatewayIntentBits.Guilds], shards: info.SHARD_LIST, shardCount: info.TOTAL_SHARDS }); this.cluster = new ClusterClient(this); // set before createShardlens: it reads the cluster ID and shard list }}
const client = new ClusteredClient();
createShardlens(client, { endpoint: process.env.SHARDLENS_URL!, apiKey: process.env.SHARDLENS_INGEST_KEY!,});
await client.login(process.env.DISCORD_TOKEN);The complete example, with the cluster manager, is in
examples/hybrid-sharding.
Stopping a sharded bot
Section titled “Stopping a sharded bot”Each shard or cluster process flushes its own events, so each needs the
shutdown handler for both SIGINT and SIGTERM. Ctrl+C in a
terminal reaches every process, but a signal sent to the manager alone (docker stop, systemd, a hosting platform’s
restart) does not: the shards keep running, and are killed without flushing once the manager exits. Pass the signal on
from the manager, and wait for the processes to finish:
import { once } from 'node:events';import type { ShardingManager } from 'discord.js';
declare const manager: ShardingManager;
for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { await Promise.all( manager.shards.map((shard) => { const child = shard.process; if (!child || child.exitCode !== null) return undefined; shard.kill(); // sends SIGTERM to the shard process return once(child, 'exit'); }), ); process.exit(0); });}With discord-hybrid-sharding (in its default mode: 'process'), do the same for manager.clusters, as in the
example’s manager:
import { once } from 'node:events';import { Child, type ClusterManager } from 'discord-hybrid-sharding';
declare const manager: ClusterManager;
for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { await Promise.all( [...manager.clusters.values()].map((cluster) => { const child = cluster.thread instanceof Child ? cluster.thread.process : null; if (!child || child.exitCode !== null) return undefined; cluster.kill({ force: true, reason: signal }); // After kill(): discord-hybrid-sharding removes the process's listeners when it kills it. return once(child, 'exit'); }), ); process.exit(0); });}lens.shutdown() can be called twice (once for each signal): every call waits for the same flush.
What happens across shards
Section titled “What happens across shards”- Totals (servers, members) add up the latest value from every shard. A shard that hasn’t reported for 2 minutes is shown as stale, not as zero.
- App-wide work (application info, the registered command list, the gateway session budget) runs only in the process that owns shard 0, so it isn’t repeated per shard.
- No
broadcastEval: Shardlens never sends code between shards. - Guild snapshots at startup are taken per shard, so joins and removals while the bot was offline are found on every shard.