Skip to content
Coding · Medium · State machines · Target O(n) · Senior

Health check state machine

Track each backend's up or down state from a sequence of probe results using rise and fall thresholds, and return the state transitions in order.

Statement

A load balancer probes its backends and must not react to a single bad probe. Write health_transitions(probes, rise, fall, initial="down"). probes is a list of (backend, ok) in the order the probes finished. Every backend has its own state and starts in initial.

A down backend comes up on its rise-th consecutive successful probe. An up backend goes down on its fall-th consecutive failed probe. A probe that agrees with the current state ends any streak against it, and a streak starts from zero after each transition.

Return the transitions as (index, backend, state) in the order they happen, where index is the position in probes of the probe that caused the change and state is "up" or "down".

Examples

rise = 2, fall = 3, initial = "down", one backend web-1. + is a successful probe, - a failed one.

index   0  1  2  3  4  5  6  7  8  9  10
probe   +  -  +  +  +  -  -  +  -  -  -
state   d  d  d  U  u  u  u  u  u  u  D

→ [(3, "web-1", "up"), (10, "web-1", "down")]

Constraints

Up to 2 × 10⁵ probes across any number of backends, interleaved. rise ≥ 1 and fall ≥ 1. A backend first seen late in the list still starts in initial. O(1) work per probe.

Free to try · sign in to save your attemptSolve it in the editor with visible tests
Open in the app