Unified Pipeline for AI Token Spend Management and Attribution

ramp · Finance · 2026 · source Agentic: no · promotional bias: med · source-backed · extracted with prompt 0.5.6 (schema v2)

Generated from extraction.json — do not edit by hand. Every claim cites verbatim source evidence; stated means the quote directly asserts the claim, implied means it supports it indirectly.

Problem

Domain: AI token spend observability

Ramp needed real-time visibility and attribution for volatile AI token spend across teams, customers, models, use cases, and runaway production behaviors.

Constraints:

Architecture

Ramp built a streaming token-spend pipeline with webhook ingestion from LiteLLM and OpenRouter, OAuth/RLS/IP/audit validation, Kafka buffering, ClickHouse ReplacingMergeTree storage, and dashboards for multi-dimensional attribution, forecasting, and anomaly investigation.

Diagram confidence: reconstructed (reconstructed from prose).

flowchart LR
  ai_gateways["AI gateways"] --> webhook_ingestion_endpoints["Webhook ingestion endpoints"]
  validation_decorator_stack["Validation decorator stack"] --> webhook_ingestion_endpoints
  webhook_ingestion_endpoints --> kafka_event_stream["Kafka event stream"]
  kafka_event_stream --> clickhouse_sink_connector["ClickHouse sink connector"]
  clickhouse_sink_connector --> clickhouse_usage_table["ClickHouse usage table"]
  clickhouse_usage_table --> attribution_dashboards["Attribution dashboards"]
  attribution_dashboards --> forecasting_and_anomaly_workflows["Forecasting and anomaly workflows"]
Drag to pan · scroll or use +/− to zoom · reconstructed from the source's described component topology

Components

Component Role Interacts with
AI gateways Emit usage events from LiteLLM and OpenRouter. Webhook ingestion endpoints
Webhook ingestion endpoints Receive LiteLLM and OpenRouter usage payloads. AI gateways, Validation decorator stack, Kafka event stream
Validation decorator stack Handles OAuth2, tenant RLS, IP allowlists, and audit logging. Webhook ingestion endpoints
Kafka event stream Buffers bursty AI usage events and provides durability/replay. Webhook ingestion endpoints, ClickHouse sink connector
ClickHouse sink connector Writes Kafka events into ClickHouse. Kafka event stream, ClickHouse usage table
ClickHouse usage table Stores deduplicated multi-tenant usage and cost records. ClickHouse sink connector, Attribution dashboards
Attribution dashboards Analyze token spend by user, team, project, model, and use case. ClickHouse usage table, Forecasting and anomaly workflows
Forecasting and anomaly workflows Detect cost spikes, phantom tokens, missing caching, agent loops, and prompt bloat. Attribution dashboards

Data flow

LiteLLM and OpenRouter gateways send usage events to Ramp webhooks. Decorators validate OAuth2, establish tenant-scoped RLS, check IP whitelists, and write audits. Events stream through Kafka for durability and burst absorption, sink into ClickHouse with deduplication, and dashboards aggregate cost by dimensions such as model, team, user, project, and use case.

3 supporting quotes
“ingests usage events from AI gateways (LiteLLM and OpenRouter) via webhooks, streams them through Kafka, stores them in ClickHouse for fast analytics”summary, stated
“Every incoming request passes through a decorator stack that validates OAuth2 tokens, establishes Row-Level Security (RLS)”summary, stated
“By placing Kafka between the webhook endpoints and the storage layer, Ramp can absorb traffic spikes without backpressuring the ingestion endpoints.”summary, stated

Why this architecture

Ramp used a streaming analytics pipeline because AI costs are high-volume, bursty, tenant-sensitive, and operationally coupled to latency; invoices are too late to diagnose token-level regressions.

“AI token spend has become one of the most opaque and volatile line items in corporate budgets”summary, stated
“without granular visibility into token-level behavior, many cost and performance issues remain invisible until invoices arrive.”summary, stated

Models used: LiteLLM · OpenRouter · Gemini

Scale

Alternatives considered (roads not taken)

Wait for invoices or aggregate billing reports

Rejected because: Token-level latency and cost regressions remain invisible until too late.

“without granular visibility into token-level behavior, many cost and performance issues remain invisible until invoices arrive.”summary, stated

