V1 Cost Tracking (Design)
This guide defines the north-star DX for plugin-based cost tracking in useanalytics.
It is a design-phase document only. API names and payload details are proposed and not final.
It assumes you already completed V1 getting started.
Goals
- Keep the SDK surface minimal.
- Support AI and external API cost use cases.
- Use the same plugin pattern as error tracking.
- Keep metadata flexible without over-modeling.
1) Enable cost tracking in lib/analytics.ts
Enable the feature where you create your server analytics instance:
import { useAnalytics } from "useanalytics";
import { drizzleAdapter } from "useanalytics/adapters/drizzle";
import { costTracking } from "useanalytics/plugins";
import { db } from "@/lib/db";
export const analytics = useAnalytics({
database: drizzleAdapter(db),
plugins: [costTracking()],
});For design parity with other feature plugins, schema generation should include cost-tracking tables when costTracking() is enabled.
2) Minimal API surface
The preferred API is one method with a small payload:
await analytics.captureCost({
type: "ai",
value: 0.0241,
metadata: {
provider: "openai",
model: "gpt-5.4",
operation: "chat-completion",
},
});Proposed payload contract:
type(required): category of cost, for exampleai,external_api,infrastructure.value(required): numeric monetary amount for one tracked operation.metadata(optional): object for provider/model/request context, ids, or tags.
3) Recommended type naming
Use a small stable set of top-level type values to keep dashboards filterable:
aiexternal_apiinfrastructureother
If needed, add a separate optional subtype later in metadata (for example vector_search, email_send, ocr).
4) Suggested usage patterns
AI usage
await analytics.captureCost({
type: "ai",
value: 0.0137,
metadata: {
provider: "anthropic",
model: "claude-sonnet-4.6",
tokensIn: 1320,
tokensOut: 480,
},
});External API usage
await analytics.captureCost({
type: "external_api",
value: 0.002,
metadata: {
provider: "resend",
operation: "send-email",
requestId: "req_123",
},
});5) Design constraints
- Keep one function name (
captureCost) for clarity. - Keep the required fields minimal (
type,value). - Do not require extra identifiers to log cost events.
- Treat
metadataas optional and schema-light. - Prefer plugin enablement over global boolean flags for feature consistency.
6) Future additions (not in v1 design)
- Built-in currency support (if multi-currency is needed).
- Automatic provider adapters for AI SDK providers.
- Aggregation helpers (daily cost rollups, budget alerts).
- Cost anomaly detection.
Notes
- This document defines API design intent only.
- Implementation details (schema shape, migrations, dashboard UI) are intentionally out of scope for now.
Last updated on