Delivered remotely for a business based in San Francisco, United States. Names withheld by agreement.
Project Overview
Usage-based and hybrid pricing models—combining base platform commitments with metered API calls, compute-seconds, active seats, and egress volume—have become standard across B2B SaaS infrastructure. Yet many engineering teams bolt metering onto existing relational databases using nightly batch scripts or fragile webhook glue. Under real customer load, those stopgaps fracture: retries double-count billable events, late-arriving worker logs disappear from closed invoices, and finance teams lose days reconciling billing discrepancies before month-end close.
We designed and delivered a Web and API metering, rating, and billing engine built on Go, Apache Kafka, PostgreSQL, and the Stripe API. Serving both internal FinOps teams and customer-facing usage portals, the platform captures high-velocity product telemetry, evaluates complex enterprise rate cards deterministically, manages prepaid credit burndowns, and orchestrates finalized invoices through Stripe without losing a single cent of auditability.
Revenue & Metering Bottlenecks
Scaling hybrid SaaS monetization surfaced four recurring engineering failure modes that ad-hoc billing scripts could not solve:
- Duplicate and dropped event accounting: Microservices retrying timed-out HTTP requests or recovering from pod restarts routinely emit duplicate usage payloads, inflating customer bills unless strict idempotency spans ingestion and aggregation.
- Rigid pricing logic coupled to application code: Hardcoding tier thresholds, promotional credits, or custom enterprise overrides inside billing cron jobs forces engineering deploys whenever sales closes a bespoke annual contract.
- Clock skew and late-arriving telemetry: Batch jobs and regional edge workers frequently report usage minutes after an hour boundary closes, causing silent under-billing if aggregation windows finalize prematurely.
- Opaque ledger drift against payment processors: Pushing unverified totals straight to a payment provider leaves finance teams unable to trace an invoice line item back to the exact underlying API calls or compute runs.
Architectural Strategy
The core design principle was separating high-throughput event capture from immutable financial rating. Go ingestion endpoints and Kafka absorb bursty product telemetry at low latency without locking transactional billing tables. Downstream, deterministic Go rating workers aggregate events across tumbling time windows, apply versioned pricing rules stored in PostgreSQL, and record every debit, credit drawdown, and adjustment in an append-only double-entry ledger before touching the Stripe API.
This architecture treats Stripe as the system of execution for invoicing, tax calculation, PDF delivery, and card/ACH collection—while PostgreSQL serves as the auditable source of truth for metered quantities, custom contract overrides, and real-time entitlement balances.
Core Capabilities
- Idempotent Multi-Dimensional Metering: Go collectors ingest counter, gauge-max, and unique-entity events with arbitrary metadata dimensions (region, model tier, workspace) while enforcing strict key deduplication.
- Versioned Rate Cards & Hybrid Subscriptions: Supports flat recurring fees, graduated and volume tiers, package blocks, minimum spends, and mid-month proration without code changes.
- Prepaid Credit & Drawdown Ledger: Tracks multi-grant credit wallets with expiration dates, consumption priority rules, and automatic overage rollover onto metered invoices.
- Real-Time Spend & Quota Guardrails: Streaming Go evaluators monitor rolling tenant spend against customer-configured budgets, firing webhooks and email alerts before surprise overages accumulate.
- Self-Serve FinOps & Customer Portals: A React interface gives finance operators pricing sandboxes and invoice lineage drill-downs while giving end customers transparent daily usage breakdowns.
Technical Architecture
Product services emit signed usage events to stateless Go ingestion gateways, which validate schemas, check Redis fast-path deduplication filters, and publish payloads partitioned by tenant_id into Apache Kafka. Partitioned Go stream aggregators roll events into minute and hourly buckets in PostgreSQL, where rating workers apply active contract snapshots and write immutable rated ledger entries.
Flow: SaaS Product Services → Go Ingestion Collector (Redis Deduplication) → Apache Kafka (Tenant-Partitioned Topics) → Go Aggregation & Rating Workers → PostgreSQL Financial Ledger → Stripe API Sync & Webhook Reconciler → React FinOps & Billing Console
At billing cycle boundaries, a deterministic cycle-close worker waits for a configurable grace window, locks the period's rated line items inside a PostgreSQL transaction, and dispatches idempotent invoice items or meter summaries to the Stripe API. Inbound Stripe webhooks flow back through a verified Go endpoint to reconcile payment settlement, dunning states, and credit notes.
Technology Stack
| Category | Technology detail |
|---|---|
| Ingestion & Rating Services | Go microservices with gRPC/HTTP collectors and Kafka consumer groups |
| Durable Event Backbone | Apache Kafka partitioned by tenant and meter key for ordered replay |
| Financial & Entitlement Ledger | PostgreSQL with serializable double-entry credit and rating tables |
| Payment & Invoice Gateway | Stripe API (Subscriptions, Invoice Items, PaymentIntents, Webhooks) |
| Idempotency & Rate Cache | Redis bloom/TTL deduplication filters and hot entitlement caches |
| FinOps & Pricing Console | React SPA for plan modeling, live usage graphs, and credit adjustments |
| Contract & Schema Safety | TypeScript UI contracts and Protobuf/JSON event schemas |
| Threshold & Quota Alerts | Go stream evaluator triggering webhook and spend-limit notifications |
| Audit & Reconciliation Jobs | Go deterministic cycle-close workers verifying Stripe vs ledger parity |
Engineering Trade-offs & Solutions
| Engineering Challenge | Solution & Trade-off |
|---|---|
| Storing every raw API event forever in PostgreSQL bloats transactional tables | Kept Kafka retention and cold object archives for raw event replay while persisting compacted time-windowed aggregates and deduplication digests in PostgreSQL; preserves full auditability without starving B-tree indexes. |
| Pushing live single-event updates to Stripe API hits rate limits during traffic spikes | Aggregated and rated usage locally in Go and PostgreSQL, dispatching batched cycle summaries and high-water updates to Stripe; introduces a short UI-to-Stripe sync lag in exchange for resilient throughput. |
| Mid-cycle contract upgrades create ambiguous rating boundaries | Modeled customer subscriptions as immutable, time-bounded version slices (effective_from, effective_to); requires explicit slice splitting on plan changes but eliminates ambiguous retroactive recalculations. |
| Prepaid wallet race conditions could allow negative balances under parallel load | Placed authoritative balance checks inside PostgreSQL transactional ledger locks while serving fast-path soft quota hints from Redis; prioritizes financial accuracy over zero-coordination credit writes. |
Security & Reliability
Financial infrastructure requires deterministic failure recovery. Every usage ingestion endpoint enforces HMAC or mTLS service authentication, preventing spoofed consumption or quota-exhaustion attacks. Within Kafka and Go workers, poison-pill payloads are isolated to dead-letter topics with alerting rather than halting partition progress for neighboring tenants.
All Stripe API calls embed deterministic idempotency keys derived from PostgreSQL billing-period and ledger-entry IDs, guaranteeing safe retries across network timeouts. Webhook handlers verify Stripe-Signature headers, reject stale timestamps, and process events idempotently so duplicate Stripe deliveries never trigger double credit grants or premature subscription cancellations. Role-based permissions in the React FinOps console strictly separate read-only support analysts from finance administrators authorized to issue manual ledger credits.
Performance & Scale
By partitioning Kafka topics on tenant_id and running stateless Go consumer groups, horizontal scaling tracks ingestion volume linearly without cross-node lock contention. Go workers batch micro-aggregations in memory across short flush windows before executing bulk upserts into PostgreSQL, keeping database CPU flat even during noisy-neighbor traffic surges.
PostgreSQL rating tables partition monthly by billing window so active cycle queries scan compact hot partitions while historical invoice audits remain online and indexed. Meanwhile, the React billing portal queries pre-aggregated daily rollups via cached endpoints, rendering multi-month spend breakdowns and tier utilization charts smoothly.
Operational Outcomes
Replacing fragmented billing scripts with a unified Go, Kafka, PostgreSQL, and Stripe API engine transformed monetization agility and financial confidence:
- Faster pricing iteration: Product and revenue teams launch new usage dimensions, tiered bundles, and promotional credit campaigns through configuration rather than multi-sprint backend rewrites.
- Elimination of month-end billing surprises: Continuous rating and automated reconciliation catch meter anomalies and ledger mismatches immediately instead of during invoice freeze windows.
- Transparent customer spend visibility: Account owners track real-time consumption, credit balances, and projected cycle charges inside the portal, dramatically reducing support tickets over invoice line items.
- Reproducible audit lineage: Finance teams trace every dollar billed in Stripe directly back through versioned rate cards and Kafka aggregation checkpoints.