Write webhooks directly to ClickHouse

Rejected because: Kafka absorbs bursty event spikes and queues during ClickHouse outages.

“If ClickHouse becomes temporarily unavailable, events queue in Kafka rather than being dropped”summary, stated

Use lower-precision cost fields

Rejected because: Small per-token rounding errors compound over millions of events.

“per-token costs like $0.0000150 require this precision because rounding to fewer decimal places compounds into meaningful drift when processing millions of events per month.”summary, stated

Patterns

observability-tracing (cost telemetry)

Ramp collects token-level usage events and attributes spend by model, team, user, project, and use case.

“provides dashboards with multi-dimensional attribution by user, team, project, model, and use case.”summary, stated

cost-aware-routing (AI spend management)

The system identifies oversized models, missing caching, prompt bloat, and runaway loops that inflate spend.

“enabled customers to detect patterns like oversized models for simple tasks, missing caching, runaway agent loops, and prompt bloat.”summary, stated

async-message-orchestration (streaming pipeline)

Kafka decouples bursty webhook ingestion from storage and provides replayability.

“Event Streaming with Kafka: The architecture uses Kafka as a critical decoupling layer between ingestion and storage. This choice addresses a fundamental challenge in LLMOps monitoring: AI usage is inherently bursty.”summary, stated

privacy-preserving-processing (tenant isolation)

OAuth, RLS, IP whitelists, and audit logs enforce multi-tenant access controls.

“validates OAuth2 tokens, establishes Row-Level Security (RLS) with the token's business_id as the tenant identifier”summary, stated

Tradeoffs

Use webhook ingestion from gateways.

Chose LiteLLM/OpenRouter webhooks over Heavy application-code instrumentation.

Rationale: Customers can configure gateways to send events with minimal code changes.

“customers don't need to modify their application code significantly - they simply configure their AI gateways to send events”summary, stated

Use ClickHouse with ReplacingMergeTree.

Chose Columnar analytics with storage-level deduplication over Application-managed deduplication and slower aggregate queries.

Rationale: This supports fast multi-dimensional cost analytics and exactly-once convergence after replay.

“storage-level deduplication that ensures replayed events converge to exactly-once semantics without requiring application logic.”summary, stated

Gotchas (what bit them)

Model package upgrades can silently change token behavior.

Root cause: A LiteLLM upgrade caused Gemini to emit phantom reasoning tokens by default.

Resolution: Track token-level usage and latency so package-induced regressions surface immediately.

“Through detailed investigation using their token tracking system, they discovered that a LiteLLM package upgrade had caused a Gemini model to produce phantom reasoning tokens by default, driving up both latency and cost.”summary, stated

AI usage is bursty and can overwhelm direct ingestion.

Root cause: Batch jobs or runaway agents can emit tens of thousands of events per minute.

Resolution: Buffer through Kafka before ClickHouse storage.

“This choice addresses a fundamental challenge in LLMOps monitoring: AI usage is inherently bursty. A single customer might generate tens of thousands of events per minute during batch jobs or when autonomous agents enter processing loops.”summary, stated

Token-cost rounding errors compound at scale.

Root cause: Per-token prices are tiny but applied across millions of events.

Resolution: Use Decimal(20,10) precision for cost fields.

“per-token costs like $0.0000150 require this precision because rounding to fewer decimal places compounds into meaningful drift”summary, stated

Evaluation

Ramp evaluates the pipeline by anomaly detection, latency/cost incident diagnosis, forecasting, multi-dimensional attribution, and fast aggregate query performance.

Metrics: 13x increase in average monthly AI token spend. · Nearly half of businesses paying at least one AI model provider. · Tens of thousands of events per minute burst capacity. · Month of usage by model/team computed in milliseconds. · Decimal(20,10) cost precision.

“computing a month of usage grouped by model and team takes milliseconds rather than seconds.”summary, stated

Outcomes

The pipeline is designed for bursty usage up to tens of thousands of events per minute per customer.

“The system helped them identify cost issues like phantom reasoning tokens causing unexpected latency and expense, provided forecasting capabilities, and enabled customers to detect patterns like oversized models for simple tasks, missing caching, runaway agent loops, and prompt bloat.”summary, stated