---
title: "How we made usage and credit balances real-time"
url: https://getlago.com/blog/how-we-made-usage-and-credit-balances-real-time
description: "The architecture, race conditions and benchmarks behind Lago’s sub-second wallet refresh and wallet alerts."
authors: ["Anh-Tho Chuong"]
tags: ["Engineering"]
published: 2026-11-27
reading_time_minutes: 6
---

# How we made usage and credit balances real-time

On August 6 we measured ourselves. We sent an event to Lago and timed how long the customer's credit balance took to move. The median was about 40 seconds.

Nothing was broken. The pipeline was correct and it scaled. It was built for invoices, and an invoice doesn't care about 40 seconds. A product that sells prepaid credits and burns them per token does, because the balance *is* what the customer is looking at.

We rebuilt that path for sub-second wallet refresh and wallet alerts.

This post explains the architecture behind it, the race conditions we had to fix, and the measurements from development and rollout.

### A chain of clocks

The old path: the API produces the event to Kafka, a Go processor enriches it, ClickHouse stores it. Usage was computed on read. Every request for current usage re-aggregated every charge and every charge filter over the whole billing period, behind a per-charge cache that any new event invalidated.

Wallets sat downstream of that. The processor flagged the subscription with a 10-second debounce. A job drained that queue every 10 seconds. The customer got flagged for refresh. A sweep picked up flagged customers on its own schedule.

Every source of latency was a clock, a cache or a recompute. We could have tuned each one. The wait would have moved to the next.

### Compute once, as events arrive

So we stopped recomputing. Each event now updates a running aggregate, and nobody re-scans raw events to answer "what's my usage right now".

The pieces. Kafka is unchanged. A streaming SQL engine, written in Rust, holds the enrichment state and the running aggregates as continuously updated materialized views. Billable metrics, subscriptions, charges and filters are replicated into it from Postgres by logical replication. The Lago-specific logic runs inside the engine as Rust compiled to WebAssembly. ClickHouse stays, now as the store for pre-aggregated usage. And the Rails API reads that usage, prices it, and owns wallets. The stream maintains a 32-day working set. History stays in ClickHouse.

