Skip to content
FluxMeter
中文

Writing

Cost spike, margin loss, forecast: three heuristic signals and how they are computed

How FluxMeter's cost-spike, margin-loss and forecast signals are computed, and where they miss. Heuristics, not a billing suite; no zero-overspend guarantee.

2026-11-29 · Intelligence · 12 min read

You already meter LLM usage per customer. FluxMeter's intelligence module adds three alerts on top of those numbers: `INTEL_COST_SPIKE`, `INTEL_MARGIN_LOSS` and `INTEL_FORECAST_RISK`. Before you route them to a pager or a Slack channel, it is worth knowing exactly what each one computes, what it reads, and when it stays silent. They are heuristic signals: fixed thresholds and arithmetic over Redis rollups, not a model and not a second source of truth.

FluxMeter is open-source, self-hosted LLM token metering software: it attributes token usage to your customers, prices it from a catalog, and optionally checks or reserves budget before a request. It is not a billing suite, it does not replace Stripe, Lago, Orb or Metronome (it can export usage to Stripe, Metronome and Orb), and it does not guarantee zero overspend. Everything below is read from the fluxmeter repository at commit `bc2ace3` and checked by running its intelligence tests and calling the detectors against a local Redis with seeded rollups. All figures in this post are from those local seeded runs, not from production data.

What the signals read

The project's own glossary (`CONTEXT.md`) defines Intelligence as read-side analytics over Redis rollups, not a second billing engine. The detectors in `api/intelligence/` do not see raw events. They read the per-customer monthly and daily cost buckets that Flink has already priced and written to Redis (`rollup:{customer}:period:{YYYY-MM}`, `rollup:{customer}:d:{YYYY-MM-DD}`, plus model and dimension buckets). How a usage event becomes one of those rollups is the subject of the gateway-to-usage-ledger walkthrough; here we start where it ends.

Flowchart of Redis rollups and a revenue overlay feeding three detectors (cost spike, margin loss, forecast risk) via an alert worker every 300 seconds, then a 24-hour debounce key, then a signed webhook.

Plain-text version: `Redis rollups (+ revenue overlay) → alert worker every 300 s → three detectors (cost spike, margin loss, forecast risk) → debounce key per type and month (24 h) → your webhook`. Nothing in this path writes back to usage, budgets or requests.

1. Cost spike: month-to-date against the whole previous month

`detect_cost_spike` calls the root-cause analysis with `scope="global"` and `baseline_period` set to the previous calendar month. It sums customer monthly costs for both months and computes `delta_pct = (current − baseline) / baseline × 100`. It returns an alert only if the baseline is above zero and `delta_pct` is strictly greater than `COST_SPIKE_PCT`, which is read from `INTEL_COST_SPIKE_PCT` and defaults to 25.

In a local seeded run (one customer, October against September):

Seeded monthly costResult
100 → 125 (+25.0%)no alert (threshold is strict)
100 → 130 (+30.0%)`Cost +30.0% vs 2026-09. Top driver: customer cust_a (100% of change).`
100 → 60 (−40.0%)no alert (only increases count)
0 → 500no alert (no baseline)

What that means in practice:

- The current month is partial. The worker always evaluates the current UTC month, so it compares month-to-date cost with the full previous month. At an unchanged daily rate, month-to-date cost only reaches roughly last month's total by month end, so the alert fires only after this month's running total has already passed 125% of last month's whole total. It is a late signal, not an early one.

- It is global. One customer whose cost jumps many times over can stay below the threshold if the overall total moves less than 25%. Per-customer root cause is available through `GET /intelligence/root-cause?scope=customer:{id}`, but the alert does not use it.

- A first month of usage never fires, because the baseline is zero.

- "Top driver" mixes dimensions. Contributors from models, customers and attribution dimensions are ranked together by absolute dollar change, and each share is computed against the customer total. In a seeded run where the total went 100 → 160 and one customer moved part of its traffic to a new model, the summary read `Cost +60.0% vs 2026-09. Top driver: model model-large (150% of change).` A share above 100% is arithmetically correct here (another model fell by 30), but it is a hint about where to look, not an allocation.

