GebSecure Docs v0.1.0

Architecture · All ADRs

ADR 0014 — Usage metering and billing: durable rollups, Redis quota gate, owner-only billing state

Architecture decision record — status: Accepted.

Status: Accepted

Context#

EPIC 34 needs per-organization metering for nine meters (authorization decisions, executions, MCP tool calls, active agents, secret accesses, stored secrets, browser minutes, database queries, security scans), plans with quotas, overage billing, invoices, subscriptions with proration, Stripe payments, billing alerts and enterprise contracts. Two constraints shape the design:

  1. The decision hot path (ADR 0007) cannot gain a database write or a second Redis round trip per call.
  2. Hard limits must not be bypassable by tenant users — not through the API, and not even if a request path running as the runtime database role (gebsecure_app) were abused.

Decision#

Metering is derived, not double-written. Most meters are counted from durable records the platform already writes: the audit trail (authz.decision, successful secret.use), executions (succeeded/failed), mcp_calls (forwarded tools/call) and secrets (hourly gauge snapshot; the period value is the peak). Meters for modules built in parallel (browser minutes, database queries) and security scans are recorded explicitly with billing.recordUsage(s, tx, orgId, { meter, quantity, idempotencyKey }) into usage_events (unique per (org, meter, idempotency_key); retries are free). New modules can registerMeter().

Aggregation is a worker loop that recomputes usage_hourly(org, meter, hour) over a trailing three-hour window with INSERT … ON CONFLICT DO UPDATE SET quantity = GREATEST(old, new). Recomputing is idempotent, late audit chaining is covered by the lookback, and a later retention purge can never shrink measured usage. Closing a period re-rolls the whole period for that org before rating. Active agents are distinct agent ids with at least one decision in the period.

Quota enforcement is a Redis gate: one EVAL atomically checks the hard limit and increments the period counter (gs:u:{org}:<periodStart>:<meter>), tracks distinct active agents (SADD), applies any staff abuse throttle and returns the org's entitlement version stamp. Entitlements (plan, contract, throttle, kill-switch flag) are cached in-process for 30 s and invalidated by the stamp. Meters without a hard limit skip Redis entirely (enterprise is uncapped by default). Callers inside a tenant transaction pass it, so an entitlement cache miss never checks out a second pool connection. Gate points: authorize() (including dry runs, which are not billed), execute(), MCP tools/call, useSecret(), explicit inspections, simulations (per scenario), stored-secret creation (counted in-transaction), and any recordUsage() caller. Counters are conservative (attempts admitted by the gate); the worker raises any counter that is below durable usage, so a Redis flush cannot reset consumption. If Redis is down the gate fails open (logged) — the control plane stays available; durable metering and invoicing are unaffected. Responses: 429 quota_exceeded with Retry-After and x-quota-{meter,limit,used,reset}; 402 payment_required when a subscription is past due beyond the grace period (limits fall back to Free); 429 rate_limited / 403 for staff throttles and blocks.

Billing state is owner-written. RLS lets tenants read their subscription, contract, usage, invoices and alerts. Guard triggers (gs_is_table_owner) reject writes from any non-owner role to usage_hourly, billing_contracts, invoices/invoice_lines, billing_alert_firings, and restrict the runtime role on billing_subscriptions to the self-service transitions the product offers (create Free; upgrade among Free/Team/Business; schedule downgrade/cancel). Status, periods, tax rates and Enterprise are owner-only. Finalized invoices are immutable and follow draft → open → paid | void | uncollectible for every role.

Money is integer: cents on invoices, micro-dollars for unit prices, one rounding (half away from zero) per invoice line, tax computed once on the subtotal. Proration credits unused time on the old base fee and charges the remainder on the new one, both by seconds; downgrades and cancellations take effect at period end. Enterprise contracts layer custom inclusions, unit prices, hard limits, committed spend (true-up line), payment terms, PO numbers and manual invoicing over the enterprise defaults.

Stripe is used through its REST API (customers, SetupIntents confirmed by Stripe.js, payment methods, off-session PaymentIntents with per-attempt idempotency keys). Webhooks are verified (Stripe-Signature, 5-minute tolerance) and stored by event id by the tenant API — which may insert but never read stripe_events — and applied by the worker; objects must belong to the org's own Stripe customer. PDF invoices are produced by an in-repo PDF 1.4 writer (no external rendering service).

Consequences#

  • The authorization hot path gains at most one Redis EVAL (none for uncapped meters) and no database work on cache hits.
  • Billable usage lags real time by up to a minute (worker cadence); quota counters are immediate.
  • Quota counters may exceed billable usage (dry runs, rolled-back work); this errs toward the customer's limit, never toward unbilled usage.
  • Self-hosted deployments that do not bill set BILLING_ENFORCE_QUOTAS=false; abuse throttles still apply.
  • Live Stripe verification requires real keys and is outside the automated suite (tests use a local Stripe stand-in that speaks the same wire format).