Lago

Open-source metering, billing, and revenue infrastructure for product-led companies that need complete control over their pricing stack.

10.2Kstars
687forks
GNU AGPLv3
Go

Lago is an open-source billing and metering platform purpose-built for SaaS, AI, and infrastructure companies that need to move beyond rigid, opaque billing systems. It provides a unified API and visual interface for tracking usage events, calculating charges, generating invoices, and orchestrating payments — all without locking you into a proprietary vendor like Stripe Billing or Chargebee.

At its core, Lago supports fully hybrid pricing: fixed subscriptions, usage-based charges, prepaid credit wallets, add-ons, and coupons can all coexist within a single billing plan. The platform is trusted in production by companies like PayPal, Mistral AI, Groq, Synthesia, and Laravel, handling everything from AI token billing to IoT SIM card metering at massive scale.

Architecturally, Lago is a polyglot system — a Ruby on Rails API with Sidekiq workers for background processing, a Go-based events-processor service for high-throughput event ingestion, a React frontend, and ClickHouse for analytics. Everything is deployed via Docker Compose with optional Kafka/Redpanda integration for streaming-scale event pipelines. Self-hosters get the full platform with no feature gating on the open-source tier.

Lago is AGPLv3-licensed and backed by Y Combinator. It is SOC 2 Type II certified and offers both a self-hosted option and a managed Lago Cloud for teams that want billing infrastructure without the operational overhead.

What You Get

  • Usage metering engine - Ingests real-time usage events via REST API or Kafka/SQS streams, aggregating them per billable metric (sum, count, max, unique count) with support for time-windowed calculations and grouped dimensions.
  • Hybrid pricing plans - Combine subscription fees with usage-based charges, graduated tiers, volume pricing, and package-based models in a single plan — configurable through the API or UI without code changes.
  • Automated invoicing - Generates PDF invoices on billing cycle completion with multi-currency support, tax calculations, line-item breakdowns, and configurable SMTP delivery — all without manual intervention.
  • Prepaid credit wallets - Create customer wallet balances for pay-as-you-go flows, with configurable top-up rules, expiration dates, and real-time balance deductions as usage events are processed.
  • Payment orchestration - Integrates with Stripe, Adyen, GoCardless, and other gateways for dunning, retry logic, and multi-gateway routing, with dedicated Sidekiq worker queues for payment job isolation.
  • Revenue analytics - Tracks MRR, usage trends, and revenue drivers across all billing streams through a built-in analytics layer backed by ClickHouse, accessible via the dashboard and API.
  • Entitlements management - Ties feature access directly to billing plan configuration, enabling product-led growth flows where feature gates automatically reflect a customer’s active subscription.
  • Integrations hub - Native connectors for NetSuite, Xero, Salesforce, HubSpot, Avalara tax engine, and AWS/Azure/GCP Marketplace for end-to-end finance and CRM automation.

Common Use Cases

  • AI API token billing - A company like Mistral AI ingests per-request token counts as usage events and bills customers based on model and token volume, combining subscription tiers with overage charges in a single Lago plan.
  • IoT SIM card metering - A telecom provider like 1NCE uses Lago to meter data consumption per SIM card globally, applying region-specific pricing rules and generating per-device invoices automatically each billing cycle.
  • SaaS seat-plus-usage billing - A B2B SaaS platform charges a fixed monthly seat fee alongside variable usage charges for API calls or storage, with Lago unifying both into one invoice and one payment collection flow.
  • Embedded billing for platforms - A marketplace or multi-tenant platform uses Lago Embedded to offer white-label billing to its own customers, with each tenant getting isolated billing configuration and invoicing through Lago’s API.
  • Cloud infrastructure pricing - A cloud provider implements graduated tiered pricing for compute hours and storage gigabytes, using Lago’s billable metric aggregations and charge models to replicate AWS-style pricing behavior.
  • Prepaid credit top-up flows - A developer tools company sells usage credits upfront that customers spend down as they make API calls, with Lago managing wallet balances, deduction logic, and low-balance threshold alerts.

Under The Hood

Architecture Lago is a modular, service-oriented system composed of distinct runtime boundaries that communicate through well-defined interfaces. The Rails API acts as the command hub — it receives HTTP requests, enqueues Sidekiq background jobs, and delegates heavy workloads to specialized workers across queues (billing, events, webhooks, PDFs, payments, analytics) that can be individually enabled and scaled via environment flags. A separate Go-based events-processor service handles high-throughput event ingestion and enrichment through Kafka or Redpanda, using BadgerDB as an in-memory cache populated via Debezium CDC snapshots to avoid database pressure during hot paths. A dedicated clock process runs Clockwork-scheduled recurring jobs independently of the main API. Three separate Redis instances are used for Sidekiq queue storage, Rails application caching, and event processing state — with credentials injected separately from URIs to follow the principle of separating configuration from secrets.

