Skip to content

RFC: @wolfstar/plugin-broker — distribute gateway events across processes over Redis Streams #136

Closed

Description

@RedStar071

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:

  1. createBroker (producer) and a broker client option (consumer), both on Redis Streams with consumer groups (XGROUP CREATE MKSTREAM, XREADGROUP, XACK).
  2. At-least-once delivery: automatic ack after the listeners resolve, redelivery of pending entries, XAUTOCLAIM of entries left by dead consumers, maxDeliveries with a dead-letter stream.
  3. Retention through MAXLEN ~ or MINID.
  4. A pluggable Codec, JSON with bigint support and optional compression by default. No node:v8 serialization.
  5. A BrokerListener piece with RegisterAsBrokerListener, typed by an augmentable BrokerEvents map.
  6. forwardGatewayDispatches to bridge @wolfstar/plugin-gateway, documented together with @wolfstar/plugin-sharder and a shared @wolfstar/plugin-cache Redis cache.
  7. A ./register entrypoint 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 ./register subpath export #123).
  8. Graceful shutdown: stop reading, wait for in-flight handlers, leave unacked entries pending for the next consumer.

Alternatives considered

  • Keep MessageBroker in 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. The Codec and 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 keeps plugin-sharder small.

Additional context

Activity

  1. added
    packages:plugin-gateway
    packages:plugin-sharder
    on Sep 27, 2026
  2. pullfrog commented on Sep 27, 2026

    @pullfrog
    Contributor

    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-broker should 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 postInitialization Plugin hook

    The RFC's consumer example (new Client({ broker: { redis, stream, group, ... } })) implies wiring through ClientOptions, the way plugin-subcommands-advanced's SubcommandsAdvancedPlugin patches the command store in a postInitialization hook. 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 base Client constructor, before a subclass has finished its own setup. That's the documented reason plugin-gateway's register.ts explicitly avoids a Plugin hook and ships GatewayClient as 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, running XGROUP 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 and plugin-cache's actual precedent instead:

    • Producer: createBroker(options) returning { publish(event, payload) } — matches the RFC, no lifecycle concerns (a plain XADD per call).
    • Consumer: an explicit object the app constructs and starts itself (e.g. createBrokerConsumer(options) + .connect()/.start()), not something spliced into ClientOptions.
    • Wiring into pieces: a plain function, not a Plugin hook — mirroring attachCacheToGateway in packages/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.
    • If typed container.broker access 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-open container.client typing item for plugin-gateway), that's a separate opt-in module augmentation, not something that drives the connection lifecycle.

    Validated building blocks already in this codebase

    • BrokerListener needs 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. EventGatewayListener already proves this pattern (emitter: "client"); BrokerListener can extend Listener the same way, loaded from the same listeners directory, with emitter resolving to the broker consumer (by container key, e.g. "broker", same convention as "client").
    • RegisterAsBrokerListener has a direct template: packages/plugin-gateway/src/util/decorators.ts's RegisterAsGatewayListener is the exact class-decorator-wraps-constructor shape to copy.
    • Ack/redelivery coordination has a ready-made primitive. Client itself extends @vladfrangu/async_event_emitter's AsyncEventEmitter (already resolved in this workspace's lockfile via @wolfstar/http-framework). That class's emit() tracks in-flight async listener promises, and waitForAllListenersToComplete(): Promise<boolean> resolves false if any listener threw. Building the consumer's per-message emitter on AsyncEventEmitter and 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.
    • Codec/compression tagging has a template, not a shared implementation. RedisEntityCache.serialize/deserialize (packages/plugin-cache/src/lib/redis.ts) shows the marker-prefix-plus-base64 approach for compression, but plugin-cache's RedisClientLike has no stream commands. Don't try to extend it — define a separate RedisStreamClientLike (xadd, xreadgroup, xack, xgroup, xautoclaim, xpending, xlen/xtrim) local to plugin-broker. Ship a self-contained Codec/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 for plugin-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)

    1. Package scaffold: packages/plugin-broker — package.json (peer dep @wolfstar/http-framework, matching the current ^3.4.0 || ^5.0.0 range so the repo's http-framework-peer-range.test.ts passes; dep on @vladfrangu/async_event_emitter; dev dep ioredis like plugin-cache), tsconfig.json + tsconfig.consumption.json, tsdown.config.ts (createTsdownOptions), a no-op register.ts (import "./index.js";, per this repo's unicorn/no-empty-file gotcha), root README.md package table row, .github/labels.yml + .github/labeler.yml entries for packages:plugin-broker, and an initial minor changeset.
    2. Redis Streams primitives + Codec: RedisStreamClientLike, Codec/jsonCodec(), and the low-level stream operations (XADD MAXLEN ~/MINID, idempotent XGROUP CREATE ... MKSTREAM, XREADGROUP, XACK, XAUTOCLAIM, XPENDING for delivery counts, dead-letter XADD to <stream>:dead).
    3. Producer: createBroker / .publish(event, payload).
    4. Consumer: batch read loop (COUNT/BLOCK), AsyncEventEmitter-based dispatch with ack/nack driven by waitForAllListenersToComplete(), maxDeliveries → dead-letter, XAUTOCLAIM idle sweep on an interval, manual message.ack()/message.nack(), graceful shutdown (stop the loop, await in-flight handlers, leave unacked entries pending).
    5. BrokerListener piece + RegisterAsBrokerListener decorator + augmentable BrokerEvents map, mirroring EventGatewayListener/RegisterAsGatewayListener.
    6. forwardGatewayDispatches bridge helper, following attachCacheToGateway's shape.
    7. Tests + docs: vitest suite with a mock Redis-stream client (same style as plugin-cache's tests), README, typedoc coverage (src/index.ts + src/register.ts), verify against tests/http-framework-peer-range.test.ts.

    Open questions worth resolving before/while implementing

    • Partial-failure ack semantics: XACK is per-message, not per-listener. If two BrokerListeners handle the same event and only one throws, the plan above acks only when waitForAllListenersToComplete() resolves true — confirm that's the intended behavior (the RFC's wording, "a listener that throws leaves the entry pending," supports this).
    • Delivery-count source for maxDeliveries: needs XPENDING's per-entry delivery count (or XAUTOCLAIM's), which should be pinned down against ioredis's actual return shape before the interface is finalized, the same way plugin-cache's RedisClientLike was scoped to real ioredis/Cluster behavior.
    • Naming: createBrokerConsumer vs. reusing createBroker with a mode discriminant — 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.

    Pullfrog  | Implement plan ➔ | View workflow run | via Pullfrog | Using Claude Sonnet | 𝕏

  3. added a commit that references this issue on Sep 27, 2026
    f3d791e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurepackages:plugin-gatewaypackages:plugin-sharder

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions