Metrics
FastPluggy provides a metrics capability for exposing operational metrics in Prometheus format. Both plugins and core can expose metrics via the MetricsProvider protocol.
Metrics Protocol
The MetricsProvider protocol and its two dataclasses are defined in fastpluggy.core.metrics
(tests/test_docs_metrics.py checks this block against them):
from dataclasses import dataclass, field
from typing import Protocol, runtime_checkable
@dataclass
class MetricEntry:
name: str
value: float # for a histogram: not rendered, pass the observation count
type: str # "gauge" | "counter" | "histogram"
help: str = ""
labels: dict[str, str] = field(default_factory=dict)
# Histogram fields, all three set when type="histogram"
buckets: list[tuple[float, int]] | None = None # (le_bound, cumulative_count)
histogram_sum: float | None = None
histogram_count: int | None = None
@dataclass
class MetricsResult:
gauges: list[MetricEntry] = field(default_factory=list)
counters: list[MetricEntry] = field(default_factory=list)
histograms: list[MetricEntry] = field(default_factory=list)
@property
def all_entries(self) -> list[MetricEntry]:
return self.gauges + self.counters + self.histograms
@runtime_checkable
class MetricsProvider(Protocol):
def get_metrics(self) -> MetricsResult: ...
Put each entry in the list of its type. The aggregator renders all_entries, and its dashboard
counts and shows each list separately.
Plugin Metrics
Plugins declare the metrics capability and implement get_metrics():
from fastpluggy.core.module_base import FastPluggyBaseModule
from fastpluggy.core.metrics import MetricEntry, MetricsResult
REQUESTS = {"200": 0, "500": 0}
CONNECTIONS: set = set()
class MyPlugin(FastPluggyBaseModule):
module_name: str = "my_plugin"
capabilities: list = ["metrics"]
def get_metrics(self) -> MetricsResult:
return MetricsResult(
counters=[
MetricEntry(name="requests_total", type="counter", value=count,
help="Total HTTP requests handled", labels={"status": status})
for status, count in REQUESTS.items()
],
gauges=[
MetricEntry(name="active_connections", type="gauge", value=len(CONNECTIONS),
help="Current active connections"),
],
)
The metrics plugin (if installed) collects every loaded plugin that declares the metrics
capability and implements get_metrics(), on each load of the application (start-up and
every reload). It serves them in the Prometheus format at /api/prometheus under its mount
point (/plugin-pkg/metrics/api/prometheus when installed as a package), and as JSON at
/api/all.
Metric names
The aggregator prefixes metric names with fp_{plugin_name}_, so a plugin named my_plugin
exposing requests_total becomes fp_my_plugin_requests_total in the Prometheus output.
Core Metrics
Core registers a CoreMetricsProvider that exposes framework-level metrics:
| Metric | Type | Description |
|---|---|---|
fp_core_plugins_loaded |
gauge | Total loaded plugin count |
fp_core_plugins_enabled |
gauge | Enabled plugin count |
fp_core_plugins_failed |
gauge | Failed plugin count |
fp_core_load_time_ms |
gauge | Total load_app() duration in milliseconds |
fp_core_plugin_load_time_ms{plugin="..."} |
gauge | Per-plugin load time |
fp_core_event_listeners_count |
gauge | Current event bus listener count |
fp_core_events_dispatched_total |
counter | Total events emitted |
fp_core_session_key_default |
gauge | 1 when sessions are signed with the public built-in default key |
fp_core_build_info{build="..."} |
gauge | Always 1; emitted only when the deployment sets its build identifier |
Core metrics are automatically available when the metrics plugin is installed (no plugin changes needed).
Grafana dashboard
A ready-to-import Grafana dashboard ships in the repository at grafana/fastpluggy-core.json with panels for:
- Plugin overview (loaded/enabled/failed counts)
- App load time
- Per-plugin load time (bar chart, sorted by duration)
- Event bus throughput (rate(fp_core_events_dispatched_total[5m]))
- Event listeners count
Histogram Metrics
Histogram metrics track value distributions (e.g. request duration, task execution time).
Producing histograms
A histogram entry requires three fields:
MetricEntry(
name="task_duration_seconds",
type="histogram",
value=32, # not rendered for a histogram
help="Task execution duration",
labels={"task_name": "sync_data", "status": "success"},
buckets=[
(0.01, 5), # ≤10ms: 5 observations
(0.05, 12), # ≤50ms: 12 (cumulative)
(0.1, 20), # ≤100ms: 20
(0.5, 25), # ≤500ms: 25
(1.0, 30), # ≤1s: 30
(5.0, 32), # ≤5s: 32
(float("inf"), 32) # +Inf bucket (total count)
],
histogram_sum=15.3, # sum of all observations
histogram_count=32 # total observation count
)
Bucket requirements:
- Buckets are (le_bound, cumulative_count) pairs
- Counts must be cumulative (monotonically increasing)
- The last bucket should be (float("inf"), total_count)
- Buckets should be sorted by le_bound ascending
Prometheus output
The aggregator renders histograms per the Prometheus exposition format:
# HELP fp_my_plugin_task_duration_seconds Task execution duration
# TYPE fp_my_plugin_task_duration_seconds histogram
fp_my_plugin_task_duration_seconds_bucket{task_name="sync_data",status="success",le="0.01"} 5
fp_my_plugin_task_duration_seconds_bucket{task_name="sync_data",status="success",le="0.05"} 12
fp_my_plugin_task_duration_seconds_bucket{task_name="sync_data",status="success",le="0.1"} 20
fp_my_plugin_task_duration_seconds_bucket{task_name="sync_data",status="success",le="0.5"} 25
fp_my_plugin_task_duration_seconds_bucket{task_name="sync_data",status="success",le="1.0"} 30
fp_my_plugin_task_duration_seconds_bucket{task_name="sync_data",status="success",le="5.0"} 32
fp_my_plugin_task_duration_seconds_bucket{task_name="sync_data",status="success",le="+Inf"} 32
fp_my_plugin_task_duration_seconds_sum{task_name="sync_data",status="success"} 15.3
fp_my_plugin_task_duration_seconds_count{task_name="sync_data",status="success"} 32
Accumulating histograms
Use a helper class to accumulate observations into histogram buckets:
class HistogramAccumulator:
def __init__(self, buckets: list[float]):
self.buckets = sorted(buckets)
self.bucket_counts = {b: 0 for b in buckets}
self.sum = 0.0
self.count = 0
def observe(self, value: float):
self.sum += value
self.count += 1
for bucket in self.buckets:
if value <= bucket:
self.bucket_counts[bucket] += 1 # the smallest bucket only: snapshot() sums them
break
def snapshot(self) -> tuple[list[tuple[float, int]], float, int]:
# Convert per-bucket counts to cumulative
cumulative = 0
buckets = []
for bound in self.buckets:
cumulative += self.bucket_counts[bound]
buckets.append((bound, cumulative))
buckets.append((float("inf"), self.count))
return buckets, self.sum, self.count
Then in get_metrics():
def get_metrics(self) -> MetricsResult:
buckets, total, count = self.histogram.snapshot()
return MetricsResult(histograms=[
MetricEntry(
name="task_duration_seconds",
type="histogram",
value=count,
buckets=buckets,
histogram_sum=total,
histogram_count=count,
labels={"task_name": "sync"}
)
])
Standard bucket sets
Common bucket boundaries for different value ranges:
Latency (milliseconds/seconds):
Duration (seconds/minutes):
Size (bytes/KB/MB):