Skip to main content

UnixSocketPubSub

UnixSocketPubSub is a PubSub implementation that delivers events across processes on a single host using a Unix domain socket. It elects one process as a broker, and other processes connect to it as clients. If the broker exits, the remaining clients elect a new broker automatically.

Use it when several local processes need to share a stream, such as coordinating thread streams across the Mastra Code terminal interface. For single-process delivery, use EventEmitterPubSub. For distributed delivery across hosts, use RedisStreamsPubSub or GoogleCloudPubSub.

UnixSocketPubSub is a push transport: events arrive without a read loop, so Mastra does not run a pull worker for it.

Usage example
Direct link to Usage example

Pass a socket path that every participating process shares.

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { UnixSocketPubSub } from '@mastra/core/events'

export const mastra = new Mastra({
pubsub: new UnixSocketPubSub('/tmp/mastra/events.sock'),
})

Constructor parameters
Direct link to Constructor parameters

socketPath:

string
Path to the Unix domain socket. All processes that share a stream must use the same path.

options?:

UnixSocketPubSubOptions
Optional configuration.
number

Properties
Direct link to Properties

socketPath:

string
The socket path passed to the constructor.

supportedModes:

ReadonlyArray<"pull" | "push">
Returns `["push"]`.

isBroker:

boolean
Whether this instance currently acts as the broker.

remoteClientCount:

number
Number of remote clients connected to this broker. Always 0 when this instance is not the broker.

Methods
Direct link to Methods

UnixSocketPubSub implements the PubSub contract. The method below is specific to this implementation.

close()
Direct link to close

Closes the socket connection and, when this instance is the broker, releases the broker role. Call this during graceful shutdown.

await pubsub.close()

Broker election
Direct link to Broker election

The first process to bind the socket becomes the broker and routes events between all connected clients. Other processes connect as clients. When the broker exits, an exclusive lock file serializes the next election so exactly one client becomes the new broker, and the remaining clients resubscribe to it. This avoids a split-brain state where two processes both act as broker.

On this page