Skip to content
pleach
Gateway

Gateway · Cost events

Per-call cost-event emission — CostEmitter contract, CostMiddleware factory, and four reference adapters (OTel, Postgres, Datadog, Honeycomb).

Every successful gateway call emits one CostEvent to the configured destination, unbatched. A destination can batch internally, and the reference adapters below do.

CostEmitter contract

interface CostEmitter {
  emit(event: CostEvent): Promise<void> | void
  flush?(): Promise<void>
}

CostEmitter extends CostEventSink with an optional flush() for buffered adapters. Anywhere a CostEventSink is expected, a CostEmitter works.

Implementations must:

  • Never throw synchronously from emit(). A failure inside an adapter should not depend on the caller to contain it; buffer and log, or swallow with a counter.
  • Own their failure handling. createCostMiddleware does wrap emit() in try/catch. A throw, or a rejected promise, goes to the onError option when you set one and is swallowed otherwise. The event is lost either way, and the gateway call isn't failed.

Implementations may:

  • Return a Promise to await a remote write, or void if they buffer and flush asynchronously.
  • Implement flush() if they buffer. Call it from your shutdown hook to drain pending events.

CostMiddleware factory

Takes a CostEmitter plus a computeCost mapper and returns a function to call after each route response.

The output of runtime.routeChatCompletion(input) carries { providerInvoked, modelInvoked, content, usage, costUsd?, costOmitted?, routingDecisionId }. It has no tenantId, family, callClass, byokActive, or full routingDecision. Merge those from the request input and your own routing context at the call site, then read them in computeCost:

import { createCostMiddleware, createOtelCostEmitter } from "@pleach/gateway/cost"
import { asTenantId } from "@pleach/gateway"
import type {
  RouteChatCompletionInput,
  RouteChatCompletionOutput,
} from "@pleach/gateway"

// The merged observation: route output + the fields the host supplies.
type CostObservation = RouteChatCompletionOutput & {
  tenantId: string
  family: RouteChatCompletionInput["family"]
  callClass: "synthesize" | "reasoning" | "converse" | "utility"
  byokActive: boolean
  rootTurnId: string   // the id you passed to route(), or the one it generated
}

const middleware = createCostMiddleware<CostObservation>({
  emitter: createOtelCostEmitter({ meter }),
  computeCost: (route, response) => ({
    type: "domain.gateway.cost.recorded",
    tenantId: asTenantId(response.tenantId),   // non-empty: sourced from input.tenantId
    rootTurnId: response.rootTurnId,           // required: buckets the event for the per-root-turn ceiling
    family: response.family,
    callClass: response.callClass,
    modelInvoked: response.modelInvoked,
    // An unknown cost is incomplete, not free: the ceiling fails closed on it.
    costUsd: response.costUsd ?? 0,
    costIncomplete: response.costUsd === undefined,
    promptTokens: response.usage.promptTokens,
    completionTokens: response.usage.completionTokens,
    byokActive: response.byokActive,
    routingDecision: {
      family: response.family,
      call_class: response.callClass,
      selected_model: response.modelInvoked,
      transport: "openrouter",
      byok_active: response.byokActive,
      upgrade_path_invoked: false,
      fallback_chain: [],
      raw_provider_cost_usd: response.costUsd ?? 0,
      markup_pct: 0,
    },
    timestamp: new Date().toISOString(),
  }),
})

const output = await runtime.routeChatCompletion(input)
void middleware({
  route: "chat.completion",
  response: {
    ...output,
    tenantId: input.tenantId,
    family: input.family,
    callClass: "converse",   // host routing context — not on the route output
    byokActive: false,       // host routing context — not on the route output
    rootTurnId,              // host routing context: the same id for every call in one root turn
  },
})

costUsd is present only when the transport reports a finite, non-negative cost. Otherwise it's absent and costOmitted says why: "unpriced" for a served call with no usable cost, or "not-a-call" for the stub answer when no transport is wired. The llm.invocation span sets pleach.cost.usd only for a known cost, and pleach.cost.incomplete: true otherwise. Map an absent cost to costUsd: 0 with costIncomplete: true, as above, never to a bare 0.

route is a free-form string ("chat.completion", "embedding", a tenant-scoped slug) forwarded verbatim to computeCost.

computeCost may return null to skip emission, for example on a cached response with no provider cost. Don't throw to skip; a throw means a real error.

onError is optional but recommended. If computeCost throws or emitter.emit rejects, the error is swallowed by default, because gateway calls must not fail when the cost destination is down. Set onError to forward it to your observability layer.

The factory returns middleware & { flush }; call middleware.flush() on shutdown to drain buffered adapters.

Reference adapters

Four adapters cover common destinations. They use your existing client (pg.Pool, an @opentelemetry/api Meter, global fetch), so no vendor SDK is a hard dependency.

OTel

import { metrics } from "@opentelemetry/api"
import { createOtelCostEmitter } from "@pleach/gateway/cost"

const meter = metrics.getMeter("@pleach/gateway")
const emitter = createOtelCostEmitter({ meter })

Emits two counters per CostEvent:

  • pleach_gateway_cost_usd (Counter, double) — incremented by event.costUsd.
  • pleach_gateway_tokens_total (Counter, long) — incremented by prompt plus completion tokens, with attribute token.kind = "prompt" | "completion".

