PubSub
Mastra uses a publish/subscribe (pub/sub) system as its internal event bus. Components publish events to topics, and other components subscribe to those topics to react. The backend determines whether events are delivered within a single process, between processes on one host, or across separate instances.
Set the backend once on the Mastra instance for use throughout the system. The default is an in-process backend that requires no setup.
How Mastra uses PubSubDirect link to How Mastra uses PubSub
Several built-in systems publish and subscribe to events through the same pub/sub bus:
- Workflow execution: The scheduler publishes a
workflow.startevent, and a long-lived worker consumes it to run the workflow. Step and lifecycle events flow over pub/sub during execution. - Scheduled workflows: The scheduler dispatches due runs by publishing to the workflow topic. See Scheduled workflows.
- Background tasks: A task manager dispatches work to a worker group and fans task lifecycle updates out to subscribers, which is how background task streams stay live. See Background task streaming.
- Agent signals: Sending a signal to an active agent run publishes an event on a thread topic. The event reaches the process that holds the run. A step of an evented run that executes in a different process gets the signal only through storage that shares pending signals across processes.
- Resumable streams: Stream chunks are published per run, so a client that reconnects can replay what it missed.
Because these systems run on one bus, the backend you choose applies to all of them at once.
Delivery modesDirect link to Delivery modes
Backends deliver events in one of two modes, defined by the PubSub contract:
- Pull: Consumers read from the backend on their own, which Mastra does with a long-lived worker loop. Distributed backends such as
RedisStreamsPubSubuse this mode. - Push: Events arrive without the consumer asking, either in process or over HTTP. The default
EventEmitterPubSubdelivers this way in process.
Subscribers can also distribute work through consumer groups. Members of the same group split the events so each event is handled once. A subscriber without a group receives every event, which fans the stream out to all ungrouped subscribers.
Default backendDirect link to Default backend
When you don't set the pubsub option, Mastra uses EventEmitterPubSub. It delivers events in process using a Node.js EventEmitter, so it works without any external service.
import { Mastra } from '@mastra/core'
// No pubsub option: Mastra uses EventEmitterPubSub
export const mastra = new Mastra({})
Because it runs in process, events aren't persisted and don't reach other processes. The default suits a single instance, which covers most applications.
Choosing a backendDirect link to Choosing a backend
Set the pubsub option on the Mastra instance to choose a backend. Each backend implements the same PubSub contract, so the rest of your application doesn't change.
The deciding questions are where the subscriber runs and whether evented workflows and agents run on more than one process.
| Backend | Scope | Evented runs on several processes | Mode | Package |
|---|---|---|---|---|
EventEmitterPubSub | Single process | No | Pull and push | @mastra/core |
UnixSocketPubSub | Multiple processes, one host | No | Push | @mastra/core |
RedisStreamsPubSub | Distributed, multiple hosts | Yes | Pull | @mastra/redis-streams |
ValkeyStreamsPubSub | Distributed, multiple hosts | Yes | Pull | @mastra/valkey-streams |
GoogleCloudPubSub | Distributed, multiple hosts | Yes | Pull | @mastra/google-cloud-pubsub |
Multiple processes on one hostDirect link to Multiple processes on one host
Use UnixSocketPubSub when several processes on the same machine need to share streams and signals. It delivers events over a Unix domain socket and elects one process as a broker. If the broker exits, the remaining processes elect a new one. It doesn't redeliver the events a stopped process held, so it isn't a backend for evented workflows or agents that run on several processes.
import { Mastra } from '@mastra/core'
import { UnixSocketPubSub } from '@mastra/core/events'
export const mastra = new Mastra({
pubsub: new UnixSocketPubSub('/tmp/mastra/events.sock'),
})
Distributed deploymentsDirect link to Distributed deployments
Use a distributed backend when you run more than one instance or host, and every instance receives the same events. This matters whenever a request handled by one instance must reach work running on another.
For example, sending a signal to an agent run requires the signal event to cross the process boundary to the instance that owns the run. With the in-process default, that instance never receives the event.
Durable agent crash recovery also depends on the backend when the storage adapter doesn't support run fencing. Recovery then uses the backend's leases to tell whether another instance still drives a run. RedisStreamsPubSub provides leases across hosts. GoogleCloudPubSub doesn't.
Both backends below deliver across processes and hosts and persist events for redelivery.
The following example uses Redis Streams:
import { Mastra } from '@mastra/core'
import { RedisStreamsPubSub } from '@mastra/redis-streams'
export const mastra = new Mastra({
pubsub: new RedisStreamsPubSub({
url: 'redis://localhost:6379',
}),
})
The following example uses Google Cloud Pub/Sub:
import { Mastra } from '@mastra/core'
import { GoogleCloudPubSub } from '@mastra/google-cloud-pubsub'
export const mastra = new Mastra({
pubsub: new GoogleCloudPubSub({
projectId: 'my-project',
}),
})
Evented workflows and agentsDirect link to Evented workflows and agents
Workflows on the evented execution engine and agents using evented durable execution advance a run one event at a time. Any worker can take the next event, which lets several processes share one run. That only holds when the deployment has both of the following:
- A PubSub backend that redelivers unacknowledged events: When a worker stops in the middle of a step, the backend gives the step's event to another worker.
- A storage adapter with workflow step guards: The backend can deliver the same event more than once, and the step guard keeps a later delivery from saving the step's result a second time. A step can still run more than once, so make steps with side effects idempotent.
The backends that redeliver are marked Yes in the Choosing a backend table. A backend's reference page says whether redelivery can be turned off. The storage adapters with workflow step guards are @mastra/pg and @mastra/libsql. With @mastra/libsql, see evented agent worker takeover for the database setups that work across machines.
EventEmitterPubSub and UnixSocketPubSub don't redeliver an event that a stopped process received and never acknowledged. On the default EventEmitterPubSub, evented workflows and agents run in one process, which is how you try the evented engine locally and run it in tests. Don't use either backend to run evented workflows or agents on several processes:
EventEmitterPubSubdelivers inside one process. An event never reaches another instance, and each instance that boots restarts the active evented workflow runs of the others.UnixSocketPubSubreaches the other processes on the host, but no other process picks up the step of a process that stopped, and each process that boots restarts the active evented workflow runs of the others.
Signals sent to a running evented agentDirect link to Signals sent to a running evented agent
Messages and other signals sent to an evented agent's active run wait until a model request of the run takes them. Where they wait depends on the storage of the agent's memory:
- Storage that keeps pending signals: Each signal waits as a row of the memory messages table under the reserved thread ID
mastra-queue:pending:<threadId>, and undermastra-queue:taken:<threadId>once a run takes it, with no resource ID. No read by thread or resource returns it. When the run saves its messages, the row becomes the message the signal would have been. A transient signal is deleted instead.@mastra/pg,@mastra/libsql, andInMemoryStorefrom@mastra/core/storagekeep pending signals. - Storage that shares pending signals across processes: Every process of the deployment reads and writes the same pending signals. A stored signal then reaches the run's next model request in whichever process executes it.
| Storage adapter | Keeps pending signals | Shares them across processes |
|---|---|---|
@mastra/pg | Yes | Yes |
@mastra/libsql | Yes | Depends on the connection |
InMemoryStore | Yes | No |
A run keeps its signals in storage when the agent's memory uses storage that keeps pending signals and the run is the thread's active run, with a thread and a resourceId. A run started with prepare() and a run with readOnly memory aren't the thread's active run. Any other evented run keeps its signals in the memory of the process that started it, and they reach the run only when that process executes the run's next step. Otherwise the agent answers them in a new turn after the run ends. Input from queueMessage() and queueSignal() always stays in process memory.
A stored signal that the run never takes waits for the thread's next run. The process that started the run starts that next run with the signal when the run ends, if that process is still up. When another run already holds the thread and reads the same storage, that run takes the signal at its next model request, or, if it already made its last one, the signal starts the thread's next turn when that run ends. Otherwise the signal waits for the thread's next run that reads the same storage. A run that fails deletes the signals its failed turn took, whether it fails in the process that started it or on a worker, and the thread's next run receives only the ones it never took. A failure that carries no saved progress is the exception, such as a step that runs out of deliveries with storageVersion: 2: the run then puts back the signals it took and never saved, and the thread's next run receives them again. When a run's modelSettings.timeout.totalMs deadline fires in the process that started it while another process executes its steps, the starting process saves only the turn's input, and the signals the interrupted step took and never saved go back to pending, so the thread's next run receives them again, also when the run saved earlier progress. A suspended run stops receiving signals once another run uses its thread, and signals sent to it afterwards wait for the thread's next run or are answered blocked, as sendSignal() describes. A signal taken by a step that crashes before the run saves its progress is taken again by the thread's next run if the crashed run never recovers or ends.
Warning for unsupported setupsDirect link to Warning for unsupported setups
Mastra logs a warning the first time an evented run is created in a setup that can't support several processes:
- The PubSub backend delivers to other processes and doesn't redeliver unacknowledged events.
- The PubSub backend redelivers unacknowledged events and the storage adapter has no workflow step guards.
- The PubSub backend delivers to other processes and an evented agent's active run keeps its signals in one process.
Mastra logs the last case as a separate warning, the first time such a run starts, beginning with Signals sent to running evented agents aren't supported on several processes with this setup. It names the cause: the run has no memory, thread, or resourceId, the agent's memory storage doesn't keep pending signals, or that storage keeps them in one process.
The default EventEmitterPubSub doesn't trigger the warning, because its events never leave the process. UnixSocketPubSub triggers it even when one process uses the socket, because Mastra can't tell how many processes share it.
If you see the warning with your own PubSub implementation, override the properties that describe its transport. Mastra reads them instead of checking which class the backend is:
import { PubSub } from '@mastra/core/events'
export class MyBrokerPubSub extends PubSub {
// The broker hands an unacknowledged event to another consumer in the group.
override get redeliversUnacked(): boolean {
return true
}
// publish(), subscribe(), unsubscribe(), flush()
}
Return true from redeliversUnacked only when the broker redelivers an abandoned event to another consumer of the same group. If your implementation delivers only inside the publishing process, return false from deliversAcrossProcesses instead. See the PubSub properties.
To disable the warning for a setup that one process uses, set the MASTRA_DISABLE_EVENTED_SETUP_WARNING environment variable to true.
Resumable streamsDirect link to Resumable streams
Resumable streams let a client reconnect and replay events it missed, which requires the backend to keep recent history. Distributed backends such as RedisStreamsPubSub persist events, so they support replay on their own.
In-process delivery doesn't keep history. To add replay on top of EventEmitterPubSub, wrap it in CachingPubSub, which records published events per topic so a late or reconnecting subscriber can catch up before continuing with live events.
import { Mastra } from '@mastra/core'
import { CachingPubSub, EventEmitterPubSub } from '@mastra/core/events'
import { InMemoryServerCache } from '@mastra/core/cache'
const cache = new InMemoryServerCache()
export const mastra = new Mastra({
pubsub: new CachingPubSub(new EventEmitterPubSub(), cache),
})
Visit the PubSub reference for the full delivery contract and the configuration options for each backend.
RelatedDirect link to Related
- PubSub reference
- Mastra class
- Workers: Run workflow orchestration and background tasks in dedicated processes using PubSub
- Background task streaming
- Scheduled workflows