Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 04 · 45 minutes

Watch rate and cost and alert on a spike

After this lesson you can
  • Count requests per user and per hour and compute the cost of each request from its tokens
  • Detect a spike with a median-based rule that one large value cannot hide
  • Report the cost per day against a budget, and split a bill into prompts, responses, processing and storage with prices you set
Lab files of this lesson (14)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The finance lead of Orbit Parcels sees that the bill for Orbi almost doubled in week 2, from 2.41 to 4.37 (invented prices, in USD). The limits from "Securing LLM applications" (lesson 8) were in place and nothing was blocked, so the finance lead asks: "Who spent it, when, and why did nobody tell us on the day?" A limit stops a request. It does not tell anyone. You build the watcher that raises the alarm, and the report that answers the three questions.

Recall

Lesson 3: why does the drift check skip a day with fewer than 100 answers?

A small sample makes the measure jump, so the check would raise a false alert. A spike detector has the same problem with a series of few points, and you will see how the median helps.

Lesson 1: which fields of the record give the cost of a request?

tokens_in and tokens_out, which make_record turns into cost with the price per million tokens. The lab prices are invented: 3 USD for a million input tokens and 15 USD for a million output tokens.

The idea

Three views of the same records catch three different things:

ViewQuestionRule
One user in one hourWho sends too much?More than 30 requests
All users in one working hourIs the whole service busier than normal?A spike against the baseline
All users in one dayDid we spend more than planned?A budget in USD

The spike rule needs a robust measure. The usual z-score uses the mean and the standard deviation. One huge value pulls both up, so it hides itself and the values next to it. The median (the middle value of a sorted list) does not move when one value is huge. The median absolute deviation (MAD) is the median of the distances of all values from the median. The robust z-score is 0.6745 × (value − median) ÷ MAD. The constant 0.6745 makes the MAD comparable to a standard deviation for data with a normal shape. The NIST Engineering Statistics Handbook, in its section on outliers, credits Iglewicz and Hoaglin with this score and recommends that values above 3.5 are looked at as possible outliers. You compare working hours (08:00 to 17:59, Monday to Friday) with working hours of the baseline week, so that night and weekend traffic do not spoil the median.

From records to a spike alert
RecordsCount per hourMedian and MADRobust z-scoreAlertworking hours onlyfrom the baseline weekhow far is this hourabove 3.5RecordsCount per hourMedian and MADRobust z-scoreAlert1234
  1. Records → Count per hour: working hours only
  2. Count per hour → Median and MAD: from the baseline week
  3. Median and MAD → Robust z-score: how far is this hour
  4. Robust z-score → Alert: above 3.5

Worked example

1. Work out the cost of a request

The cost is the input tokens times the input price plus the output tokens times the output price. Compare a normal request with a very long one from week 2.

python3 -c "
from logrec import load
rs = load('logs/week2.jsonl')
for r in (next(x for x in rs if x['prompt_len'] < 100), next(x for x in rs if x['prompt_len'] > 8000)):
    print(r['prompt_len'], 'chars:', r['tokens_in'], 'in,', r['tokens_out'], 'out, cost', r['cost'])
"
80 chars: 320 in, 2 out, cost 0.00099
12881 chars: 3520 in, 152 out, cost 0.01284

The long request costs about 13 times the normal one, and it only has a longer prompt.

2. Write the watcher

cost.py has the working-hours filter, the hourly counts, the robust z-score, the spike finder, the per-user limit and the daily cost. statistics.median gives the median. date.fromisoformat(...).weekday() gives 0 for Monday up to 6 for Sunday. sorted(..., key=...) sorts by the value that the key function returns.

cost.py

"""cost.py: request rates, cost, budgets and a spike detector built on the median."""
import statistics
from collections import Counter, defaultdict
from datetime import date

USER_HOUR_LIMIT = 30     # requests that one user may send in one hour
DAY_BUDGET = 1.00        # USD for the whole assistant in one day (an invented budget)
Z_LIMIT = 3.5            # a robust z-score above this is a spike


