A latency report arrives as pairs of observed milliseconds and exact occurrence counts. Taking the ordinary median of the listed latency values gives rare values the same influence as common values. Expanding every pair into repeated rows gives the right weighting but wastes memory. Sort the distinct or repeated values and walk their cumulative counts instead.

Prerequisites and median convention

Use Python 3.12 and save the example as weighted.py. No packages are needed. This tutorial uses the lower median for an even number of observations. In the expanded list [10, 10, 30, 30], that means 10 rather than 20 or 30. The rule deliberately returns an observed value. It is not the arithmetic midpoint convention used by some median functions.

def weighted_median(rows):
    rows = list(rows)
    for value, count in rows:
        if type(value) is not int or type(count) is not int or count < 0:
            raise ValueError("expected integer values and nonnegative counts")
    total = sum(count for _, count in rows)
    if total == 0:
        raise ValueError("no observations")
    running = 0
    for value, count in sorted(rows):
        running += count
        if 2 * running >= total:
            return value

rows = [(900, 1), (25, 8), (90, 2)]
answer = weighted_median(rows)
expanded = sorted(v for v, n in rows for _ in range(n))
assert answer == expanded[(len(expanded) - 1) // 2] == 25
assert weighted_median([(10, 2), (30, 2), (-5, 0)]) == 10
assert weighted_median([(5, 10**20), (100, 1)]) == 5
assert weighted_median([(9, 1), (4, 1), (4, 1)]) == 4
for invalid in [[], [(1, 0)], [(1, -1)], [(1, True)]]:
    try:
        weighted_median(invalid)
    except ValueError:
        continue
    raise AssertionError("accepted invalid counts")
print(f"lower weighted median = {answer} ms")

Run and read the cumulative count

python3 weighted.py
lower weighted median = 25 ms

There are 11 observations and the lowest value, 25, accounts for eight of them. The halfway point is already inside that run of eight. Comparing twice the cumulative count against the total keeps the boundary exact for integer counts, including counts too large for an exact floating-point conversion. The expanded list in the script is a small independent fixture check only. The algorithm itself sorts input rows, not observations. Zero-count rows carry no mass, and repeated values can remain separate because the return value at the crossing is the same.

Check that the input represents observations

Do not feed interval buckets into this function as if their midpoints were exact values. With bucketed data, the cumulative count can identify the median bucket, but the exact latency inside that bucket is generally unknown. Similarly, per-shard medians and request totals are not enough to reconstruct the overall median. Merge exact frequency tables or use a compatible summary designed for quantiles. If your result differs from a dashboard, check the even-count convention and whether the dashboard interpolates before treating the difference as a data error.

Federal Reserve survey manual on weighted medians · Java Samples data-science tutorials