To Realtime, a Mastra agent is one more writer on your data. This example triggers agents when users write data and syncs agent activity and agent sessions through the database.
Full example on GitHub
The complete app is in the thruflo/livebase repository.
Store Mastra's data in your database
Point Mastra's storage at your database, so Realtime can sync agent sessions, memory and traces:
import { Agent } from "@mastra/core/agent"
import { Mastra } from "@mastra/core/mastra"
import { Memory } from "@mastra/memory"
import { MastraStorageExporter, Observability } from "@mastra/observability"
import { PostgresStore } from "@mastra/pg"
import { pool } from "~/server/db.server"
const storage = new PostgresStore({ id: "app-storage", pool, schemaName: "public" })
const memory = new Memory({ storage, options: { lastMessages: false } })
const enrichmentAgent = new Agent({
id: "enrichment-agent", name: "Enrichment agent", instructions: "...", model: "...", memory
})
const exporter = new MastraStorageExporter({ strategy: "batch-with-updates", maxBatchWaitMs: 250 })
export const mastra = new Mastra({
agents: { enrichmentAgent },
storage,
observability: new Observability({ configs: { default: { serviceName: "app", exporters: [exporter] } } })
})PostgresStore on your pg pool and public schema puts mastra_threads, mastra_messages and mastra_ai_spans next to your tables. Use it rather than PostgresStoreVNext, because that only stores finished spans. Whereas here, batch-with-updates inserts each span when it starts and updates it when it ends, so the browser sees all the agent steps in progress.
Start agents from your writes
This server function creates a record, then starts its agent:
import { createServerFn } from "@tanstack/react-start"
import { z } from "zod"
import { leadInputs, leads } from "~/db/schema"
import { db } from "~/server/db.server"
import { startLead } from "~/server/runner.server"
import { txid } from "~/server/txid.server"
import { requireWorkspace } from "~/server/workspace.server"
export const createLead = createServerFn({ method: "POST" })
.validator(z.object({ leadId: z.uuid(), inputId: z.uuid(), rawText: z.string().min(1) }))
.handler(async ({ data: { leadId, inputId, rawText } }) => {
const { workspaceId } = await requireWorkspace()
const result = await db.transaction(async (tx) => {
await tx.insert(leads).values({ id: leadId, workspaceId })
const [input] = await tx
.insert(leadInputs)
.values({ id: inputId, workspaceId, leadId, rawText })
.returning({ txid })
return { txid: input!.txid }
})
startLead({ leadId, workspaceId })
return result
})requireWorkspace()stands in for your auth checktxidispg_current_xact_id()::text. Both inserts share one transaction, and the second returns its ID, so there's no extra select. The client waits for that txid to confirm its optimistic insertstartLead()runs after the commit, so the agent reads committed rows, and returns without holding up the response
Run the agent on a thread
Each run is one generate() call on the record's thread:
import type { LeadRef } from "~/lib/types"
import { enrichmentPrompt } from "~/server/enrichment/prompt"
import { recordTools } from "~/server/enrichment/record-tools.server"
import { mastra } from "~/server/mastra/mastra.server"
import { loadEnrichmentSnapshot, setLeadStatus } from "./persist.server"
export async function runEnrichment({ leadId, workspaceId, signal }: LeadRef & { signal: AbortSignal }) {
const snapshot = await loadEnrichmentSnapshot({ leadId, workspaceId })
await setLeadStatus({ leadId, workspaceId, status: "enriching" })
await mastra.getAgent("enrichmentAgent").generate(enrichmentPrompt(snapshot), {
memory: { thread: leadId, resource: workspaceId },
toolsets: { enrichment: recordTools({ leadId, workspaceId, signal }) },
savePerStep: true,
abortSignal: signal
})
signal.throwIfAborted()
await setLeadStatus({ leadId, workspaceId, status: "ready" })
}- Mastra stores
threadandresourceon every thread, message and span row, and live queries filter on them. Here the thread is the record and the resource is the workspace savePerStep: truesaves messages after each step, so they reach the browser while the agent worksgenerate()can resolve after an abort, sothrowIfAborted()keeps an aborted run from marking the recordreadyrecordTools()returns MastracreateTool()tools that write domain rows withupdatedBy: "agent"
Sync agent activity to the browser
Seal Mastra's tables the way you seal your own.
Seal the spans on the server
This server function seals the workspace's spans. Records, threads and messages seal the same way:
import { createServerFn } from "@tanstack/react-start"
import { eq, getTableColumns, sql } from "drizzle-orm"
import { mastraAiSpans } from "~/db/mastra-schema"
import { db } from "~/server/db.server"
import { realtime } from "~/server/realtime.server"
import { requireWorkspace } from "~/server/workspace.server"
export const sealSpans = createServerFn({ method: "POST" }).handler(async () => {
const { workspaceId } = await requireWorkspace()
const query = db
.select({
...getTableColumns(mastraAiSpans),
startedAt: sql<Date | null>`${mastraAiSpans.startedAt}`.as("startedAt"),
endedAt: sql<Date | null>`${mastraAiSpans.endedAt}`.as("endedAt")
})
.from(mastraAiSpans)
.where(eq(mastraAiSpans.resourceId, workspaceId))
return realtime.seal({ query })
})mastraAiSpansdeclares only the columns you sync. Mastra creates and migrates the table, so keep it out of your Drizzle migrations- Mastra's timestamp column names differ from their Drizzle field names, so
startedAtandendedAtneed an SQL alias realtime.seal()seals the server'sworkspaceId, so a browser only gets its own workspace's spans
Filter the spans in the browser
A TanStack DB collection holds the sealed spans, and useLiveQuery narrows them to one record's thread:
import { eq, useLiveQuery } from "@tanstack/react-db"
import { useRealtime } from "~/realtime/RealtimeProvider"
export function useLeadActivity(leadId: string) {
const { descriptors } = useRealtime()
const { data: spans } = useLiveQuery({
query: (q) =>
q
.from({ span: descriptors.spans })
.where(({ span }) => eq(span.threadId, leadId))
.orderBy(({ span }) => span.startedAt, "asc")
})
return spans
}descriptors.spanscomes fromrealtimeCollectionOptions()withrefreshQuery: () => sealSpans(). ItsgetKeyreturns`${span.traceId}:${span.spanId}`, for the table's composite primary key- the sealed query has no
ORDER BY, so order the spans inuseLiveQuery
See the TanStack example for collections, SSR and optimistic writes.
Restart agents when users edit
When a user edits a record, commit the update, then call restartEnrichment(). The runner keeps one AbortController per record:
import type { LeadRef } from "~/lib/types"
import { markLeadFailed, runEnrichment } from "./pipeline.server"
const jobs = new Map<string, { controller: AbortController }>()
const restartTimers = new Map<string, ReturnType<typeof setTimeout>>()
export function startLead(ref: LeadRef) {
const job = { controller: new AbortController() }
jobs.set(ref.leadId, job)
runEnrichment({ ...ref, signal: job.controller.signal })
.catch((error) => job.controller.signal.aborted || markLeadFailed(ref, String(error)))
.finally(() => jobs.get(ref.leadId) === job && jobs.delete(ref.leadId))
}
export function restartEnrichment(ref: LeadRef) {
clearTimeout(restartTimers.get(ref.leadId))
jobs.get(ref.leadId)?.controller.abort()
restartTimers.set(ref.leadId, setTimeout(() => startLead(ref), 1_500))
}restartEnrichment()aborts the running job and starts a new one after 1.5 seconds. Each edit resets the timer, so a burst of edits restarts once- the
jobs.get(ref.leadId) === jobcheck keeps an aborted run that settles late from removing its replacement
The abort reaches generate() through its abortSignal and the tools check the same signal before each write. Agents only write fields that are empty or still hold the agent's own earlier value, so a user's edit always wins. Each run starts with a fresh read, so the restarted run works from the user's values.
Next steps
- read the guides on queries, subscribing and optimistic mutations
- look up
realtime.seal()andrealtimeCollectionOptions()in the SDK reference - see the Drizzle and TanStack examples
- read Mastra's docs on storage, memory and tracing
- browse the full source on GitHub
Need help?
Join our Discord Server to ask questions or see what others are doing with Neon. For paid plan support options, see Support.