def work_hour(hour):
    """True for 08:00 to 17:59 on Monday to Friday. `hour` looks like 2026-10-12T09."""
    return date.fromisoformat(hour[:10]).weekday() < 5 and 8 <= int(hour[11:13]) <= 17


def hourly(records, field=None):
    """Requests per hour, or the sum of a field (for example cost) per hour, for the working hours."""
    out = defaultdict(float)
    for r in records:
        h = r["ts"][:13]
        if work_hour(h):
            out[h] += r[field] if field else 1
    return dict(out)


def robust_z(x, baseline):
    """How far x is from the median of the baseline, in units of the median absolute deviation."""
    mid = statistics.median(baseline)
    mad = statistics.median(abs(v - mid) for v in baseline)
    return 0.6745 * (x - mid) / mad


def spike_hours(baseline, new, field=None):
    """(hour, value, z) for each working hour of `new` that is a spike against `baseline`."""
    base = list(hourly(baseline, field).values())
    return [(h, round(v, 4), round(robust_z(v, base), 1)) for h, v in sorted(hourly(new, field).items())
            if robust_z(v, base) > Z_LIMIT]


def user_hour_alerts(records, limit=USER_HOUR_LIMIT):
    """(user, hour, requests) for each user that sent more than `limit` requests in one hour."""
    counts = Counter((r["user"], r["ts"][:13]) for r in records)
    return sorted((u, h, n) for (u, h), n in counts.items() if n > limit)


def daily_cost(records):
    days = defaultdict(float)
    for r in records:
        days[r["ts"][:10]] += r["cost"]
    return {d: round(c, 2) for d, c in sorted(days.items())}


def top_users(records, n=3):
    cost = defaultdict(float)
    for r in records:
        cost[r["user"]] += r["cost"]
    return [(u, round(c, 2)) for u, c in sorted(cost.items(), key=lambda kv: -kv[1])[:n]]

3. Learn what is normal

The baseline is week 1. Print the median and the MAD of its hourly request counts in working hours.

python3 -c "
import statistics, cost
from logrec import load
h = list(cost.hourly(load('logs/week1.jsonl')).values())
m = statistics.median(h)
print(len(h), 'hours, median', m, ', MAD', statistics.median(abs(v - m) for v in h))
"
50 hours, median 13.0 , MAD 2.0

A normal working hour has about 13 requests, and the typical distance from that is 2. An hour with 113 requests is 50 units of MAD away.

4. Run the report

run_cost.py prints the cost per day, the top users, the spikes and the user-hour alerts for week 2, and it checks that week 1 raises nothing.

run_cost.py

"""run_cost.py: the cost report and the alerts for week 2, with week 1 as the baseline."""
import cost
from logrec import load

week1, week2 = load("logs/week1.jsonl"), load("logs/week2.jsonl")
print("cost per day (USD), budget", cost.DAY_BUDGET)
for day, usd in cost.daily_cost(week2).items():
    print(f"  {day}  {usd:6.2f}  {'OVER BUDGET' if usd > cost.DAY_BUDGET else ''}")
print("week 2 total:", round(sum(r["cost"] for r in week2), 2), "week 1 total:", round(sum(r["cost"] for r in week1), 2))
print("top users by cost:", cost.top_users(week2))
print("request spikes (hour, requests, z):", cost.spike_hours(week1, week2))
print("cost spikes (hour, USD, z):", cost.spike_hours(week1, week2, "cost"))
print("user-hour alerts:", cost.user_hour_alerts(week2))
print("week 1 alerts:", cost.spike_hours(week1, week1), cost.user_hour_alerts(week1))
python3 run_cost.py
cost per day (USD), budget 1.0
  2026-10-12    0.49  
  2026-10-13    0.65  
  2026-10-14    0.47  
  2026-10-15    2.14  OVER BUDGET
  2026-10-16    0.48  
  2026-10-17    0.07  
  2026-10-18    0.07  
