Silgi
Plugins

Publisher/PubSub

Event pub/sub with pluggable backends — publish from mutations, subscribe via SSE.

Publish events from any procedure and subscribe to them via SSE or WebSocket. Built-in memory backend, pluggable for Redis/Upstash.

Setup

import { ,  } from 'silgi/plugins'

const  = (new ())

Publish from a mutation

const  = k
  .$input(z.object({ : z.string(), : z.string().email() }))
  .$resolve(async ({ ,  }) => {
    const  = await .db.users.create()
    await pubsub.publish('user:created', )
    return 
  })

Subscribe via SSE

pubsub.subscribe() returns an async generator — use it in a subscription:

const  = s.subscription(async function* () {
  yield* pubsub.subscribe('user:created')
})

The client receives each published event as an SSE message in real time.

Custom backend

Implement the PubSubBackend interface for Redis, Upstash, or any message broker:

import type { PubSubBackend } from 'silgi/plugins'
import  from 'ioredis'

class  implements PubSubBackend {
  #pub = new ()
  #sub = new ()

  async (: string, : unknown) {
    await this.#pub.publish(, .())
  }

  (: string, : (: unknown) => void) {
    this.#sub.subscribe()
    const  = (: string, : string) => {
      if ( === ) (.())
    }
    this.#sub.on('message', )
    return () => {
      this.#sub.unsubscribe()
      this.#sub.off('message', )
    }
  }
}

const  = createPublisher(new ())

MemoryPubSub is single-process only. For multi-server deployments, use Redis or a similar shared backend.

What's next?

  • WebSocket — bidirectional RPC for real-time
  • Procedures — subscriptions with async generators
  • Plugins — other available plugins

On this page