Given per-minute aggregate serving metrics with numeric minute
indexes, flag minutes where queue growth and tail latency suggest
overload even if error rate is low.
Hidden answer: invariant, test cases, and Python solution
Invariant: overload is a joint signal. High utilization alone can
be healthy; queue growth plus tail latency means work is waiting.
Sort or require monotonic telemetry before comparing adjacent
minutes. Test flat queues, rising queues with low latency, high
latency with no queue growth, missing minutes, duplicate minutes,
and impossible negative counters.
def detect_saturation(minutes, queue_growth_threshold=25, p95_threshold_ms=1200):
if queue_growth_threshold < 0 or p95_threshold_ms < 0:
raise ValueError("thresholds must be non-negative")
alerts = []
previous_minute = None
previous_depth = None
for point in sorted(minutes, key=lambda item: item["minute"]):
minute = point["minute"]
depth = point["queue_depth"]
p95 = point["p95_ms"]
if depth < 0 or p95 < 0:
raise ValueError(f"minute {minute}: queue depth and p95 must be non-negative")
if previous_depth is None:
previous_minute = minute
previous_depth = depth
continue
if minute == previous_minute:
raise ValueError(f"duplicate telemetry for minute {minute}")
if minute - previous_minute > 1:
alerts.append({
"minute": minute,
"missing_minutes": minute - previous_minute - 1,
"action": "check_telemetry_gap_before_scaling_decision",
})
growth = depth - previous_depth
if growth >= queue_growth_threshold and p95 >= p95_threshold_ms:
alerts.append({
"minute": minute,
"queue_growth": growth,
"p95_ms": p95,
"action": "shed_batch_or_add_capacity",
})
previous_minute = minute
previous_depth = depth
return alerts