week 2 total: 4.37 week 1 total: 2.41
top users by cost: [('u_3ca43ca6', 1.66), ('u_f29a99ff', 0.4), ('u_1b458063', 0.4)]
request spikes (hour, requests, z): [('2026-10-13T10', 113.0, 33.7), ('2026-10-13T11', 113.0, 33.7), ('2026-10-15T14', 165.0, 51.3)]
cost spikes (hour, USD, z): [('2026-10-13T10', 0.1413, 8.7), ('2026-10-13T11', 0.1276, 7.6), ('2026-10-15T14', 1.6993, 141.4)]
user-hour alerts: [('u_3ca43ca6', '2026-10-15T14', 150), ('u_bc5bfb76', '2026-10-13T10', 97), ('u_bc5bfb76', '2026-10-13T11', 103)]
week 1 alerts: [] []
Cost of each day of week 2, in USD
Mon 12 Oct0.49Tue 13 Oct0.65Wed 14 Oct0.47Thu 15 Oct2.14Fri 16 Oct0.48Sat 17 Oct0.07Sun 18 Oct0.07Mon 12 Oct0.49Tue 13 Oct0.65Wed 14 Oct0.47Thu 15 Oct2.14Fri 16 Oct0.48Sat 17 Oct0.07Sun 18 Oct0.07

Answer the finance lead from the output. Thursday 2026-10-15 cost 2.14 USD, more than the budget of 1.00. One user, u_3ca43ca6, spent 1.66 USD, and sent 150 requests in the single hour 14:00. The user-hour alert names the same user, and the next user on the list spent only 0.40 USD.

The request spikes show a second event that the budget does not: on Tuesday 2026-10-13 the hours 10 and 11 had 113 requests each, and one user (u_bc5bfb76) sent 97 and 103. The cost of those hours was small, and the day stayed under the budget. A rate alarm cannot tell expensive abuse from cheap abuse. Only the cost view tells them apart, and lesson 5 explains the Tuesday user.

This report runs by hand, so it does not yet tell anyone on the day. Lesson 9 puts it in one command. A scheduler plus a mail or chat hook, which the lab does not have, is what tells a person at 10:00 on Tuesday.

The two bursts of week 2
Tue 13 Oct 10:00u_bc5bfb76 sends 97 requests in the hour; the cost stays smallTue 13 Oct 11:00the same user sends 103 more; the day stays under the budgetThu 15 Oct 14:00u_3ca43ca6 sends 150 requests; the hour costs 1.70 USDThu 15 Octthe day costs 2.14 USD and goes over the budget of 1.00Tue 13 Oct 10:00u_bc5bfb76 sends 97 requests in the hour;the cost stays smallTue 13 Oct 11:00the same user sends 103 more; the day staysunder the budgetThu 15 Oct 14:00u_3ca43ca6 sends 150 requests; the hourcosts 1.70 USDThu 15 Octthe day costs 2.14 USD and goes over thebudget of 1.00

5. See why the median matters

Now test the usual z-score on week 2 itself, with its own mean and standard deviation, and compare it with the robust score.

python3 -c "
import statistics, cost
from logrec import load
h = cost.hourly(load('logs/week2.jsonl'))
v = list(h.values())
m, s = statistics.mean(v), statistics.pstdev(v)
for k in ('2026-10-13T10', '2026-10-15T14'):
    print(k, int(h[k]), 'requests: usual z', round((h[k] - m) / s, 1), ', robust z', round(cost.robust_z(h[k], v), 1))
"
2026-10-13T10 113 requests: usual z 3.2 , robust z 22.0
2026-10-15T14 165 requests: usual z 5.1 , robust z 33.7

With the usual score, Tuesday's hour gets 3.2, below the limit of 3.5: the Thursday spike has pulled the standard deviation up, and Tuesday is missed. The robust score gives 22.0 for the same hour. That is the reason for the median.

6. Count what the tokens do not cover

The tokens are two of four parts of the cost of an AI service: the prompts (input tokens) and the responses (output tokens). The other two are the processing around the model (each tool call and each retrieved document uses compute and an outside service) and the storage of logs, documents and vectors. The log holds no price for these two, so the lab invents them (the line TOOL, DOC, MB_MONTH of the program): 0.0005 USD for a tool call, 0.0002 USD for a document, and 0.05 USD for each megabyte of log kept for a month. os.path.getsize gives the size of a file in bytes. The last line adds what the log would weigh if it held the text, which lesson 1 forbids.

