Back
+30 XP
Concept

Async Periodic Heartbeat Daemon

Background health monitors must reliably ping external cluster nodes without accumulating drift or leaking tasks on shutdown. An async heartbeat daemon runs a non-drifting loop, tracks consecutive health probe failures, and supports graceful cancellation.

python
import asyncio

async def heartbeat(target_fn, interval=5.0):
    while True:
        await target_fn()
        await asyncio.sleep(interval)

# Async Periodic Heartbeat Daemon When orchestrating microservice clusters, silence kills. If a database replica or worker node drops offline, your API gateway must detect the outage within milliseconds, not minutes after user transactions start dropping. 💓⚡ A production **Heartbeat Daemon** runs as an unblocking background `asyncio.Task`. It probes upstream health at rigid intervals, accounts for execution time to prevent drift, counts consecutive connection timeouts, and sounds the alarm when health thresholds are breached. ```python import asyncio async def monitor_heartbeat(health_check, interval: float = 1.0): while True: start_time = asyncio.get_running_loop().time() is_healthy = await health_check() elapsed = asyncio.get_running_loop().time() - start_time await asyncio.sleep(max(0.0, interval - elapsed)) ``` ## Pop Quiz Why should a periodic daemon use `loop.time()` drift adjustment instead of naive `asyncio.sleep(interval)`? - [ ] Execution duration of the ping callable delays the next tick, accumulating timing skew over hours. - [ ] The Python event loop resets its internal clock ticks on every raw sleep call. - [ ] Naive sleep calls force the garbage collector into full stop-the-world sweeps. - [ ] OS kernels throttle sleeping asyncio tasks if they are not tied to monotonic clock deltas. ## Real-World Challenge Implement `HeartbeatDaemon(interval: float, max_consecutive_misses: int, ping_coro)`. It must support `start()` and `async stop()`. If `ping_coro()` returns `False` or raises an exception `max_consecutive_misses` times consecutively, set `alert_triggered = True` and halt probing. <details> <summary>Solution</summary> ```python import asyncio class HeartbeatDaemon: def __init__(self, interval: float, max_consecutive_misses: int, ping_coro): self.interval = interval self.max_misses = max_consecutive_misses self.ping_coro = ping_coro self.consecutive_misses = 0 self.running = False self.alert_triggered = False self._task = None async def _probe_loop(self): loop = asyncio.get_running_loop() while self.running: tick_start = loop.time() try: healthy = await self.ping_coro() if healthy: self.consecutive_misses = 0 else: self.consecutive_misses += 1 except Exception: self.consecutive_misses += 1 if self.consecutive_misses >= self.max_misses: self.alert_triggered = True self.running = False break elapsed = loop.time() - tick_start remaining_sleep = max(0.0, self.interval - elapsed) try: await asyncio.sleep(remaining_sleep) except asyncio.CancelledError: break def start(self): self.running = True self._task = asyncio.create_task(self._probe_loop()) async def stop(self): self.running = False if self._task: self._task.cancel() try: await self._task except asyncio.CancelledError: pass # Verification async def run_test(): status = True async def probe(): return status daemon = HeartbeatDaemon(interval=0.01, max_consecutive_misses=2, ping_coro=probe) daemon.start() await asyncio.sleep(0.025) assert daemon.alert_triggered is False status = False await asyncio.sleep(0.035) assert daemon.alert_triggered is True await daemon.stop() asyncio.run(run_test()) ``` </details>