Prometheus Text Exposition Format Exporter
Cloud orchestrators scrape metrics by polling HTTP endpoints serving the Prometheus text exposition format. Each metric definition declares metadata with `# HELP` and `# TYPE`, followed by label-dimensional series (`http_requests_total{method="GET",code="200"} 4210`). It is lightweight, zero-overhead, and human-readable 📊⚡.
def render_prometheus(name, doc, metric_type, samples):
lines = [
f"# HELP {name} {doc}",
f"# TYPE {name} {metric_type}"
]
for labels, val in samples:
lbl_fmt = ",".join(f'{k}="{v}"' for k, v in sorted(labels.items()))
lines.append(f"{name}{{{lbl_fmt}}} {val}")
return "\n".join(lines) + "\n"
payload = render_prometheus(
"api_http_requests_total",
"Total processed requests",
"counter",
[({"handler": "/checkout", "status": "200"}, 1420)]
)
print(payload)
# 94. Prometheus Text Exposition Format Exporter High-throughput systems do not push metrics into third-party servers on every HTTP request—doing so introduces external network latency into the hot critical path. Instead, production engines record values in-memory and let Prometheus pull them at scheduled intervals 🛑. ```python # Prometheus Line Format Spec: # # HELP <metric_name> <docstring> # # TYPE <metric_name> <counter|gauge|histogram|summary> # <metric_name>{<label_1>="<val_1>",<label_2>="<val_2>"} <numeric_value> [timestamp] ``` ### Exposition Engineering Principles 1. **Pull vs Push Decoupling**: If the monitoring infrastructure experiences downtime, your core application remains completely unaffected because metrics scraping is decoupled from request serving ⚡. 2. **Cardinality Armor**: Never inject unbounded variables (like user IDs, raw UUIDs, or email addresses) into metric labels. High label cardinality explodes memory on both the scraping agent and the time-series database. 3. **Sorted Label Determinism**: Sort labels alphabetically before rendering. Consistent line output avoids thrashing downstream scrapers and compression algorithms 🛡️. --- ### Interactive Pop-Quiz 🧠 #### What is the primary benefit of exposing metrics via Prometheus pull-based text format instead of pushing UDP packets? - [ ] Pulling lets scrapers control scrape intervals and detect server unavailability immediately if the endpoint is unreachable 🛡️ - [ ] Text format automatically encrypts network interfaces using TLS 1.3 - [ ] Pushing UDP packets makes the kernel memory run out of CPU registers - [ ] Prometheus pull format requires zero network bandwidth --- ### Practical Challenge 🎯 Implement `format_prometheus(name: str, doc: str, mtype: str, samples: list[tuple[dict, float]]) -> str` that outputs Prometheus text with `# HELP`, `# TYPE`, and formatted `{k="v"}` labels sorted alphabetically. Test with `name='http_requests_total'`, `doc='Total HTTP requests'`, `mtype='counter'`, and samples `[({'method': 'GET', 'status': '200'}, 105.0), ({'method': 'POST', 'status': '500'}, 2.0)]`. Assert expected strings and print the output. <details> <summary>Solution</summary> ```python def format_prometheus(name: str, doc: str, mtype: str, samples: list[tuple[dict, float]]) -> str: lines = [ f"# HELP {name} {doc}", f"# TYPE {name} {mtype}" ] for labels, val in samples: if labels: lbl_str = ",".join(f"{k}=\"{v}\"" for k, v in sorted(labels.items())) lines.append(f"{name}{{{lbl_str}}} {val}") else: lines.append(f"{name} {val}") return "\n".join(lines) + "\n" samples = [ ({"method": "GET", "status": "200"}, 105.0), ({"method": "POST", "status": "500"}, 2.0) ] text = format_prometheus("http_requests_total", "Total HTTP requests", "counter", samples) assert "# HELP http_requests_total Total HTTP requests" in text assert "# TYPE http_requests_total counter" in text assert 'http_requests_total{method="GET",status="200"} 105.0' in text assert 'http_requests_total{method="POST",status="500"} 2.0' in text print(text.strip()) ``` </details>