2. Newly unprofitable customers: only as good as the revenue you supply

FluxMeter meters cost; it does not know what you charge. `detect_margin_loss` needs a separate revenue figure per customer and month, which you supply through the admin endpoint `POST /intelligence/revenue/{customer_id}` or `POST /intelligence/import/openmeter`. For each customer with a monthly cost rollup, it computes `margin = revenue − cost`. A customer is `loss` if the margin is negative. A customer with no revenue entry is `unknown_revenue`, which is never treated as a loss.

The alert does not report every unprofitable customer. It reports the ones that are new since the previous run: it keeps a snapshot of the loss set in `intel:snapshot:loss_customers:{period}` and alerts on the difference. Seeded run, October:

StepResult
Three customers with costs, no revenue enteredno alert; all three `unknown_revenue`
Revenue added: cust_a 500 (cost 620), cust_c 100 (cost 80)`1 new unprofitable customer(s): cust_a`
Run again, nothing changedno alert
cust_c cost rises to 130`1 new unprofitable customer(s): cust_c`

Where it misses or misleads:

- No revenue, no signal. Without an overlay this detector says nothing, and silence does not mean healthy margins.

- "Cost" is metered token cost from your pricing catalog. Infrastructure, support and anything outside the rollups are not in it, and the revenue figure is whatever you posted; FluxMeter does not check it against your billing system.

- The snapshot is written on every run, before delivery. In a local run of the real worker against a webhook receiver that returned HTTP 400, the margin-loss alert was attempted once and then not again, because the customer was already in the snapshot. The cost-spike alert, which has no snapshot, was retried on every tick.

- Attribution is per `customerId`, so the signal is only as meaningful as your customer mapping (customers, not API keys).

3. Forecast risk: a straight line to the end of the month

`compute_forecast` takes the daily cost rollups for the month and extrapolates linearly:

days_elapsed  = max(days with data, current UTC day of month, 1)
avg_daily     = month_to_date / days_elapsed
forecast_eom  = month_to_date + avg_daily × (days_in_month − days_elapsed)

It then compares the forecast with a budget: `over_budget` above 100%, `at_risk` above 85%, `on_track` otherwise, and `no_budget` when no budget is found. For a customer scope, the budget is that customer's `initial_balance_usd` from the check/reserve budget keys (how check and reserve work). That is a configured balance, not necessarily a monthly budget, so read the comparison with that in mind.

Seeded run on 2026-11-29 (UTC day 29 of 30), one customer at $10 per day:

`initial_balance_usd`Result
none`MTD $290.00; forecast EOM $300.00 (no budget configured)`
400`Forecast EOM $300.00 on track vs budget $400.00`
330`Forecast EOM $300.00 is at risk vs budget $330.00`
250`Forecast EOM $300.00 exceeds budget $250.00 by $50.00`

The alert itself does not fire at this commit. `detect_forecast_risk`, which the worker calls, uses `scope="global"`, and the global scope has no budget source, so its status is always `no_budget`. In all four seeded cases above, including the `over_budget` one, `detect_forecast_risk` returned nothing. The per-customer forecast is available on demand via `GET /intelligence/forecast?period=YYYY-MM&scope=customer:{id}`; if you want it as an alert today, you would poll that endpoint yourself.

Even where it does compute, a straight line has known blind spots:

- Step changes. In a seeded run with $10 per day for 28 days and $100 on day 29, the forecast was `$393.10`, `at_risk` against 400. If the new rate held for the last day the month would reach 480 (our arithmetic: 380 + 100). An average absorbs a launch-day jump slowly, and it cannot see one that has not happened yet.

- Weekly shape. Weekday-heavy or weekend-heavy traffic is flattened into one average, so the forecast drifts depending on which weekday the month started.

