Sharded Pub/Sub Bus
createShardedBus(redis, options?) is the sharded counterpart to createPubSubBus. It uses Redis 7’s SPUBLISH / SSUBSCRIBE to scope traffic to specific shards rather than every node in the cluster. Use it when topic cardinality and publish volume push the regular pub/sub bus past your Redis cluster’s bandwidth budget.
Requires Redis 7+. The bus runs
INFO serveron activate and throws on Redis older than 7. There is no EVALSHA orPUBLISHfallback. On Redis 6, usecreatePubSubBusinstead.
Setup
import { createRedisClient } from 'svelte-adapter-uws-extensions/redis';
import { createShardedBus } from 'svelte-adapter-uws-extensions/redis/sharded-bus';
const redis = createRedisClient();
const bus = await createShardedBus(redis, {
shardKey: (topic) => topic.split(':')[0]
}); Wire into hooks
// hooks.ws.js
export async function init({ platform }) {
await bus.activate(platform);
}
export async function shutdown() {
await bus.deactivate();
}
export const subscribe = bus.hooks.subscribe;
export const subscribeBatch = bus.hooks.subscribeBatch; bus.activate(platform) is idempotent. The bus subscribes lazily - only topics with active local subscribers are followed.
API
| Method | Description |
|---|---|
activate(platform) | Idempotent. Wire the bus to platform.publish and platform.publishBatched. |
deactivate() | Drain followers, close connections. Safe to call from shutdown. |
wrap(platform) | Returns a wrapped platform whose publish / publishBatched route through the bus. Used by cron fan-out. |
follow(topic) | Manually follow a single topic (rare; auto-following covers most cases). |
followBatch(topics) | Bulk follower path. One SSUBSCRIBE per shard channel. |
unfollow(topic) | Drop a follower. |
publishBatched(messages) | One SPUBLISH per shard, regardless of how many events land in that shard. Receivers fan out via platform.publishBatched. |
hooks.subscribe | subscribe hook that auto-follows topics on first local subscriber. |
hooks.subscribeBatch | Bulk variant of the above. |
Options
| Option | Default | Description |
|---|---|---|
shardKey(topic) | identity | Pick a shard slot per topic. Default uses the whole topic; pass a function to group related topics on the same shard. |
maxEnvelopeBytes | 1048576 (1 MB) | Inbound envelope size cap. Larger envelopes are rejected before JSON.parse. |
allowSystemTopics | false | Whether to republish __-prefixed topics. The configured systemChannel (default __realtime) is allowlisted regardless. |
systemChannel | '__realtime' | Bus’s own degraded/recovered system channel. |
Metrics
| Metric | Type | Description |
|---|---|---|
sharded_pubsub_parse_errors_total | counter | Malformed envelopes received. Alert on a non-zero rate. |
pubsub_degraded_total / pubsub_recovered_total | counter | Shared-circuit-breaker transitions. |
See also
createPubSubBus- default Redis pub/sub bus, no Redis 7+ requirement.- Distributed Pub/Sub guide.
Was this page helpful?