AlgoMaster Logo
AlgoMasterBalance by Smoothed Latencymedium

Balance by Smoothed Latency

medium

Routing by the most recent latency sample can overreact to one unusually fast or slow request. An exponentially weighted moving average, or EWMA, smooths observations while still giving recent measurements more influence.

Design an EwmaLatencyBalancer class:

  • EwmaLatencyBalancer(int backendCount, double alpha) creates backends with no latency measurements.
  • double recordLatency(int backend, double observedMs) records one completed request and returns that backend's updated EWMA.
  • int pick() returns the backend preferred by the current measurements.

For the first observation of a backend:

For every later observation:

Selection rules:

  1. If any backend is unmeasured, return the smallest unmeasured index.
  2. Otherwise return the backend with the smallest EWMA.
  3. Break equal-EWMA ties by smaller index.

Keep full floating-point precision in stored estimates. Floating results are accepted within 10^-5.

Example 1:

Input:

Output:

Explanation: Every backend receives an initial measurement. Backend 1 later ties backend 2 at 80 ms and wins by index, then rises to 140 ms after a 200 ms observation.

Example 2:

Input:

Output:

Explanation: The smaller alpha dampens changes. Backend 0 moves from 100 to 90 rather than immediately becoming 60.

Constraints

  • 1 <= backendCount <= 10^5
  • 0 <= alpha <= 1
  • 0 <= backend < backendCount
  • 0 <= observedMs <= 10^9
  • At most 10^5 calls are made to each method.
  • Floating-point answers are accepted within 10^-5.
Hints

Loading...
CallReturns
new EwmaLatencyBalancer(3, 0.5)null
pick()0
recordLatency(0, 100)100
pick()1
recordLatency(1, 60)60
pick()2
recordLatency(2, 80)80
pick()1
recordLatency(1, 100)80
pick()1
recordLatency(1, 200)140
pick()2

Unmeasured backends are explored in index order. Once measured, backend 1 ties backend 2 at 80 ms and wins by index; after its EWMA rises to 140 ms, backend 2 wins.

Run checks these cases. Submit also runs a larger hidden set.