Heartbeats

Step 2: Heartbeats

An instance proves it's still alive by sending a heartbeat: a periodic ping that refreshes its last-seen time, resetting its TTL. This is the mechanism that keeps a busy instance in the pool and lets a crashed one fall out automatically: no heartbeat, no refresh, and it expires. A heartbeat for an instance the registry has never seen is meaningless and should be rejected.

Add heartbeats:

  • heartbeat(service, instance_id, now): if the instance is registered, update its last-seen to now and return True; otherwise return False.
Hints
Starter code
class ServiceRegistry:
    def __init__(self, ttl=10):
        self.ttl = ttl
        self.instances = {}
        self._rr = {}

    def register(self, service, instance_id, now):
        self.instances.setdefault(service, {})[instance_id] = now

    def healthy(self, service, now):
        svc = self.instances.get(service, {})
        return sorted(i for i, last in svc.items() if now - last <= self.ttl)

    def heartbeat(self, service, instance_id, now):
        """Refresh a known instance's TTL; reject unknown instances."""
        svc = self.instances.get(service, {})
        # TODO: svc holds this service's instance ids mapped to their last-seen
        #   times. Only an id already present there may beat: refresh its
        #   last-seen stamp to now and report True. An id the registry has never
        #   registered gets False and no change.
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.