1. Understand the Goal: The user wants a "metric aggregation system." This is a broad request. I need to interpret what a typical, useful, and educational implementation looks like.
-
Identify Key Components: A metric aggregation system generally involves:
- Ingestion: Receiving metric data (counters, gauges, histograms).
- Storage/Aggregation: Storing these metrics in memory, usually aggregating them over time windows (e.g., calculating rates, sums, percentiles).
- Exposure/Retrieval: Allowing the data to be queried or exported (e.g., Prometheus-style text exposition).
-
Choose a Language: Python is excellent for this because it's readable and has good standard libraries for HTTP servers and concurrency. Go is also popular in the observability space (Prometheus is written in Go), but Python is often more accessible for a general "write a program" request unless specified otherwise. Let's stick to Python.
-
Determine the Scope/Features:
- Simple approach: A dictionary that counts things.
- Better approach: Support different metric types (Counter, Gauge, Histogram).
- Advanced approach: Time-windowed aggregation, multi-threading safety, an HTTP endpoint for scraping.
Let's aim for the "Better/Advanced" mix. I will implement:
Counter: Only goes up (cumulative).
Gauge: Goes up and down (current state).
Histogram: Buckets observations (latency, sizes).
- A simple Flask/FastAPI (or just
http.server) endpoint to expose metrics in a Prometheus-like format.
-
Drafting the Architecture:
- Class
MetricRegistry: Holds all the metrics. ensures thread safety (using a Lock).
- Abstract Base Class
Metric: Defines the interface (inc, dec, observe, collect).
- Concrete Classes:
Counter: inc(delta)
Gauge: inc(delta), dec(delta), set(value)
Histogram: observe(value) - needs bucket definitions.
- Server: A simple HTTP server that calls
registry.output() and prints it.
-
Refining the Implementation Details:
-
Thread Safety: Essential for a real system. I'll use threading.Lock.
-
Naming: Use standard naming conventions (snake_case).
-
Labels/Tags: Real-world metrics need tags (e.g., path=/api, status=200). Implementing a full label system (cardinality management) is complex, so I'll stick to a simpler version: metrics have names, and maybe basic labels, or just names for the MVP to keep code size reasonable.
-
Decision: Let's keep labels out of the core implementation to keep the code understandable, but mention them in the explanation. Or, better yet, I can implement a simple label dict approach. Let's stick to named metrics without dynamic labels for the code example to ensure it fits in a single readable file, but structure it so labels could be added.
-
Histogram Logic: How to store buckets? A dictionary mapping upper bounds to counts.
-
Writing the Code (Mental Draft & Iteration):
-
Imports: threading, time, math, http.server.
-
Registry: needs register(metric) and get_all().
-
Counter:
class Counter:
def __init__(self, name, help_text):
self.name = name
self.value = 0
self.lock = Lock()
def inc(self, val=1):
with self.lock: self.value += val
-
Gauge: Similar to Counter but allows decrementing.
-
Histogram: Needs buckets (e.g., 0.1, 0.5, 1.0, +Inf).
class Histogram:
def __init__(self, name, buckets):
self.buckets = {b: 0 for b in buckets}
self.sum = 0
self.count = 0
def observe(self, val):
self.count += 1
self.sum += val
for b in self.buckets:
if val <= b:
self.buckets[b] += 1
-
Output Format: Prometheus text format is the industry standard.
# HELP my_counter Total count
# TYPE my_counter counter
my_counter 10
-
Adding "Aggregation" Logic:
The prompt asks for "metric aggregation." This usually implies:
- Receiving raw data points.
- Summing/Counting them locally.
- Maybe rolling windows (ephemeral metrics).
The implementation above covers local aggregation (turning events into counters/summaries). To make it more "system-like," I should simulate a workload that pushes metrics while the server exposes them.
-
Refining the Code Structure:
- File:
metrics_system.py
- Classes:
MetricRegistry, Counter, Gauge, Histogram.
- Server: A background thread running
http.server.
- Simulation: A main loop that generates traffic.
-
Self-Correction/Review:
- Critique: The histogram implementation needs to be cumulative (standard for Prometheus). If a value is 0.3, it goes into the 0.5 bucket and the 1.0 bucket, etc.
- Fix: Loop through sorted buckets. If value <= bucket, increment bucket.
-
Final Code Assembly Plan:
- Define the
Metric base structure.
- Implement
Counter, Gauge, Histogram.
- Implement
Registry to manage them.
- Add a text exporter method.
- Add a simple HTTP server to scrape it.
- Add a "Worker" thread to simulate data generation.
-
Constructing the Explanation:
- Explain what the code does (types of metrics).
- Explain the Prometheus exposition format.
- Explain Thread Safety.
-
Final Polish: Ensure the code is PEP 8 compliant and handles edge cases (like negative counters - usually not allowed). (Self-correction: Counters shouldn't go down in standard systems, but for a simple demo, maybe just let it. I'll enforce positive increments).
Let's write the code. I will use Python as it is most pseudocode-friendly and executable.
Key features to include:
- Counter: Cumulative metric.
- Gauge: Point-in-time metric.
- Histogram: Distribution of values.
- Registry: Singleton-ish container.
- Exporter: HTTP endpoint.
(Self-Correction during drafting Histogram): Handling "infinity" is necessary for the _bucket metrics. I'll add float("inf").
Let's execute.
Here is a complete, robust implementation of a Metric Aggregation System in Python.
This system is designed to be thread-safe and follows patterns similar to industry-standard libraries (like Prometheus). It supports the three core metric types: Counters, Gauges, and Histograms. It also includes an HTTP server to expose the metrics so they can be scraped by monitoring tools.
The Architecture
MetricsRegistry: The central hub where all metrics are stored and managed.
Metric Classes: Specific implementations for Counters (increment only), Gauges (up/down), and Histograms (distribution).
Exporter: An HTTP server that formats the data into a text-based format ready for scraping.
The Code
Save this file as metrics_system.py.
import threading
import time
import math
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import List, Dict, Optional
from collections import defaultdict
# ==========================================
# 1. Core Metric Types
# ==========================================
class Counter:
"""
A metric that only goes up (cumulative).
Use for: Request counts, tasks completed, errors.
"""
def __init__(self, name: str, help_text: str):
self.name = name
self.help_text = help_text
self._value = 0.0
self._lock = threading.Lock()
def inc(self, amount: float = 1.0):
if amount < 0:
raise ValueError("Counter can only be incremented by non-negative amounts.")
with self._lock:
self._value += amount
def get_value(self) -> float:
with self._lock:
return self._value
def collect(self) -> str:
return f"# HELP {self.name} {self.help_text}\n# TYPE {self.name} counter\n{self.name} {self.get_value()}\n"
class Gauge:
"""
A metric that can go up or down (current state).
Use for: Memory usage, active threads, temperature.
"""
def __init__(self, name: str, help_text: str):
self.name = name
self.help_text = help_text
self._value = 0.0
self._lock = threading.Lock()
def inc(self, amount: float = 1.0):
with self._lock:
self._value += amount
def dec(self, amount: float = 1.0):
with self._lock:
self._value -= amount
def set(self, value: float):
with self._lock:
self._value = value
def get_value(self) -> float:
with self._lock:
return self._value
def collect(self) -> str:
return f"# HELP {self.name} {self.help_text}\n# TYPE {self.name} gauge\n{self.name} {self.get_value()}\n"
class Histogram:
"""
A metric that observes the distribution of values.
Use for: Latency, request sizes.
"""
def __init__(self, name: str, help_text: str, buckets: List[float] = None):
self.name = name
self.help_text = help_text
# Default buckets (in seconds/milliseconds depending on context)
if buckets is None:
buckets = [.005, .01, .025, .05, .075, .1, .25, .5, .75, 1.0, 2.5, 5.0, 7.5, 10.0, float("inf")]
# Ensure buckets are sorted and include infinity
self.buckets = sorted(buckets)
if self.buckets[-1] != float("inf"):
self.buckets.append(float("inf"))
self._counts = [0] * len(self.buckets)
self._sum = 0.0
self._count = 0
self._lock = threading.Lock()
def observe(self, amount: float):
with self._lock:
self._sum += amount
self._count += 1
# Increment bucket counters
for i, threshold in enumerate(self.buckets):
if amount <= threshold:
self._counts[i] += 1
break
def collect(self) -> str:
lines = []
lines.append(f"# HELP {self.name} {self.help_text}")
lines.append(f"# TYPE {self.name} histogram")
with self._lock:
cumulative_count = 0
# Output buckets (cumulative)
for i, threshold in enumerate(self.buckets):
cumulative_count += self._counts[i]
label = f'le="{threshold}"' if threshold != float("inf") else 'le="+Inf"'
lines.append(f'{self.name}_bucket{{{label}}} {cumulative_count}')
lines.append(f'{self.name}_sum {self._sum}')
lines.append(f'{self.name}_count {self._count}')
return "\n".join(lines) + "\n"
# ==========================================
# 2. Registry (Singleton Pattern)
# ==========================================
class MetricRegistry:
"""
Stores all registered metrics.
"""
_instance = None
_lock = threading.Lock()
def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super(MetricRegistry, cls).__new__(cls)
cls._instance._metrics = {}
return cls._instance
def register(self, metric):
if metric.name in self._metrics:
# In production, you might want to throw an error or return existing
return self._metrics[metric.name]
self._metrics[metric.name] = metric
return metric
def get_metric(self, name: str):
return self._metrics.get(name)
def collect_all(self) -> str:
output = ""
for metric in self._metrics.values():
output += metric.collect() + "\n"
return output
# ==========================================
# 3. HTTP Exporter
# ==========================================
class MetricsRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
registry = MetricRegistry()
if self.path == '/metrics':
output = registry.collect_all()
self.send_response(200)
self.send_header('Content-Type', 'text/plain; version=0.0.4')
self.end_headers()
self.wfile.write(output.encode('utf-8'))
else:
self.send_response(404)
self.end_headers()
def log_message(self, format, *args):
# Suppress default logging to keep console clean
pass
def start_exporter(host='localhost', port=8000):
server = HTTPServer((host, port), MetricsRequestHandler)
thread = threading.Thread(target=server.serve_forever)
thread.daemon = True
thread.start()
print(f"Metrics server started at http://{host}:{port}/metrics")
# ==========================================
# 4. Usage Demonstration
# ==========================================
def simulate_application_work():
"""
Simulates a background process generating metrics.
"""
registry = MetricRegistry()
# Create metrics
http_requests_total = registry.register(Counter(
"http_requests_total",
"Total number of HTTP requests."
))
active_threads = registry.register(Gauge(
"active_threads",
"Number of active worker threads."
))
request_latency = registry.register(Histogram(
"request_latency_seconds",
"Time taken to process requests."
))
print("Simulating workload... (Press Ctrl+C to stop)")
cycle = 0
while True:
cycle += 1
# 1. Increment Counter
http_requests_total.inc()
# 2. Fluctuate Gauge
if cycle % 5 == 0:
active_threads.inc()
elif cycle % 7 == 0:
active_threads.dec()
# 3. Record Latency (simulated random value)
# Simulate latency between 0.01s and 0.2s
latency = 0.01 + (0.19 * (cycle % 10 / 10.0))
request_latency.observe(latency)
time.sleep(1)
if __name__ == "__main__":
# 1. Start the HTTP Server in a background thread
start_exporter()
# 2. Run the simulation
try:
simulate_application_work()
except KeyboardInterrupt:
print("\nSystem stopped.")
How to Run It
- Save the code above into a file named
metrics_system.py.
- Run it via your terminal:
python metrics_system.py
- Open a separate terminal or web browser and visit:
http://localhost:8000/metrics
Sample Output
When you visit the URL, you will see a text output (Prometheus format) that updates every second:
# HELP http_requests_total Total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total 45.0
# HELP active_threads Number of active worker threads.
# TYPE active_threads gauge
active_threads 4.0
# HELP request_latency_seconds Time taken to process requests.
# TYPE request_latency_seconds histogram
request_latency_seconds_bucket{le="0.005"} 0
request_latency_seconds_bucket{le="0.01"} 0
request_latency_seconds_bucket{le="0.025"} 0
request_latency_seconds_bucket{le="0.05"} 15
...
request_latency_seconds_bucket{le="+Inf"} 45
request_latency_seconds_sum 5.849999999999999
request_latency_seconds_count 45
Key Concepts Implemented
-
Thread Safety (threading.Lock):
In a real application, metrics are often written by worker threads and read by an HTTP server thread. Without locks, you might encounter race conditions where data is corrupted.
-
Counter vs. Gauge:
- Counter: Notice the
inc method. It throws an error if you try to decrease it. This is because a counter represents accumulation (like total miles driven).
- Gauge: Allows
inc, dec, and set. This represents a state (like current speed).
-
Histogram Aggregation:
The Histogram doesn't just store the average; it stores buckets. This allows you to calculate percentiles (e.g., "95% of requests finished in under 200ms"). Notice that the counts are cumulative (if you are in the 0.1s bucket, you are also in the +Inf bucket).