Back
+30 XP
Concept

Gauntlet 09: Prometheus Metrics Collector

Cloud-native observability relies on Prometheus scraping metrics over HTTP /metrics endpoints. The Prometheus text exposition format serializes counters and gauges with multi-dimensional label dimensions and standard metric metadata (# TYPE, # HELP).

python
# Prometheus exposition syntax:
# metric_name{label="val",...} 42.0
line = f'{name}{"{" + labels_str + "}" if labels_str else ""} {val}'

# Gauntlet 09: Prometheus Metrics Collector & HTTP Exporter Every production Kubernetes service exposes an HTTP `/metrics` endpoint scraped by Prometheus. If your service doesn't output metrics, you are flying blind in production. 📊📉 The **Prometheus Text Exposition Format (version 0.0.4)** defines how time-series metrics are formatted on the wire: 1. **Metadata line**: `# TYPE <metric_name> <counter|gauge>` 2. **Data line**: `<metric_name>{<label1>="<val1>",<label2>="<val2>"} <numeric_value>` - **Counter**: Cumulative metric representing a monotonically increasing counter (e.g. `http_requests_total`). - **Gauge**: Metric that represents a single numerical value that can arbitrarily go up or down (e.g. `active_db_connections`, `memory_rss_bytes`). ```text # TYPE http_requests_total counter http_requests_total{code="200",method="GET"} 1420.0 # TYPE active_workers gauge active_workers 8.0 ``` ## Pop Quiz What is the semantic difference between a Prometheus Counter and a Gauge? - [ ] Counters are monotonically increasing values that only reset to 0 on restart; Gauges represent snapshot values that move up and down. - [ ] Counters measure network traffic while Gauges measure memory usage. - [ ] Gauges cannot have multi-dimensional string labels attached. - [ ] Because Prometheus only stores Counters in its time-series database. ## Real-World Challenge Implement `PrometheusRegistry`: - `inc_counter(name: str, value: float = 1.0, labels: dict = None)`: Increments metric. - `set_gauge(name: str, value: float, labels: dict = None)`: Updates gauge value. - `export() -> str`: Formats and returns the compliant Prometheus plaintext string with sorted labels and `# TYPE` declarations. <details> <summary>Solution</summary> ```python class PrometheusRegistry: def __init__(self): self._counters = {} # (name, sorted_labels_tuple) -> float self._gauges = {} # (name, sorted_labels_tuple) -> float def _normalize_labels(self, labels: dict | None) -> tuple: if not labels: return () return tuple(sorted((k, str(v)) for k, v in labels.items())) def inc_counter(self, name: str, value: float = 1.0, labels: dict = None): key = (name, self._normalize_labels(labels)) self._counters[key] = self._counters.get(key, 0.0) + float(value) def set_gauge(self, name: str, value: float, labels: dict = None): key = (name, self._normalize_labels(labels)) self._gauges[key] = float(value) def export(self) -> str: lines = [] # Export Counters counter_names = sorted(set(name for name, _ in self._counters)) for c_name in counter_names: lines.append(f"# TYPE {c_name} counter") for (name, labels_tuple), val in sorted(self._counters.items()): if name == c_name: lbl_str = "" if labels_tuple: formatted_lbls = ",".join(f'{k}="{v}"' for k, v in labels_tuple) lbl_str = f"{{{formatted_lbls}}}" lines.append(f"{c_name}{lbl_str} {val}") # Export Gauges gauge_names = sorted(set(name for name, _ in self._gauges)) for g_name in gauge_names: lines.append(f"# TYPE {g_name} gauge") for (name, labels_tuple), val in sorted(self._gauges.items()): if name == g_name: lbl_str = "" if labels_tuple: formatted_lbls = ",".join(f'{k}="{v}"' for k, v in labels_tuple) lbl_str = f"{{{formatted_lbls}}}" lines.append(f"{g_name}{lbl_str} {val}") return "\n".join(lines) + ("\n" if lines else "") # Verification registry = PrometheusRegistry() registry.inc_counter("http_requests_total", 5.0, {"method": "GET", "status": "200"}) registry.inc_counter("http_requests_total", 1.0, {"method": "POST", "status": "500"}) registry.set_gauge("memory_bytes", 1048576.0, {"subsystem": "heap"}) output = registry.export() assert "# TYPE http_requests_total counter" in output assert 'http_requests_total{method="GET",status="200"} 5.0' in output assert 'http_requests_total{method="POST",status="500"} 1.0' in output assert "# TYPE memory_bytes gauge" in output assert 'memory_bytes{subsystem="heap"} 1048576.0' in output ``` </details>