Repository navigation
Description
Is there an existing issue or pull request for this?
- I have searched the existing issues and pull requests
Feature description
Context
Since #121, @wolfstar/plugin-gateway runs the gateway in-process, and @wolfstar/plugin-sharder spreads shards across processes. What no package covers is distributing events across processes: one gateway process (or a set of sharded ones) that receives dispatches, and N worker processes that consume them. The worker count scales independently, and a worker can restart, crash or deploy without dropping the gateway connection.
WolfStar had its own implementation in projects/shared: MessageBroker (Redis Streams) plus Listener/ListenerStore, a @sapphire/pieces listener bound to an arbitrary emitter such as the broker. We are removing that project, and this RFC proposes turning the idea into a maintained plugin. That in-house implementation also shows the pitfalls a generic package has to get right:
Problem in the current MessageBroker |
Consequence |
|---|---|
Reads with XREAD ... STREAMS <stream> $, no consumer group |
Every worker receives every message, so workers cannot share the load. Messages published while a worker is down are lost, because $ only reads new entries |
RedisMessage#ack() calls XACK without a group |
A no-op: there is no pending entries list (PEL) to acknowledge against |
XADD without MAXLEN/MINID |
The stream grows without bound |
Payloads serialized with node:v8 serialize |
Tied to the V8 version: producer and consumer on different Node.js majors can fail to decode, and nothing else can read the payloads |
| No compression | Large dispatches (GUILD_CREATE, member chunks) are stored and transferred at full size |
| No retry/dead-letter handling | A message whose handler throws is never redelivered, or blocks nothing and is silently lost |
Proposal: @wolfstar/plugin-broker
A plugin for @wolfstar/http-framework that publishes and consumes messages over Redis Streams with at-least-once delivery.
Producer
import { createBroker } from "@wolfstar/plugin-broker";
const broker = createBroker({
redis, // ioredis-compatible client, like plugin-cache's RedisClientLike
stream: "wolfstar:events",
maxLength: 100_000, // XADD MAXLEN ~ trimming, or `minId`/age-based retention
codec: jsonCodec({ compression: "gzip", compressionThreshold: 1024 }),
});
await broker.publish("messageCreate", payload);Consumer (workers)
const client = new Client({
broker: {
redis,
stream: "wolfstar:events",
group: "workers", // XGROUP CREATE ... MKSTREAM on start
consumer: `worker-${process.pid}`, // stable name per replica to reclaim its own PEL on restart
batchSize: 10, // COUNT
block: 5_000, // BLOCK ms
claimIdle: 60_000, // XAUTOCLAIM entries idle longer than this, from dead consumers
maxDeliveries: 5, // after that, move to `<stream>:dead` instead of retrying forever
},
});Messages are acknowledged automatically after every listener resolved. A listener that throws leaves the entry pending, so it is redelivered, and after maxDeliveries it moves to a dead-letter stream. message.ack() / message.nack() stay available for manual control.
Listener piece
Like EventGatewayListener in plugin-gateway, a BrokerListener piece typed by event name, loaded from the listeners directory:
@RegisterAsBrokerListener("messageCreate")
export class MessageCreateListener extends BrokerListener<"messageCreate"> {
public override run(payload: GatewayMessageCreateDispatchData, message: BrokerMessage) {}
}An event map augmentation (interface BrokerEvents {}) types payloads per event.
Gateway bridge
The common use case is forwarding plugin-gateway dispatches, so the plugin could ship a helper for it: forwardGatewayDispatches(gatewayClient, broker, { events?: [...] }). It publishes the raw dispatch after plugin-cache has applied it. Workers then read state from the same Redis cache through plugin-cache and receive events through the broker, which reproduces the split gateway/worker architecture with maintained pieces.
Codec
A small Codec interface (encode(value): Buffer | string, decode(buffer)) with a JSON codec by default, supporting bigint through a tagged replacer and optional gzip/brotli, reusing plugin-cache's compression tagging so both packages behave the same. Other codecs (msgpack) can be plugged in. The codec should be shared with the plugin-cache codec proposal (see #137).
Desired solution
A new @wolfstar/plugin-broker package, with:
createBroker(producer) and abrokerclient option (consumer), both on Redis Streams with consumer groups (XGROUP CREATE MKSTREAM,XREADGROUP,XACK).- At-least-once delivery: automatic ack after the listeners resolve, redelivery of pending entries,
XAUTOCLAIMof entries left by dead consumers,maxDeliverieswith a dead-letter stream. - Retention through
MAXLEN ~orMINID. - A pluggable
Codec, JSON withbigintsupport and optional compression by default. Nonode:v8serialization. - A
BrokerListenerpiece withRegisterAsBrokerListener, typed by an augmentableBrokerEventsmap. forwardGatewayDispatchesto bridge@wolfstar/plugin-gateway, documented together with@wolfstar/plugin-sharderand a shared@wolfstar/plugin-cacheRedis cache.- A
./registerentrypoint from day one (RFC: plugin-gateway follow-ups from replacing a dedicated gateway process (register entrypoint, member requests, session resume, …) #121, fix(plugin-gateway,plugin-cache,plugin-sharder): add a no-op./registersubpath export #123). - Graceful shutdown: stop reading, wait for in-flight handlers, leave unacked entries pending for the next consumer.
Alternatives considered
- Keep
MessageBrokerin the application. It works for one consumer, but it has the delivery and retention bugs listed above, and every bot that wants a gateway/worker split would rewrite it. - Redis Pub/Sub. Simpler, but it has no persistence and no acknowledgement: anything published while a worker is down is lost.
- A dedicated message queue (NATS JetStream, RabbitMQ, Kafka). Stronger guarantees, but it adds an infrastructure dependency, while Redis is already required by
plugin-cache. TheCodecand listener layers could later target another transport behind the same API. - Folding it into
plugin-sharder. Sharding and event distribution are orthogonal: a single-shard bot can still want several workers. A separate package keepsplugin-shardersmall.
Additional context
- Current implementation being retired: WolfStar
projects/shared/src/lib/messaging/MessageBroker.ts,RedisMessage.ts,projects/shared/src/lib/structures/Listener.ts,ListenerStore.ts. - Related: RFC: plugin-gateway follow-ups from replacing a dedicated gateway process (register entrypoint, member requests, session resume, …) #121 (in-process gateway), and RFC: pluggable codec and opt-in projection for
@wolfstar/plugin-cache's Redis store #137 (pluggable codec for@wolfstar/plugin-cache).
Activity
pullfrog commentedon Sep 27, 2026
Verdict: actionable, but scope it as a multi-PR package build
This RFC is well specified (concrete API sketches, a clear bug list from the retired
MessageBroker, alternatives considered), the same shape as #121, which was closed after being split into several PRs.@wolfstar/plugin-brokershould get the same treatment rather than landing as one PR. Below is a milestone plan, plus one architectural correction to the RFC's own sketch that implementation should follow instead.Design correction: don't wire the consumer through a
postInitializationPluginhookThe RFC's consumer example (
new Client({ broker: { redis, stream, group, ... } })) implies wiring throughClientOptions, the wayplugin-subcommands-advanced'sSubcommandsAdvancedPluginpatches the command store in apostInitializationhook. That doesn't fit here:Plugin's three hooks (preGenericsInitialization/preInitialization/postInitialization,node_modules/@wolfstar/http-framework/dist/esm/index.d.ts:1684-1953) are all synchronous and all run during the baseClientconstructor, before a subclass has finished its own setup. That's the documented reasonplugin-gateway'sregister.tsexplicitly avoids aPluginhook and shipsGatewayClientas a real subclass with an explicit.start()/.connect()instead ("a hook would run for every Client of the process... before GatewayClient has set up its gateway and cache"). Opening a Redis connection, runningXGROUP CREATE ... MKSTREAM, and starting a read loop is exactly the same kind of async setup — it will hit the same problem.Follow
plugin-gateway's andplugin-cache's actual precedent instead:createBroker(options)returning{ publish(event, payload) }— matches the RFC, no lifecycle concerns (a plainXADDper call).createBrokerConsumer(options)+.connect()/.start()), not something spliced intoClientOptions.Pluginhook — mirroringattachCacheToGatewayinpackages/plugin-cache/src/lib/gateway.ts, which is exactly "wire a Redis-backed thing into a client/gateway that doesn't manage it itself" and returns an unsubscribe callback.forwardGatewayDispatches(gatewayClient, broker, { events? })should follow this same shape (subscribe to the gateway's raw dispatch,broker.publish(...), return an unsubscribe function) rather than a new hook mechanism.container.brokeraccess from pieces is wanted (parallel to RFC: plugin-gateway follow-ups from replacing a dedicated gateway process (register entrypoint, member requests, session resume, …) #121's still-opencontainer.clienttyping item forplugin-gateway), that's a separate opt-in module augmentation, not something that drives the connection lifecycle.Validated building blocks already in this codebase
BrokerListenerneeds no new piece-store type.Listener.Options.emitter(confirmed in the framework's.d.ts) accepts any object shaped like{ on, once, off, emit, setMaxListeners, getMaxListeners }, not just a string key into the container.EventGatewayListeneralready proves this pattern (emitter: "client");BrokerListenercan extendListenerthe same way, loaded from the samelistenersdirectory, withemitterresolving to the broker consumer (by container key, e.g."broker", same convention as"client").RegisterAsBrokerListenerhas a direct template:packages/plugin-gateway/src/util/decorators.ts'sRegisterAsGatewayListeneris the exact class-decorator-wraps-constructor shape to copy.Clientitself extends@vladfrangu/async_event_emitter'sAsyncEventEmitter(already resolved in this workspace's lockfile via@wolfstar/http-framework). That class'semit()tracks in-flight async listener promises, andwaitForAllListenersToComplete(): Promise<boolean>resolvesfalseif any listener threw. Building the consumer's per-message emitter onAsyncEventEmitterand driving XACK off that boolean is a much better fit than inventing custom coordination — it's the same mechanism the framework already uses for its own dispatch listeners.RedisEntityCache.serialize/deserialize(packages/plugin-cache/src/lib/redis.ts) shows the marker-prefix-plus-base64 approach for compression, but plugin-cache'sRedisClientLikehas no stream commands. Don't try to extend it — define a separateRedisStreamClientLike(xadd,xreadgroup,xack,xgroup,xautoclaim,xpending,xlen/xtrim) local toplugin-broker. Ship a self-containedCodec/jsonCodec()now (bigint via tagged replacer + optional gzip/brotli); RFC: pluggable codec and opt-in projection for@wolfstar/plugin-cache's Redis store #137 (pluggable codec forplugin-cache) is still open, so don't block on it — just keep the interface shape (name,encode,decode) compatible so a later unification is a rename, not a rewrite.Milestones (suggested PR split)
packages/plugin-broker—package.json(peer dep@wolfstar/http-framework, matching the current^3.4.0 || ^5.0.0range so the repo'shttp-framework-peer-range.test.tspasses; dep on@vladfrangu/async_event_emitter; dev depioredislikeplugin-cache),tsconfig.json+tsconfig.consumption.json,tsdown.config.ts(createTsdownOptions), a no-opregister.ts(import "./index.js";, per this repo'sunicorn/no-empty-filegotcha), rootREADME.mdpackage table row,.github/labels.yml+.github/labeler.ymlentries forpackages:plugin-broker, and an initialminorchangeset.RedisStreamClientLike,Codec/jsonCodec(), and the low-level stream operations (XADD MAXLEN ~/MINID, idempotentXGROUP CREATE ... MKSTREAM,XREADGROUP,XACK,XAUTOCLAIM,XPENDINGfor delivery counts, dead-letterXADDto<stream>:dead).createBroker/.publish(event, payload).COUNT/BLOCK),AsyncEventEmitter-based dispatch with ack/nack driven bywaitForAllListenersToComplete(),maxDeliveries→ dead-letter,XAUTOCLAIMidle sweep on an interval, manualmessage.ack()/message.nack(), graceful shutdown (stop the loop, await in-flight handlers, leave unacked entries pending).BrokerListenerpiece +RegisterAsBrokerListenerdecorator + augmentableBrokerEventsmap, mirroringEventGatewayListener/RegisterAsGatewayListener.forwardGatewayDispatchesbridge helper, followingattachCacheToGateway's shape.plugin-cache's tests), README, typedoc coverage (src/index.ts+src/register.ts), verify againsttests/http-framework-peer-range.test.ts.Open questions worth resolving before/while implementing
XACKis per-message, not per-listener. If twoBrokerListeners handle the same event and only one throws, the plan above acks only whenwaitForAllListenersToComplete()resolvestrue— confirm that's the intended behavior (the RFC's wording, "a listener that throws leaves the entry pending," supports this).maxDeliveries: needsXPENDING's per-entry delivery count (orXAUTOCLAIM's), which should be pinned down againstioredis's actual return shape before the interface is finalized, the same wayplugin-cache'sRedisClientLikewas scoped to realioredis/Clusterbehavior.createBrokerConsumervs. reusingcreateBrokerwith amodediscriminant — worth deciding once the producer/consumer split above is agreed on.No code changes made in this run (Plan mode). Ready to start on milestone 1 when you'd like implementation to begin.
Claude Sonnet| 𝕏feat(plugin-broker): distribute gateway events across processes over …