Fleet health

Unhealthy instances, partly written

You are given heartbeat records from production instances. Return the unique instance ids that are unhealthy, in the order they first appear. An instance is unhealthy if any of its records has healthy=False, cpu at or above the threshold, or last_heartbeat_seconds greater than 120. Missing optional fields are not enough to mark it unhealthy. Ignore unknown keys.

In production

Heartbeat scrapes feed pages and alerts. If this filter is wrong, operators page healthy hosts or miss a hot CPU before traffic shifts.

What it must return

Return each unhealthy instance id once, in the order that instance first appears in the input, even when the first record for it was healthy.

  • Return unique instance ids in the order they first appear.
  • An instance is unhealthy if any record has healthy=False, CPU at or above the threshold, or last_heartbeat_seconds greater than 120.
  • Missing optional fields are not enough to mark it unhealthy.
  • Ignore unknown keys.
  • Do not modify the input. All records have valid identifiers and numeric metrics when present.

Edge cases

  • Missing cpu or last_heartbeat_seconds is not enough to mark unhealthy.
  • CPU at the threshold counts as unhealthy; just under it does not.
  • Duplicates keep the first-seen position, not the position of the failing record.

Signature

get_unhealthy_instances(records, cpu_threshold=85.0) -> list[str]

Part of this function is already written. The TODO comments mark what is left.

Hints

  1. Second hint

  2. A partial sketch

The reference solution opens after the last hint.

Adapted from Baodium Interview Coach.

solution.py · Python

Loading editor…

High CPU is unhealthy

records

[
  {
    "instance_id": "i-ok",
    "cpu": 12,
    "healthy": true,
    "last_heartbeat_seconds": 4
  },
  {
    "instance_id": "i-hot",
    "cpu": 91,
    "healthy": true,
    "last_heartbeat_seconds": 3
  }
]

Expected

[
  "i-hot"
]

Each run uses a fresh Python runtime in this browser, with a 3-second limit and a Stop button. The first run downloads the runtime. 0 of 3 in Fleet health passed in Python on this device.

Next: Unhealthy instances, with a bug