Architecture
How the parts of TrailAI fit together, and what happens to a span between your application and a chart. Useful for evaluating the platform, self-hosting it, or debugging an ingestion problem.

Repository layout
trail/
├── server/ # TypeScript / Node.js REST API backend
├── web-client/ # Next.js dashboard (App Router)
├── sdk/
│ ├── python/ # trailai — the primary SDK
│ └── typescript/ # trailai — Node/TS SDK
├── tools/loadgen/ # synthetic OTLP load generator (testing)
├── tests/ # integration tests
├── docs/ # internal ADRs, specs, and plans
└── documentation/ # ← this user-facing documentation set
Components
Server (server/)
Express + TypeScript, PostgreSQL, layered:
Request → Route → Security middleware → Controller → Model / SQL query → PostgreSQL
Three route namespaces, all mounted under /api:
| Namespace | Consumer | Auth | Examples |
|---|---|---|---|
/api/client/v1/* |
The dashboard | JWT session, Client role | orgs, projects, traces, metrics, guardrails, prompts, billing |
/api/sdk/v1/* |
The SDKs | X-Public-Key + X-Secret-Key, Sdk role |
traces, metrics, prompt/compiled, vault/secrets, guardrail/detect |
/api/admin/v1/* |
Operators | Super Admin role | roles, logs, provisioning |
Layers:
- Routes — wire paths to middleware chains and controllers. Path constants live in
server/src/config/routenames.cfg.ts. - Security middleware — JWT verification, role gating (Super Admin / Client / Sdk), user-agent validation, account-status checks.
- Validators — Joi schemas, applied before the controller runs.
- Controllers — business logic; ~25 of them.
- Models — static-class abstractions over PostgreSQL tables; ~32 of them. They go through a
small document layer (
server/src/db): typed columns for top-level fields,jsonbfor nested data such as span attributes, 24-hex string ids. - Queries — the dashboard analytics are hand-written, parameterised SQL in
server/src/db/queries. - Services — external integrations: AI provider adapters (OpenAI, Anthropic, Cohere, Mistral, Gemini, Grok, LLaMA, DeepSeek), SendGrid email, payment gateway, and the guardrail detection engine.
Notable technology: protobuf (protobufjs) for decoding OTLP payloads, Socket.IO for real-time
dashboard updates, JWT + bcrypt + Google OAuth2 for auth, Jest for tests.
Web client (web-client/)
Next.js App Router, React, Tailwind, Radix UI + MUI, Zustand for state, TanStack Table for grids.
- Route groups:
(auth)for public pages,(dashboard)for the authenticated app. - Auth: NextAuth, backed by the server's
client/API. - API routes: the app's own
/api/*handlers proxy to the backend, so the browser never holds a backend token directly andEXTERNAL_API_URLstays server-side.
SDKs (sdk/)
- Python (
trailai) — the primary SDK. Auto-instruments 40+ AI libraries, exports via OpenTelemetry OTLP/HTTP, and provides guardrail, prompt, and vault modules. - TypeScript (
trailai) — Node instrumentation for OpenAI, Anthropic, Cohere, and Ollama, plus prompt hub and vault features.
Load generator (tools/loadgen/)
A Python CLI that fabricates realistic LLM / embedding / vector-DB / nested-agent traces and pushes
them through the same OTLP wire path as the SDK (/api/sdk/v1/traces) — no real LLM calls.
provision → run → teardown, isolated to a dedicated synthetic project. Production runs are gated
behind a synthetic-project check plus an explicit --confirm-prod flag. It is the right tool for
populating a demo org before capturing documentation screenshots. See tools/loadgen/README.md.
The ingestion path
What happens between client.chat.completions.create(...) and a number on a chart:
1. Your code calls an instrumented library
│
2. The SDK's instrumentor wraps the call, opens a span, and records
gen_ai.* attributes: model, prompt, completion, tokens, latency
│
3. Span cost is computed locally from a pricing table
(fetched at init from the pricing JSON, overridable via pricing_json=)
│
4. Span is queued in a BatchSpanProcessor
(or exported immediately when disable_batch=True)
│
5. OTLP/HTTP POST → <TRAIL_URL without a trailing /v1>/v1/traces
headers: X-Public-Key, X-Secret-Key
│
6. Server: UserAgent.verify → UserAccess.sdkOnly → VerifyToken.sdk → validator
│
7. TracesController decodes the protobuf payload, resolves the key pair to a
project, and writes spans + derived aggregates to PostgreSQL
│
8. Dashboard queries /api/client/v1/* which reads those tables
Metrics follow the same path via /api/sdk/v1/metrics.
Guardrails, prompts, and vault are plain JSON REST calls to their own /api/sdk/v1/* endpoints,
not OTLP.
Why the URL shape matters
The Python SDK normalises TRAIL_URL to a base without a trailing /v1 and builds every
endpoint from it:
| Feature | Path built |
|---|---|
| Tracing / metrics | <base>/v1/traces, <base>/v1/metrics (OTLP exporter) |
| Prompts | <base>/v1/prompt/compiled |
| Vault | <base>/v1/vault/secrets |
| Guardrails | <base>/v1/guardrail/detect |
So https://host/api/sdk/v1 and https://host/api/sdk both work (since trailai 1.7.0;
older versions needed exactly …/api/sdk/v1). https://host/api or a bare host do not.
Data model, briefly
| Collection group | Holds |
|---|---|
trace, event, histogram, sum, metric |
Telemetry, span-level and aggregated |
organization, project, members, role, user |
Tenancy and access control |
apikeys |
Public/secret key pairs, hashed |
guardrail, guardprompts |
Guardrail configs and every check performed |
prompt |
Prompts and their versions |
vault |
Encrypted secrets |
models, aiinfo |
Registered provider models and pricing metadata |
openground |
Saved provider-comparison runs |
subscription, invoice, usage, billaddress, paymethods |
Billing |
notification, log, cronlogger |
Alerts and operational logging |
Analytics aggregate in PostgreSQL (SQL over the traces, sums and related tables, with
span attributes in an indexed jsonb column). The move from MongoDB is recorded in
docs/adr/0002-postgresql-as-primary-datastore.md;
the option of a columnar store for very large analytics volumes stays open.
Security model
| Boundary | Control |
|---|---|
| SDK → server | Public + secret key headers, verified per request; secret keys stored hashed |
| Dashboard → server | JWT session issued at login, Client-role gated |
| Admin endpoints | Separate namespace, Super Admin role only |
| Between projects | Every query is project-scoped from the resolved key or session |
| Vault secrets | Encrypted at rest; the SDK receives values only over an authenticated call |
| Guardrail failure | Fails closed — an unreachable guardrail service returns verdict: "yes" (blocked) rather than silently allowing content |
Deployment
render.yaml at the repo root describes the reference deployment: the server, the web client, and a
Render Postgres database. Any Node-capable host works — the only hard dependency is PostgreSQL 14+
(the server creates and upgrades its schema on startup).
Environment configuration:
- Server —
DATABASE_URL, JWT secret, SendGrid credentials, payment gateway keys, AI provider keys for OpenGround. - Web client —
EXTERNAL_API_URL,NEXTAUTH_SECRET,NEXTAUTH_URL,GOOGLE_CLIENT_ID. See Running Locally.