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 server on activate and throws on Redis older than 7. There is no EVALSHA or PUBLISH fallback. On Redis 6, use createPubSubBus instead.

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

MethodDescription
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.subscribesubscribe hook that auto-follows topics on first local subscriber.
hooks.subscribeBatchBulk variant of the above.

Options

OptionDefaultDescription
shardKey(topic)identityPick a shard slot per topic. Default uses the whole topic; pass a function to group related topics on the same shard.
maxEnvelopeBytes1048576 (1 MB)Inbound envelope size cap. Larger envelopes are rejected before JSON.parse.
allowSystemTopicsfalseWhether to republish __-prefixed topics. The configured systemChannel (default __realtime) is allowlisted regardless.
systemChannel'__realtime'Bus’s own degraded/recovered system channel.

Metrics

MetricTypeDescription
sharded_pubsub_parse_errors_totalcounterMalformed envelopes received. Alert on a non-zero rate.
pubsub_degraded_total / pubsub_recovered_totalcounterShared-circuit-breaker transitions.

See also

Was this page helpful?