costparts.py

"""costparts.py: the cost of week 2 in four parts, with invented prices for processing and storage."""
import os

from logrec import PRICE_IN, PRICE_OUT, load

rs = load("logs/week2.jsonl")
mb = os.path.getsize("logs/week2.jsonl") / 1e6
text_mb = sum(r["prompt_len"] + r["resp_len"] for r in rs) / 1e6
# invented prices, USD: one tool call, one document, one megabyte of log for a month
TOOL, DOC, MB_MONTH = 0.0005, 0.0002, 0.05
parts = {"prompts": sum(r["tokens_in"] for r in rs) * PRICE_IN / 1e6,
         "responses": sum(r["tokens_out"] for r in rs) * PRICE_OUT / 1e6,
         "processing": sum(len(r["tools"]) * TOOL + len(r["docs"]) * DOC for r in rs),
         "storage": mb * MB_MONTH}
for name, usd in parts.items():
    print(f"{name:11}{usd:6.2f}")
print("total".ljust(11) + f"{sum(parts.values()):6.2f}")
print(f"storage if the log held the text: {(mb + text_mb) * MB_MONTH:.2f}")
python3 costparts.py
prompts      2.81
responses    1.56
processing   0.49
storage      0.02
total        4.88
storage if the log held the text: 0.13

Prompts and responses add up to the 4.37 of the report. Processing is a tenth of the bill, and storage is small. In this lab, a log that kept the text would cost six times as much to store. Watch each part against its own baseline: a loop of tool calls raises processing and leaves the tokens alone. Real prices differ, so keep them in one place with their date.

Your turn

Files you need: logrec.py, cost.py, run_cost.py and the data of lesson 0 (kr-lab.sh for this lesson, then python3 makelogs.py). Finance cuts the daily budget to 0.60 USD. Change DAY_BUDGET in your copy of cost.py and run the report again for week 2.

Then use the functions of cost.py on week 1 and week 2 to answer. For the last question, change week2 to week1 in the two file names of costparts.py of step 6 and run it.

Check yourself

A budget alert fired at 09:00 on Friday for Thursday's cost. Why is it too late, and what would be better?

A daily budget is a report. The damage of Thursday was done in one hour. The hourly rules (the user limit and the spike rule) can fire within the hour. Run them every few minutes, and keep the daily budget as the last check.

Why are night and weekend hours left out of the baseline?

The traffic at night and on weekends is lower, so a baseline that mixes it in has a low median and a wide spread. Normal working hours would then look like spikes. You compare like with like.

The robust z-score is 0.6745 × (x − median) ÷ MAD. What happens if the MAD is 0?

The division fails. This happens when more than half of the values are the same, for example a rarely used tool. Then use a different rule, such as "more than three times the median plus a fixed number", or add a small floor to the MAD.

A user stays below 30 requests an hour all week, with long prompts. Which view catches the user?

The cost views. The user's cost per day and per request is high even if the rate is low. Add a per-user daily cost to the report, and look at the top users every day.

Field notes

  • Limits and alerts are different tools. The limits of "Securing LLM applications" (lesson 8) refuse the request. These alerts tell a person. Run both, and when a limit blocks a user, log the refusal: a block that nobody sees is a lost signal.
  • In the OWASP Top 10 for LLM Applications (2025) the risk is Unbounded Consumption (LLM10:2025). Cost alerts are the monitoring part of its advice: watch usage and log it to see unusual patterns.
  • A budget needs an owner. Write who gets the alert, and what they may do alone: lower a limit, disable a user, or switch to a cheaper model.
  • Count the false alerts of the rule on quiet weeks. Week 1 gives 0 in 50 working hours. A run of the generator of lesson 0 on 60 invented quiet weeks (other seeds than the lab's) raised false alerts in several of them: the MAD is small, so an ordinary busy hour can look like a spike. Do this test on your own data before you trust a limit. With 4 or more weeks of data, compare each hour with the same hour of the day.
  • Report the cost per user and per feature, not only the total: the total tells you that something happened, the split tells you who and what. Real prices change and differ by model, so keep the price table in one place with its date, and compute the cost from tokens when you read the log.