Tech Stack The backend is split between a Ruby on Rails application for billing logic, invoice generation, and API endpoints, and a Go service for event processing that uses franz-go for Kafka consumption, pgx for PostgreSQL access, and BadgerDB for in-memory caching. PostgreSQL 15 with the pg_partman extension handles billing data at scale with table partitioning for high-volume tables. ClickHouse provides analytics storage for usage data aggregation and revenue reporting. Redis 7 serves three distinct roles: Sidekiq job queues, Rails cache, and event processing state. Traefik v3 handles TLS termination and routing for API, frontend, and webhook endpoints. The frontend is a React application served via Nginx. PDF generation is handled by a repackaged Gotenberg instance. OpenTelemetry with Datadog tracing and Sentry for error capture provide observability across all services.

Code Quality The Go events-processor demonstrates strong engineering discipline throughout: a generic Result[T] type enforces explicit success/failure handling without panics, table-driven tests with go-sqlmock cover database interactions under diverse conditions, and structured JSON logging via slog with custom handlers ensures consistent observability. The cache layer uses BadgerDB with parallel snapshot loading via errgroup for concurrent initialization, and all Redis passwords are injected separately from connection URIs for clean secret management. Comprehensive test coverage spans cache hydration, event enrichment, Kafka consumer behavior, and subscription flagging logic. The codebase uses descriptive, domain-aligned naming that maps directly to billing concepts (BillableMetric, EnrichedEvent, FlagStore, ChargeCache), reducing cognitive load for new contributors.

What Makes It Unique Lago’s primary technical differentiator is its separation of the billing engine into independently scalable components — the Go events-processor can handle extremely high event ingestion rates without impacting the Rails API or Sidekiq workers, which is critical for AI and IoT customers sending millions of events. The in-memory cache populated via Debezium CDC enables the events-processor to resolve subscriptions, billable metrics, and charge filters without hitting the primary database on each event, dramatically reducing database load at ingestion time. The support for LAGO_LICENSE-gated enterprise features, dual-algorithm webhook signing (HMAC and JWT/RSA simultaneously), three isolated Redis topologies, and a purpose-built Kafka connector layer for SQS/Kinesis/HTTP ingestion give Lago a production-grade operational surface that most open-source billing tools lack entirely.

Self-Hosting

Lago is distributed under the GNU Affero General Public License v3.0 (AGPLv3). This is a strong copyleft license with a network use clause: if you run a modified version of Lago as a service accessible to others over a network, you are required to make your modifications available under the same AGPLv3 terms. For companies running Lago purely for internal billing infrastructure — serving their own customers but not distributing the software itself — the practical implication is that any modifications to the Lago codebase must be released publicly if Lago is offered as a service. Most self-hosters using Lago to bill their own end customers fall outside the distribution clause, but legal review is recommended for any commercial embedding or SaaS offering built on top of Lago. A paid Lago Cloud option is available under a commercial arrangement for teams that need a different licensing posture.

Running Lago self-hosted requires a reasonably capable infrastructure team. The minimal production setup involves PostgreSQL 15 (with partman extension), Redis 7 (ideally three separate instances for queues, cache, and event processing), the Rails API with a clock process, and the React frontend — all deployable via the provided Docker Compose files. At scale, you will want to enable dedicated Sidekiq workers for billing, webhooks, PDFs, and events separately, with each worker type scaled independently based on queue depth and latency. The Go events-processor with Kafka/Redpanda is an optional but recommended addition for high event volumes. You are responsible for database backups, PostgreSQL partitioning maintenance via pg_cron, Redis persistence, TLS certificate management through Traefik, and Sentry/Prometheus alerting integration. Lago publishes detailed resource configuration guidance, including production-scale CPU and memory baselines per service role.

Compared to Lago Cloud, self-hosted deployments forgo managed upgrades, automatic database migrations, SLA guarantees, and integrated support channels. The cloud offering additionally provides SOC 2 Type II compliance out of the box, multi-region deployment, and enterprise support tiers that include SLAs and dedicated customer success. The open-source codebase is complete — there is no feature gating on the self-hosted tier beyond what requires a LAGO_LICENSE key for undisclosed premium capabilities — making Lago one of the more generous open-source billing platforms available.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack

No spam. Unsubscribe anytime.

Join 750+ subscribers
No spam. Unsubscribe anytime.

Search