Attributes on every measurement: tenant.id, provider.family, call.class, model.invoked, byok.active, cost.event.type.

The OTel SDK is an optional peer; the factory takes any meter shaped like @opentelemetry/api's Meter. Override counter names with costCounterName / tokensCounterName. See OpenTelemetry.

Postgres

import { Pool } from "pg"
import { createPostgresCostEmitter } from "@pleach/gateway/cost"

const pool = new Pool({ connectionString: process.env.DATABASE_URL })
const emitter = createPostgresCostEmitter({
  pool,
  table: "your_cost_events_table", // the table the schema tier created
  batchSize: 100,
  flushIntervalMs: 5000,
})

Buffered: emit() returns immediately, and flushing is timer-driven (default 5s), size-driven (default 100 events), or manual via flush(). The table ships in the @pleach/gateway schema tier. Apply it with the schema CLI:

npx @pleach/core schema --apply --with @pleach/gateway

The table stores one row per event, with the event's tenant, family, call class, model, cost, token counts, BYOK flag and key hash, and routing decision. Row-level security is on with a service-role writer policy, so other roles are denied by default, for reads as well as writes. To fence reads by tenant, apply the @pleach/compliance tier. The adapter sets no per-connection session variables; that's your pool configuration.

The table option must be a bare identifier or schema.table, or the factory throws at construction.

Datadog

import { createDatadogCostEmitter } from "@pleach/gateway/cost"

const emitter = createDatadogCostEmitter({
  apiKey: process.env.DD_API_KEY!,
  site: "datadoghq.com",
  flushIntervalMs: 10_000,
  batchSize: 100,
})

POSTs to Datadog's /api/v2/series endpoint with global fetch. Set site for your region (datadoghq.eu, us3.datadoghq.com). The factory doesn't validate site, since Datadog adds sites over time.

Two series per event:

  • pleach.gateway.cost.usd (count, event.costUsd)
  • pleach.gateway.tokens.total (count, prompt + completion)

Both series carry the tags tenant_id, family, call_class, model, byok. The token series adds two points tagged token_kind:prompt and token_kind:completion.

Honeycomb

import { createHoneycombCostEmitter } from "@pleach/gateway/cost"

const emitter = createHoneycombCostEmitter({
  apiKey: process.env.HONEYCOMB_API_KEY!,
  dataset: "pleach-gateway",
  apiHost: "api.honeycomb.io",
  flushIntervalMs: 5_000,
  batchSize: 50,
})

POSTs to https://<apiHost>/1/batch/<dataset> with global fetch. EU customers may use api.eu1.honeycomb.io.

Each CostEvent becomes one Honeycomb event with flat fields (tenant_id, family, call_class, model_invoked, cost_usd, prompt_tokens, completion_tokens, tokens_total, byok_active, byok_key_hash, event_type). The full routingDecision is in routing_decision_json.

Production-readiness notes

The three buffered adapters (Postgres, Datadog, Honeycomb) behave the same way:

  • Clean exit. Their flush timers don't keep the process alive, so a CLI or short-lived worker exits normally.
  • Failed flushes retry in order. A failed batch (HTTP 5xx, pool exhausted, network reset) is retried ahead of newer events, and onError fires on every failure.
  • Bounded shutdown drain. flush() retries a bounded number of times, so a destination that keeps failing can't block shutdown. flush() stops after 1000 drain passes, so if you may hold more than 1000 × batchSize events at shutdown, log and force-exit.
  • emit() never throws. Cost emission is fire-and-forget and can't fail a gateway call.

Enforcing a per-root-turn cost ceiling

To cap swarm spend, compose RootTurnCostAggregator with CostCeilingMiddleware from @pleach/gateway/swarm at your gateway integration seam. The aggregator rolls sub-agent cost events up under the originating rootTurnId, so the ceiling applies to the user-visible turn, not one sub-agent's slice. The middleware checks before and after each call, warns once per rootTurnId at a soft threshold (only when you set warnCostUsdPerRootTurn or warnThreshold), and throws CostCeilingExceededError on a hard breach.

An unknown cost fails closed. A guarded call whose CostEvent has a missing, non-finite or negative costUsd, or costIncomplete: true, throws CostCeilingExceededError with reason: "unpriced", and onBreach fires with severity breach. That root turn is then marked costIncomplete: true, so its total reads as a floor, and later guarded calls are refused before invocation (when the aggregator implements isIncomplete). The built-in aggregator keeps this flag in process memory, so calls already past the pre-call check, or running on another instance, fail closed only after they return.

Cached prompt tokens count at the full input rate. The ceiling prices cached prompt tokens at the full input rate, so an unverified cache discount never lets a run pass a limit it crossed. It's an estimate, not an upper bound: cache-write tokens, which some providers bill above the input rate, aren't added by the ceiling. The audit side doesn't inherit the estimate: from v42 a per-call row prices cache writes at the rate source's cache-write rate, and from v44 at the rate for each write's lifetime; it stays unpriced only when there is no rate for a lifetime it wrote. See Observe → unknown cost and Auditable call row → Cache writes.

Public surface

  • CostEmitter contract and CostMiddleware factory, from @pleach/gateway/cost.
  • Adapters: @pleach/gateway/cost/adapters/otel, .../postgres, .../datadog, .../honeycomb.

Where to go next