Skip to content

Parse metrics in a worker thread to avoid blocking the event loop - #284

Closed
nsleigh wants to merge 1 commit into
tr4nt0r:mainfrom
nsleigh:offload-metrics-parsing
Closed

nsleigh wants to merge 1 commit into
tr4nt0r:mainfrom
nsleigh:offload-metrics-parsing

Conversation

@nsleigh

@nsleigh nsleigh commented Nov 8, 2026

Copy link
Copy Markdown

Summary

UptimeKuma.metrics() parses the Prometheus response (text_string_to_metric_families) and builds the UptimeKumaMonitor models directly on the event loop. That work is CPU-bound and grows with the number of monitors, so on a larger Kuma instance it can block the caller's event loop. In Home Assistant this shows up as the whole instance freezing, with unrelated integrations logging "took longer than the scheduled update interval" at the same moment (home-assistant/core#178608).

This PR moves the parsing into a module-level _parse_metrics() helper and runs it with asyncio.to_thread. The HTTP request and error handling stay on the loop. The public API and return values don't change, and self.version is still updated when app_version is present.

Changes

  • pythonkuma/uptimekuma.py: parsing and model building moved into _parse_metrics(text), which returns (version, monitors). metrics() awaits it via asyncio.to_thread. UptimeKumaParseException is still raised on invalid input.
  • tests/test_metrics.py: new test checking that the parser runs on a worker thread, not the event-loop thread.

Related: home-assistant/core#178608

🤖 Generated with Claude Code

text_string_to_metric_families() and building the monitor models are
CPU-bound and scale with the number of monitors. Running them on the
event loop can stall the host application (e.g. Home Assistant) for
seconds at a time. Offload them with asyncio.to_thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the 🧪 testing Pull request that adds tests label Nov 8, 2026
@nsleigh

nsleigh commented Nov 8, 2026

Copy link
Copy Markdown
Author

Closing: testing on a live instance showed that moving the parse off the event loop doesn't fix the freeze reported in home-assistant/core#178608 (polls took ~0.1s; the stall happened during entity setup). I'll revisit when I have more time.

@nsleigh nsleigh closed this Nov 8, 2026
@nsleigh
nsleigh deleted the offload-metrics-parsing branch November 8, 2026 10:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🧪 testing Pull request that adds tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant