ValkeyStreamsPubSub
ValkeyStreamsPubSub is a PubSub and LeaseProvider implementation backed by Valkey Streams through Valkey GLIDE. It provides persistent cross-process delivery, consumer groups, redelivery, topic cleanup, and distributed leasing.
Use it for Valkey deployments. Use RedisStreamsPubSub for Redis deployments that use the official redis client. Both integrations implement the same Mastra behavior, with independent tests running against Valkey and Redis.
InstallationDirect link to Installation
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/valkey-streams @mastra/valkey @valkey/valkey-glide@2.5.2
pnpm add @mastra/valkey-streams @mastra/valkey @valkey/valkey-glide@2.5.2
yarn add @mastra/valkey-streams @mastra/valkey @valkey/valkey-glide@2.5.2
bun add @mastra/valkey-streams @mastra/valkey @valkey/valkey-glide@2.5.2
@mastra/valkey and @valkey/valkey-glide provide the shared server cache in the usage example. The GLIDE version must match the one @mastra/valkey uses, or the client types don't match.
Usage exampleDirect link to Usage example
Set a server cache that every process shares together with the pubsub: agent runs keep their numbered stream events and ownership record in it, so observing and resuming a run from an offset work through any process. Replicas of one deployment use the same keyPrefix values, and another deployment on the same Valkey needs its own on both the pubsub and the cache.
import { Mastra } from '@mastra/core'
import { ValkeyServerCache } from '@mastra/valkey'
import { ValkeyStreamsPubSub } from '@mastra/valkey-streams'
import { GlideClient } from '@valkey/valkey-glide'
// One GLIDE configuration for the pubsub and the cache, so both reach the same Valkey.
// The top-level await below needs an ES module entry point, as in projects created with create-mastra.
const valkey = {
addresses: [
{ host: process.env.VALKEY_HOST ?? 'localhost', port: Number(process.env.VALKEY_PORT ?? 6379) },
],
}
export const mastra = new Mastra({
pubsub: new ValkeyStreamsPubSub({ valkeyOptions: valkey, keyPrefix: 'mastra:my-app' }),
cache: new ValkeyServerCache(
{ client: await GlideClient.createClient(valkey) },
{ keyPrefix: 'mastra:my-app:cache:' },
),
})
Add credentials or useTLS to that configuration when the server needs them.
Constructor parametersDirect link to Constructor parameters
url?:
valkeyOptions.url. rediss:// and valkeys:// URLs enable TLS unless valkeyOptions.useTLS is set.valkeyOptions?:
keyPrefix?:
blockMs?:
maxStreamLength?:
streamIdleTtlMs?:
agent.stream.*, agent.control.*, agent.thread-stream.*) use shorter transport defaults instead: a day for run topics, matching the run record that authorizes reading them, and an hour for thread streams. Ungrouped subscribers starting at earliest can read retained entries on these topics; after the stream expires, those entries are unavailable. streamIdleTtlMs still caps their transport TTLs, so lowering it lowers them too. Changing CachingPubSub’s runLogTtlMs or threadStreamLogTtlMs changes the cache retention request, not these transport defaults. Set to 0 to disable expiry for every topic; streams that never reach clearTopic then stay in Valkey forever.reclaimIntervalMs?:
reclaimIdleMs?:
leaseRenewIntervalMs (10 seconds by default). Keep reclaimIdleMs above that interval, or an evented workflow step that's still running can be delivered again.maxDeliveryAttempts?:
Infinity to disable the cap.inFlightTimeoutMs?:
deliveryAttempt, so maxDeliveryAttempts still applies. Set this to recover hung handlers in single-consumer groups. The reclaim loop checks the timeout on each pass, and the orchestration worker's heartbeat resets it every leaseRenewIntervalMs (10 seconds by default). Keep it above that interval, or an evented workflow step that's still running can be delivered again. 0 disables it.logger?:
Delivery behaviorDirect link to Delivery behavior
ValkeyStreamsPubSub supports pull delivery and doesn't support numeric replay offsets. Grouped subscribers compete for events through a shared consumer group. Subscribers without a group receive fan-out delivery through private consumer groups.
Use startFrom: "latest" to skip retained entries when a group is first created. The default, "earliest", reads retained entries first.
When a subscriber calls nack, the event is republished with an incremented deliveryAttempt and the original is acknowledged. Once an event reaches maxDeliveryAttempts, it's dropped instead of redelivered. Separately, each subscription periodically reclaims events that an earlier consumer in the group read but never acknowledged, controlled by reclaimIntervalMs and reclaimIdleMs.
A subscription never reclaims an event its own handler is still processing, so a slow handler isn't invoked twice for the same event. If a handler hangs, a different consumer in the group reclaims the event once it has been idle for reclaimIdleMs. In a single-consumer group there's no sibling to do that, so set inFlightTimeoutMs to have the subscription nack the event itself after that long.
Server configurationDirect link to Server configuration
Set maxmemory-policy to noeviction. Consumer groups, unacknowledged entries, and lease keys are live state, and any evicting policy deletes them when the server reaches maxmemory, dropping events and leases. When maxmemory is set and the policy isn't noeviction, ValkeyStreamsPubSub logs a warning once after it first connects. To reclaim streams created without a TTL, follow the Redis Streams runbook with valkey-cli.
Cleanup and shutdownDirect link to Cleanup and shutdown
clearTopic(topic) deletes a topic stream and its consumer groups; Mastra's run lifecycles call it when a run ends, and a stream that never reaches the call is reclaimed by its sliding idle TTL instead. flush() waits for in-flight publishes, and close() stops subscriptions and closes GLIDE connections.
await pubsub.clearTopic('workflow.events.run-123')
await pubsub.flush()
await pubsub.close()