![Lago event-to-wallet pipeline: Kafka feeds a Rust streaming engine, which writes usage buckets and refresh triggers; Rails prices usage and updates wallets.](https://getlago.com/blog/images/realtime-wallet-pipeline.webp)

One choice shaped everything else. The engine computes *quantities*. The API turns quantities into money, with the same charge-model code that produces invoices. It costs a little at read time. In exchange, real-time usage and the invoice can't disagree on pricing, because there is only one implementation of pricing.

### One event, four stages

**Deduplicate.** The engine keeps the first write for a given organization, metric code, subscription, timestamp and transaction ID, and holds that key for 32 days. Re-sends are dropped. Events in this path are immutable; corrections go out of band as voids, adjustments or credit notes.

**Expand.** Which charge does this event bill? The engine picks the subscription active at the event's timestamp, then fans out one row per charge that bills the metric. Then comes filter matching, which was the hard part.

Some charges have around 3,000 filters. Our first version handed each charge's full filter list to a function for every event. That's hundreds of kilobytes per event, and the stage saturated. More CPU didn't move it, and neither did more partitions. The version that works compiles filters into lookup keys whenever a plan changes, so each event finds its filter in one or two point lookups regardless of how many filters exist. Precedence follows the API's rule: most matching keys, then fewest allowed values, then oldest. We fuzzed it against the reference implementation on 50,000 randomized charges.

Plan and filter changes apply to new events. Events already expanded keep their original attribution.

Rewriting this stage as Rust functions took a 100,000-event burst from 21.3 seconds to drain to under 2.6, and the stage's state from 3.2 GB to about 10 KB.

**Bucket.** Events aggregate into 15-minute windows per subscription, charge, filter and grouping key. Why 15? Every real UTC offset is a multiple of 15 minutes, Nepal's +5:45 included. Any customer's day boundary lands on a bucket wall, so a billing period in any timezone is an exact sum of buckets. Late events land in their original bucket. There's no event-time watermark quietly dropping them.

**Serve.** Buckets upsert into ClickHouse. In one run, 3.3 million events became about 30,000 buckets. For a subscription with 2.6 million events a month, reading 30 days of usage went from 10,091 ms of CPU on raw events to 20.6 ms on buckets.

### From usage to a balance

Every expanded event also emits a trigger message, keyed by customer. One customer, one partition, so refreshes for the same customer never contend in Postgres.

A consumer reads triggers in batches and collapses each batch to one refresh per customer. In a production test, 18,000 events at 100 per second produced 168 refreshes.

Then it waits, and what it waits for is data. The bucket write and the trigger leave the engine together and can arrive in either order.

That gave us the most interesting bug of the project. When the trigger won, the consumer read the *previous* usage total, wrote a stale balance, and cleared the customer's pending-refresh flag. The safety-net sweep only selects on that flag. So the refresh reported success, the balance was wrong, and nothing was left to correct it.

Now each trigger carries an ingestion timestamp, and the consumer polls until a bucket at or past it exists:

```rb
def bucket_caught_up?(subscription_id, watermark_ms)
  Clickhouse::UsageBucket.uncached do
    Clickhouse::UsageBucket
      .unscoped
      .where(organization_id:, subscription_id:)
      .where("toUnixTimestamp64Milli(last_ingested_at) >= ?", watermark_ms.to_i)
      .exists?
  end
end
```

It polls every 100 ms for up to five seconds. On timeout it leaves the flag set and the sweep takes over, slower but correct. One assumption sits under this check: the engine writes each checkpoint's buckets to ClickHouse in a single insert, so one row at the watermark means the rest of that checkpoint is there too.

Three details cost us time. The watermark is ingestion time, because an event for work done at 9 a.m. can arrive at 2 p.m. and update a 9 a.m. bucket. The query bypasses the cache, otherwise the first miss gets served back for the whole wait. And a trigger already more than 30 seconds old gets one check, since that means the consumer is behind and sleeping on it wastes the batch.

A fixed sleep would have been three lines. It also would have slowed every refresh and still failed whenever ClickHouse took longer than the number we picked.

The refresh itself computes usage from buckets, allocates it across the customer's wallets in priority order, and writes the balance. From bucket landing to committed balance: 329 ms at the median.

### Why Rust

The API is Ruby and the old processor is Go. Both are good at their jobs. This layer does millions of small state updates per second over a month of keyed state, and a garbage collector shows up in the tail of that. Rust also lets the matching logic run in-process inside the engine, with no network hop per event.

Most of the gain over the old path is the architecture, though. Incremental aggregation is what made it fast. Rust made it hold at throughput.

### What we measured during development and rollout

These historical tests ran from August to October 2026. Every test used one clock, starting at the client's POST, so these end-to-end results include ingestion and processing before the wallet refresh.

| Test | Event to usage | Event to wallet |
| --- | --- | --- |
| Production, isolated events |   | 1.19 s p50, 1.72 s p99 (old path: 26.2 s) |
| Production, 100 events/s for 3 min |   | 1.37 s p50, 3.51 s p99 |
| Staging, 5,000 events/s | 284 ms p50, 536 ms p99 | 603 ms p50, 949 ms p99 |
| Staging, 20,000 events/s | 330 ms p50 | 826 ms p50 |
| Staging, 50,000 events/s for 9 min 38 s | 1,051 ms p50, 1,549 ms p95 | 1,427 ms p50, 2,515 ms p95 |

At 50,000 we ran four long runs, from about 2.5 to almost 10 minutes. Usage latency landed at 1,100, 955, 1,044 and 1,051 ms. It didn't grow with run length, which is what a pipeline that can't keep up would show.

Now the limits. The 50,000 figure is staging, for under ten minutes, with no row-count check at that rate. We're not claiming production runs there, and we're not claiming exactly-once at 50,000. The production samples are small. During a production backlog, two probes missed the fast path and were refreshed by the sweep, about 26 seconds later.

### How we tried to break it

We killed Postgres, Kafka and ClickHouse, one at a time. No data was lost in any of the three. With Postgres down, replication reconnected in 2 to 7 seconds and the pipeline never stopped. With Kafka down, offsets resumed within 6 seconds. With ClickHouse down, the pipeline paused, recovered about 3 seconds after it came back, and drained the backlog in under 10. Totals were exact to the decimal, including after a SIGKILL in the middle of an insert.

We also ran a week of production shadow, with real traffic and nothing served, comparing old and new on every charge. That found the bugs worth finding: max and latest computed wrong across bucket boundaries, a default-bucket error on charges that were both grouped and filtered, and an overflow above 1.7 × 10¹² units. Earlier, a ranking step in the stream had been producing about 0.4% duplicate rows under burst. We fixed that by taking ranking out of the stream entirely.

### Current coverage

The real-time path supports count, sum, max and latest for non-prorated, non-recurring charges billed in arrears, across both plan versions. It requires a premium license and is enabled behind a feature flag. Unique count, weighted sum, custom aggregations, pay-in-advance, prorated and recurring charges use the existing path. Usage-threshold alerts and progressive billing still run on a one-minute clock; moving their threshold detection into the stream is planned.

### What this changes for AI products

An AI product keeps paying for inference while its billing catches up. A stale balance can let more work through after a customer has used their credits, whether through ordinary use or [deliberate abuse](https://getlago.com/blog/token-fraud-happens-in-the-window-before-billing-catches-up).

Lago’s sub-second wallet refresh and wallet alerts shorten that window. Your application gets a current balance to [check before accepting more work](https://getlago.com/blog/how-can-a-prepaid-balance-go-negative), and threshold top-ups run from the same refresh. For teams offering prepaid usage or credit-based trials, that means less time making spending decisions against credits already consumed.