- Partial days. `days_elapsed` counts today as a full day, so early in a UTC day the average is understated.

- UTC months. Periods are UTC calendar months. For a team in UTC+8, the month boundary falls at 08:00 local time on the 1st.

- Past months have no remaining days, so the "forecast" equals the month-to-date total.

How alerts reach you

`intel_alert_worker.py` is a loop inside the API process. Every `INTEL_ALERT_INTERVAL_SEC` seconds (default 300) it reads the webhook URL (`FLUXMETER_INTEL_WEBHOOK_URL` or the Redis key set by `POST /intelligence/alerts/webhook`), runs the three detectors for the current UTC month, and posts each result as JSON. If a secret is set, the body is signed with HMAC-SHA256 in `X-FluxMeter-Signature`.

A few details that matter for operations:

- The loop is started at API startup only if a webhook URL already exists (`api/main.py`). Configuring the URL through the admin endpoint on a process that started without one does not start the loop until the API restarts.

- Debounce is 24 hours, not once per month. After a successful delivery the worker sets `intel:alert:{type}:{YYYY-MM}:sent` with a TTL of 86,400 seconds. While a cost spike persists, expect one alert per day for the rest of the month. In our local run with a one-second interval, about five seconds of ticks produced exactly two deliveries (one cost spike, one margin loss), both with valid signatures.

- Failures. A 4xx response counts as failed with no retry inside the tick; a 5xx or network error is retried up to `WEBHOOK_MAX_RETRIES` (3) times. Nothing is marked sent until delivery succeeds, which is why the cost spike repeats while the margin-loss alert, as noted above, does not.

What these signals are not

- Not billing truth. The record of what a customer used stays in the metered, attributed usage lines (`GET /usage/customer/{id}`) and in your external billing system. Intelligence reads a derived view of those rollups; ClickHouse, where enabled, is an audit cold store, not a source for these numbers either. As with ingestion, where HTTP 202 means custody rather than settlement, an alert here means "look at this", not "this is final".

- Not ML anomaly detection. There is no model, no seasonality and no learned baseline: one percentage threshold, one sign check on margin, and one straight line.

- Not enforcement. None of the three detectors blocks, delays or changes a request. Pre-request checks and reservations are a separate mechanism, and they reduce overspend risk without removing it.

- The module also exposes a pricing recommendations endpoint; it applies similar fixed rules to the same rollups and revenue overlay, and we treat it the same way.

Using them sensibly

- Treat each alert as a pointer to the usage lines and the root-cause breakdown, then confirm against the metered data and your billing system before acting.

- Tune `INTEL_COST_SPIKE_PCT` to your traffic; 25% of a small month is noise, 25% of a large one may be late.

- If margin matters to you, feed revenue every month, and keep your webhook receiver returning 2xx so margin-loss alerts are not consumed by a failed delivery.

- For budget risk today, poll the per-customer forecast endpoint rather than waiting for `INTEL_FORECAST_RISK`.

Where FluxMeter fits

FluxMeter's job is the metered, attributed, priced usage line per customer, with optional pre-request checks. The intelligence signals sit beside that as auxiliary hints: useful for noticing a change sooner than a month-end review, not a replacement for reading the numbers. To see where the rollups come from, start with the architecture overview or the quickstart.

Reproduce it

git clone https://github.com/10kshuaizhang/fluxmeter && cd fluxmeter
pip install -r tests/requirements.txt -r api/requirements.txt
python -m pytest tests/test_intelligence_*.py -v

The detectors are plain functions in `api/intelligence/alerts.py` that take a Redis client, so you can call them against a local Redis with a few seeded rollup hashes, which is how the examples above were produced.

FluxMeter's job is the metered, attributed, priced usage line per customer, with optional pre-request checks. The intelligence signals sit beside that as auxiliary hints: useful for noticing a change sooner than a month-end review, not a replacement for reading the numbers.