Compute the median latency per model with window functions

HardSQLPro

Why it matters p50 latency is a headline SLO for LLM serving, and many SQL engines used for logs have no built-in median.

Median latency (p50) is more honest than the mean when a few requests hang. SQLite has no MEDIAN function, so you build one from row numbers and counts.

Write query() returning a SQLite SQL string. Table latencies(id INTEGER, model TEXT, ms REAL).

Return (model, median_ms) for every model, ordered by model ascending. For an odd number of rows the median is the middle value after sorting; for an even number it is the average of the two middle values.

Signaturedef query()

Example

model 'a' with 10, 30, 20 and model 'b' with 5, 1, 9, 7 give [('a', 20.0), ('b', 6.0)].

Understand the idea

The median is the middle value after sorting. Half the values are below it and half above, so one huge outlier barely moves it, unlike the mean.

Worked example: model b has 5, 1, 9, 7. Sorted: 1, 5, 7, 9. cnt = 4 is even, so the median is the average of rows 2 and 3: (5 + 7) / 2 = 6.0. Model a has 10, 20, 30 sorted, cnt = 3, so the median is row 2: 20.0.

Rule with integer division: lo = (cnt + 1) / 2, hi = (cnt + 2) / 2. For cnt = 3: lo = hi = 2. For cnt = 4: lo = 2, hi = 3. median = AVG of rows lo and hi. ROW_NUMBER gives row positions and COUNT(*) OVER gives cnt.

LLM serving dashboards report p50 latency per model and per region this way.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: example_run1(query())
  • Sample 2: one slow outlier_run2(query())