Metrics
Mastra automatically derives metrics from spans as traced operations complete. No separate metric instrumentation is required.
Mastra emits:
- Duration metrics for agent runs, workflows, tools, model calls, and processors
- Token usage metrics for model input and output, including detailed token categories when the provider reports them
- Cost estimates calculated from token usage, provider, model, and model prices from models.dev or from a custom gateway
Metrics retain trace correlation context, so you can investigate a change in a chart by finding the related span. See the Automatic metrics reference for metric names, labels, and cost fields. To record your own measurements, emit custom metrics.
When to use metricsDirect link to When to use metrics
- Monitor latency across agents, tools, workflows, and model calls
- Track token consumption and estimated cost over time
- Compare success and error rates across agents or tools
- Measure the effect of prompt, model, or code changes
- Count business events, such as orders processed or documents indexed
Storage supportDirect link to Storage support
Metrics require an analytics-capable observability store:
- DuckDB through
@mastra/duckdbis recommended for local development. - ClickHouse through
@mastra/clickhouseis recommended for high-volume production workloads. - PostgresStoreVNext supports metrics when its observability domain is enabled.
- In-memory storage supports metrics, but its data is lost when the process restarts.
- Google Cloud Spanner disables metrics by default. Set
disableMetrics: falseonly for light workloads, or route metrics to a dedicated OLAP store.
Other storage adapters, including LibSQL, MSSQL, and MongoDB, can store other observability signals but don't implement metric storage and queries.
Set up local metricsDirect link to Set up local metrics
Install the observability, application storage, and DuckDB packages:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/observability @mastra/libsql @mastra/duckdb
pnpm add @mastra/observability @mastra/libsql @mastra/duckdb
yarn add @mastra/observability @mastra/libsql @mastra/duckdb
bun add @mastra/observability @mastra/libsql @mastra/duckdb
Configure a composite store that routes the observability domain to DuckDB:
import { Mastra } from '@mastra/core/mastra'
import { LibSQLStore } from '@mastra/libsql'
import { DuckDBStore } from '@mastra/duckdb'
import { MastraCompositeStore } from '@mastra/core/storage'
import { Observability, MastraStorageExporter, SensitiveDataFilter } from '@mastra/observability'
export const mastra = new Mastra({
storage: new MastraCompositeStore({
id: 'composite-storage',
default: new LibSQLStore({
id: 'mastra-storage',
url: 'file:./mastra.db',
}),
domains: {
observability: await new DuckDBStore().getStore('observability'),
},
}),
observability: new Observability({
configs: {
default: {
serviceName: 'mastra',
exporters: [new MastraStorageExporter()],
spanOutputProcessors: [new SensitiveDataFilter()],
},
},
}),
})
MastraStorageExporter persists metrics to the configured observability store and makes them available to Studio. Use MastraPlatformExporter instead, or alongside it, to send metrics to Mastra Platform.
Emit custom metricsDirect link to Emit custom metrics
Emit your own metrics from tools and workflow steps with metrics.emit(). Custom metrics go to the same exporters and storage as automatic metrics. They also carry the trace and span of the tool call or step that emitted them.
In a tool, read metrics from the execution context:
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const lookupOrder = createTool({
id: 'lookup-order',
description: 'Looks up an order by ID',
inputSchema: z.object({ orderId: z.string() }),
execute: async ({ orderId }, context) => {
const order = await db.orders.find(orderId)
context.metrics?.emit('orders_looked_up', 1, {
status: order ? 'found' : 'missing',
})
return { order }
},
})
In a workflow step, read metrics from the execute parameters:
import { createStep } from '@mastra/core/workflows'
import { z } from 'zod'
const chargeCard = createStep({
id: 'charge-card',
inputSchema: z.object({ amount: z.number(), currency: z.string() }),
outputSchema: z.object({ charged: z.boolean() }),
execute: async ({ inputData, metrics }) => {
metrics?.emit('payment_amount', inputData.amount, { currency: inputData.currency })
return { charged: true }
},
})
Mastra drops negative, NaN, and infinite values. When observability isn't configured, emit() does nothing.
Keep labels low-cardinalityDirect link to Keep labels low-cardinality
Each distinct combination of labels becomes a separate series in the metrics store. Use labels for small, fixed sets of values, such as a status, region, or plan tier. Don't use IDs or free text as labels.
Mastra removes labels that would create unbounded series. By default it drops trace_id, span_id, run_id, request_id, user_id, resource_id, session_id, and thread_id, and any label whose value is a UUID. Each metric still keeps its trace and span IDs, so you can go from a metric to the related trace without them. Change this behavior with the cardinality option in the observability configuration.
See the MetricsContext reference for every parameter.
View and query metricsDirect link to View and query metrics
Use the Studio observability dashboard to inspect KPI cards, breakdowns, and time-series charts. For custom dashboards and analysis, use the observability store, @mastra/client-js, HTTP endpoints, or CLI described in the Metric queries reference. To query a custom metric, pass the name you gave to emit().
In production, always include a timestamp range in metric queries. Time bounds limit the data scanned and allow partitioned backends to skip unrelated partitions or chunks.