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 doesn't run a pull worker for it.
Usage exampleDirect link to Usage example
Pass a socket path that every participating process shares.
import { Mastra } from '@mastra/core'
import { UnixSocketPubSub } from '@mastra/core/events'
export const mastra = new Mastra({
pubsub: new UnixSocketPubSub('/tmp/mastra/events.sock'),
})
Constructor parametersDirect link to Constructor parameters
socketPath:
options?:
PropertiesDirect link to Properties
socketPath:
supportedModes:
["push"].isBroker:
remoteClientCount:
MethodsDirect 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. close() waits up to one second for lease releases that started before it. A release still blocked on another process's lock after that rejects with UnixSocketPubSub is closed. Lease operations started after close() throw.
await pubsub.close()
Broker electionDirect link to Broker election
The broker is the first process to link its socket into place at the shared path. It routes events between all connected clients, and other processes connect to it as clients. Each candidate binds a socket at a private name and hard-links it to the shared path. The link fails if a socket is already there, so a candidate never replaces a live broker by accident.
When the broker exits cleanly, it removes the shared path. Clients then reconnect, and the first to link its socket into place becomes the new broker. The remaining clients resubscribe to it.
A refused connection doesn't trigger a takeover on its own. Clients retry with backoff first. Only if the socket keeps refusing connections does a client take an exclusive lock file and replace it. A broker removes the shared path only while it still points at its own socket. If a broker finds its path deleted or replaced, it steps down and rejoins as a client. Processes that end up on different sockets therefore converge on one broker again instead of staying split.