How to Build a Health Check Service Registry in Python
Build a minimal Python service registry that handles registration, deregistration, health checks, and service listing in one simple class.
Python code
57 linesimport random
import time
class ServiceRegistry:
def __init__(self):
self.services = {}
def register(self, name, address):
self.services[name] = {
"address": address,
"status": "healthy",
"registered_at": time.time(),
"checks": 0
}
return f"Registered {name} at {address}"
def deregister(self, name):
if name in self.services:
del self.services[name]
return f"Deregistered {name}"
return f"Service {name} not found"
def health_check(self, name):
if name not in self.services:
return f"Service {name} not registered"
service = self.services[name]
service["checks"] += 1
is_healthy = random.random() > 0.3
service["status"] = "healthy" if is_healthy else "unhealthy"
return f"{name} status: {service['status']} (check #{service['checks']})"
def list_services(self):
return list(self.services.keys())
if __name__ == "__main__":
registry = ServiceRegistry()
print(registry.register("api-gateway", "http://localhost:8080"))
print(registry.register("auth-service", "http://localhost:8081"))
print(registry.register("user-service", "http://localhost:8082"))
print("\nRegistered services:", registry.list_services())
print("\nFirst health check:")
print(registry.health_check("api-gateway"))
print(registry.health_check("auth-service"))
print("\nSecond health check:")
print(registry.health_check("api-gateway"))
print(registry.health_check("api-gateway"))
print("\n" + registry.deregister("user-service"))
print("Remaining services:", registry.list_services())
print("\n" + registry.health_check("user-service"))
Output
Registered api-gateway at http://localhost:8080
Registered auth-service at http://localhost:8081
Registered user-service at http://localhost:8082
Registered services: ['api-gateway', 'auth-service', 'user-service']
First health check:
api-gateway status: healthy (check #1)
auth-service status: healthy (check #2)
Second health check:
api-gateway status: healthy (check #3)
api-gateway status: unhealthy (check #4)
Deregistered user-service
Remaining services: ['api-gateway', 'auth-service']
user-service not registered
How it works
The ServiceRegistry class stores each service in a dictionary keyed by its name, giving O(1) access for register, deregister, and health checks. The health_check method simulates status fluctuations with random.random(), returning healthy 70% of the time (since 0.3 equals a 30% failure rate). Each check increments a counter, which makes it easy to track check history for debugging or monitoring. The string formatting in health_check uses an f-string to combine status and check count cleanly. Deregistering simply removes the key, and listing returns only the keys — keeping the object small and focused on registry behavior.
Common mistakes
- Treating `random.random()` > 0.3 as a health check instead of a simulation — real checks need actual PING or HTTP probes
- Not noticing that a deregistered service loses all its check history since the dictionary entry is deleted
- Forgetting that the registry is in-memory only — it will lose all data on process restart
Variations
- Use a `defaultdict(dict)` for automatic initialization of service entries
- Add a heartbeat thread that periodically runs health checks on all registered services
Real-world use cases
- Simulating service discovery in local microservices demos where you need to register APIs and check their health
- Teaching or prototyping a service registry pattern before jumping into production-grade tools like Consul or etcd
- Building a custom metrics endpoint that tracks health check counts of backend services during development
Sponsored
More from Microservices patterns
- BFF aggregation pattern: combine multiple service responses in Python easy
- Backward Compatible Schema Evolution in Python medium
- Bulkhead Thread Pool per Service Mock in Python medium
- CQRS with Separate Read and Write Repositories in Python medium
- Cache-Aside Pattern in Python: Per-Service Mock easy
- Consumer Driven Contract Pact Mock in Python medium
Keep learning
Related tutorials and quizzes for this topic.