Deregistration

Step 3: Deregistration

Instances also leave gracefully: a service shutting down should announce its departure rather than wait to expire, so callers stop routing to it immediately. deregister removes an instance from the pool at once. It must be safe to call on an instance (or service) that isn't there, so a double-deregister or a stale call never raises.

Add graceful removal:

  • deregister(service, instance_id): remove the instance from its service if present; do nothing (no error) if it isn't.
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):
        svc = self.instances.get(service, {})
        if instance_id in svc:
            svc[instance_id] = now
            return True
        return False

    def deregister(self, service, instance_id):
        """Remove an instance immediately; a no-op if it isn't registered."""
        # TODO: self.instances.get(service, {}).pop(instance_id, None)
        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.