CachingPubSub
CachingPubSub wraps any PubSub implementation and adds event caching and replay. It records published events per topic in a cache, so a subscriber that connects late or reconnects after a disconnect can replay the events it missed before continuing with live events.
Mastra already wraps agent run streams in CachingPubSub with the server cache of the Mastra instance. Use it yourself to add replay to other topics. Over a transport that reaches other processes, such as RedisStreamsPubSub, pass a cache that every process shares: each process otherwise records only the events it published itself.
CachingPubSub is transparent to batching: subscribe() forwards options.batch to the inner pub/sub, and supportsNativeBatching mirrors the inner's value. Wrapping an inner that doesn't support batching results in unbatched delivery even when options.batch is passed.
Usage exampleDirect link to Usage example
Wrap an inner pub/sub and provide a server cache to store events.
import { Mastra } from '@mastra/core'
import { CachingPubSub, EventEmitterPubSub } from '@mastra/core/events'
import { InMemoryServerCache } from '@mastra/core/cache'
const cache = new InMemoryServerCache()
const pubsub = new CachingPubSub(new EventEmitterPubSub(), cache)
export const mastra = new Mastra({
pubsub,
})
The withCaching helper returns the same instance and reads better when wrapping inline:
import { withCaching, EventEmitterPubSub } from '@mastra/core/events'
import { InMemoryServerCache } from '@mastra/core/cache'
const pubsub = withCaching(new EventEmitterPubSub(), new InMemoryServerCache())
Constructor parametersDirect link to Constructor parameters
inner:
cache:
options?:
PropertiesDirect link to Properties
supportsNativeBatching:
true only when the wrapped implementation supports batching.supportsOffsets:
true. Cached events carry numeric indexes that support offset replay, strictly increasing within a log's lifetime. Indexes are opaque cursors, not positions: with the built-in Redis, Valkey and in-memory caches a fresh log starts at a clock-derived value, and Convex numbers densely, so pass an index read from an event (plus one), never a computed count. A recreated log normally continues above its predecessor, but that follows the cache's clock rather than a guarantee.MethodsDirect link to Methods
CachingPubSub implements the PubSub contract. It overrides the replay methods to read cached events. The methods below describe the caching behavior.
publish(topic, event)Direct link to publishtopic-event
Caches the event with the topic's next index, then publishes it to the inner pub/sub. Consecutive publishes get consecutive indexes. A topic whose log expired or was cleared normally restarts above every index it issued before, so a reconnecting subscriber doesn't mistake new events for already-seen ones. That depends on the cache: ConvexServerCache numbers densely instead, and a clock-seeded cache can repeat an index when a log is recreated within the clock's resolution or after the clock moves backwards.
A publish with { localOnly: true } skips the cache and goes straight to the inner pub/sub, so live subscribers receive it but it can't be replayed.
await pubsub.publish('my-topic', {
type: 'example',
data: { value: 1 },
runId: 'run-123',
})
subscribeWithReplay(topic, cb)Direct link to subscribewithreplaytopic-cb
Replays all cached events for the topic, then subscribes to live events.
await pubsub.subscribeWithReplay('my-topic', event => {
console.log(event)
})
subscribeFromOffset(topic, offset, cb)Direct link to subscribefromoffsettopic-offset-cb
Replays cached events starting at offset, then subscribes to live events. Use this when the client knows its last position, to avoid replaying the whole history.
await pubsub.subscribeFromOffset('my-topic', 42, event => {
console.log(event)
})
getHistory(topic, offset?)Direct link to gethistorytopic-offset
Returns cached events for the topic, starting at offset.
const events = await pubsub.getHistory('my-topic', 0)
Returns: Promise<Event[]>
clearTopic(topic)Direct link to cleartopictopic
Removes the topic's cached events and offset counter, and forwards the call to the inner pub/sub so persistent transports (such as RedisStreamsPubSub) can delete their retained state too. Mastra's run lifecycles call this automatically when a run finishes.
await pubsub.clearTopic('my-topic')
FunctionsDirect link to Functions
withCaching(pubsub, cache, options?)Direct link to withcachingpubsub-cache-options
Convenience wrapper that constructs a CachingPubSub. Accepts the same arguments as the constructor and returns the new instance.
import { withCaching, EventEmitterPubSub } from '@mastra/core/events'
import { InMemoryServerCache } from '@mastra/core/cache'
const pubsub = withCaching(new EventEmitterPubSub(), new InMemoryServerCache(), {
keyPrefix: 'events:',
})
Returns: CachingPubSub