AlgoMaster Logo
AlgoMasterBuild a Lease-Based Service Registrymedium

Build a Lease-Based Service Registry

medium

A service registry must stop returning instances that have disappeared, while still allowing live instances to renew their leases and temporarily leave traffic without unregistering.

Design a ServiceRegistry class:

  • ServiceRegistry(int leaseTtl) creates an empty registry with a fixed lease duration.
  • addInstance(service, instanceId, zone, now) adds a ready instance and returns false when that active instance id already exists.
  • heartbeat(instanceId, now) renews a live instance from now.
  • setReady(instanceId, ready, now) changes whether a live instance may receive traffic without renewing its lease.
  • deregister(instanceId, now) removes a live instance immediately.
  • discover(service, preferredZone, now) returns eligible instance ids.

Times within one object are nondecreasing. Before every operation, expire all entries satisfying:

An expired instance cannot be revived by a heartbeat, readiness change, or deregistration. Its id may be registered again as a new entry. Active instance ids are globally unique across services.

Discovery includes only live, ready instances of the requested service. Return preferred-zone ids first, followed by other zones, with each group sorted lexicographically.

Example 1:

p1 is preferred while it is ready. Its readiness update removes it from discovery but does not renew or delete its registration.

Example 2:

The renewal at time 8 keeps the instance live through times below 18. It expires exactly at time 18.

Constraints

  • 1 <= leaseTtl <= 10^9
  • Names and ids contain 1 to 40 printable non-space characters.
  • 0 <= now <= 10^9, and times are nondecreasing within one object.
  • At most 500 live registrations and 10^4 total operations exist per object.
Hints

Loading...
CallReturns
new ServiceRegistry(10)null
addInstance("payment", "p1", "zone-a", 0)true
addInstance("payment", "p2", "zone-b", 0)true
discover("payment", "zone-a", 5)["p1","p2"]
setReady("p1", false, 6)true
discover("payment", "zone-a", 6)["p2"]

Both instances are live at time 5 and the preferred-zone instance appears first. Making p1 unready removes it from discovery without deregistering it.

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