Skip to content

Chapter 13 · Storage Layer ​

Chapter goals: Understand Mastra's storage domain model, learn to选择 LibSQL/Postgres and other adapters for different scenarios, and persist workflow state.

13.1 What Is Storage ​

Storage is Mastra runtime's persistent layer. Data that survives进程重启 is managed by it:

  • Memory: message history, threads, resources, working memory;
  • Workflows: persistence snapshots required for suspend/resume;
  • Observability: traces, spans, metrics, logs, feedback;
  • Evals: scores, datasets, experiment results;
  • Background tasks & schedules: background tasks, schedules, threadState.

Default is in-memory storage

When not configured, Mastra uses an in-memory store — suitable for testing and short-term experiments, but data is lost on进程 exit.

13.2 Domain Model ​

Storage is organized by domain; each adapter implements one or more domains:

DomainWhat It Stores
memoryThreads, messages, resources, working memory
workflowsWorkflow suspend/resume snapshots
observabilityTraces, metrics, logs
scores / datasets / experimentsEvaluation-related data
backgroundTasks / schedules / threadStateBackground task and schedule state

Selection principle:高频 transactional reads/writes like memory → choose LibSQL/PostgreSQL; analytical queries → columnar or specialized backends.

13.3 Configuring LibSQL (Development and Small Production) ​

typescript
// src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { LibSQLStore } from '@mastra/libsql'

export const mastra = new Mastra({
  storage: new LibSQLStore({
    // Local file; swap to libsql:// remote instance (Turso) for production
    url: process.env.NODE_ENV === 'production'
      ? process.env.LIBSQL_URL!
      : 'file:./mastra.db',
    authToken: process.env.LIBSQL_AUTH_TOKEN, // Required for remote instances
  }),
  agents: { support: supportAgent },
  workflows: { refundFlow },
})

13.4 Configuring Postgres (Large-Scale Production) ​

typescript
// src/mastra/storage.ts
import { MastraStorage } from '@mastra/core/storage'
import { PgStore } from '@mastra/pg'

export const storage: MastraStorage = new PgStore({
  id: 'main-storage',
  connectionString: process.env.DATABASE_URL,
  // Optional: specify schema name for multi-env isolation
  schemaName: 'mastra_prod',
})

13.5 In-Memory Storage for Tests ​

No persistence needed for unit tests — explicitly声明内存存储, discard after each run:

typescript
// tests/setup.ts
import { Mastra } from '@mastra/core'
import { InMemoryStore } from '@mastra/core/storage'

export const testMastra = new Mastra({
  // Isolated and zero residue; each test instance互不干扰
  storage: new InMemoryStore(),
  agents: { support: supportAgent },
})

13.6 Workflow State Persistence Verification ​

typescript
// src/verify-persistence.ts
import { mastra } from './mastra'

// Start a workflow with suspend, kill the进程,
// restart and resume with the same runId — state restores from storage
const run = await mastra.getWorkflow('refundFlow').createRunAsync()
const result = await run.start({ inputData: { orderId: 'A-1001' } })
console.log(result.status) // 'suspended' (waiting for approval)
// After进程 restart:
// const resumed = await run.resume({ resumeData: { approved: true } })

13.7 Chapter Summary ​

  • Storage is the unified persistent layer for memory/workflows/observability/evals;
  • Default in-memory storage is test-only; production必须配置持久适配器;
  • LibSQL (local file or Turso) suits development and small-scale; Postgres suits large-scale;
  • Workflow suspend/resume依赖存储快照; seamlessly恢复 after restart.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What storage does Mastra use when not configured?

2. Which of the following is NOT managed by Mastra storage?

3. What storage layer capability does the workflow suspend/resume mechanism rely on?

4. The read/write characteristics of the memory domain determine which type of backend is suitable?

🛠️ Hands-On Exercises ​

  1. Run the same suspend-including workflow with default in-memory storage vs LibSQLStore; restart the进程 and对比 the resume结果.
  2. Register a Turso云端 LibSQL instance and migrate本地 data onto it. 3.查看 which domains your adapter supports; find缺失的领域 and think about替代方案.

Next: Chapter 14 · Building an MCP Server