| 1 |
""" |
| 2 |
Producer benchmark metrics collection and validation for Kafka performance testing. |
| 3 |
|
| 4 |
Implements comprehensive metrics tracking including latency percentiles, |
| 5 |
per-topic/partition breakdowns, memory monitoring, and batch efficiency analysis. |
| 6 |
""" |
| 7 |
import time |
| 8 |
import statistics |
| 9 |
import os |
| 10 |
import json |
| 11 |
from typing import List, Dict, Any, Optional |
| 12 |
from collections import defaultdict |
| 13 |
import psutil |
| 14 |
|
| 15 |
|
| 16 |
class MetricsCollector: |
| 17 |
"""Collects comprehensive performance metrics for producer testing.""" |
| 18 |
|
| 19 |
def __init__(self): |
| 20 |
|
| 21 |
self.start_time = None |
| 22 |
self.end_time = None |
| 23 |
|
| 24 |
|
| 25 |
self.messages_sent = 0 |
| 26 |
self.messages_delivered = 0 |
| 27 |
self.messages_failed = 0 |
| 28 |
self.delivery_latencies = [] |
| 29 |
|
| 30 |
|
| 31 |
self.total_bytes = 0 |
| 32 |
self.message_sizes = [] |
| 33 |
|
| 34 |
|
| 35 |
self.topic_metrics = defaultdict(lambda: { |
| 36 |
'sent': 0, 'delivered': 0, 'failed': 0, 'bytes': 0, 'latencies': [] |
| 37 |
}) |
| 38 |
self.partition_metrics = defaultdict(lambda: { |
| 39 |
'sent': 0, 'delivered': 0, 'failed': 0, 'bytes': 0, 'latencies': [] |
| 40 |
}) |
| 41 |
|
| 42 |
|
| 43 |
self.initial_memory_mb = None |
| 44 |
self.peak_memory_mb = 0 |
| 45 |
|
| 46 |
|
| 47 |
self.poll_count = 0 |
| 48 |
self.buffer_full_count = 0 |
| 49 |
|
| 50 |
|
| 51 |
self._process = None |
| 52 |
|
| 53 |
def start(self): |
| 54 |
"""Start metrics collection""" |
| 55 |
self.start_time = time.time() |
| 56 |
self.initial_memory_mb = self._get_memory_usage() |
| 57 |
|
| 58 |
def record_sent(self, message_size: int, topic: str = "unknown", partition: int = 0): |
| 59 |
"""Record a message being sent""" |
| 60 |
self.messages_sent += 1 |
| 61 |
self.total_bytes += message_size |
| 62 |
self.message_sizes.append(message_size) |
| 63 |
|
| 64 |
|
| 65 |
self.topic_metrics[topic]['sent'] += 1 |
| 66 |
self.topic_metrics[topic]['bytes'] += message_size |
| 67 |
|
| 68 |
partition_key = f"{topic}-{partition}" |
| 69 |
self.partition_metrics[partition_key]['sent'] += 1 |
| 70 |
self.partition_metrics[partition_key]['bytes'] += message_size |
| 71 |
|
| 72 |
def record_delivered(self, latency_ms: float, topic: str = "unknown", partition: int = 0): |
| 73 |
"""Record a message being delivered""" |
| 74 |
self.messages_delivered += 1 |
| 75 |
self.delivery_latencies.append(latency_ms) |
| 76 |
|
| 77 |
|
| 78 |
self.topic_metrics[topic]['delivered'] += 1 |
| 79 |
self.topic_metrics[topic]['latencies'].append(latency_ms) |
| 80 |
|
| 81 |
partition_key = f"{topic}-{partition}" |
| 82 |
self.partition_metrics[partition_key]['delivered'] += 1 |
| 83 |
self.partition_metrics[partition_key]['latencies'].append(latency_ms) |
| 84 |
|
| 85 |
def record_failed(self, topic: str = "unknown", partition: int = 0): |
| 86 |
"""Record a message delivery failure""" |
| 87 |
self.messages_failed += 1 |
| 88 |
|
| 89 |
|
| 90 |
self.topic_metrics[topic]['failed'] += 1 |
| 91 |
|
| 92 |
partition_key = f"{topic}-{partition}" |
| 93 |
self.partition_metrics[partition_key]['failed'] += 1 |
| 94 |
|
| 95 |
def record_poll(self): |
| 96 |
"""Record a producer poll operation for batch efficiency tracking""" |
| 97 |
self.poll_count += 1 |
| 98 |
|
| 99 |
|
| 100 |
current_memory = self._get_memory_usage() |
| 101 |
if current_memory and current_memory > self.peak_memory_mb: |
| 102 |
self.peak_memory_mb = current_memory |
| 103 |
|
| 104 |
def record_buffer_full(self): |
| 105 |
"""Record a buffer full event for batch efficiency tracking""" |
| 106 |
self.buffer_full_count += 1 |
| 107 |
|
| 108 |
def finalize(self): |
| 109 |
"""Finalize metrics collection""" |
| 110 |
self.end_time = time.time() |
| 111 |
|
| 112 |
def get_summary(self) -> Dict[str, Any]: |
| 113 |
"""Get comprehensive metrics summary""" |
| 114 |
if not self.start_time or not self.end_time: |
| 115 |
return {} |
| 116 |
|
| 117 |
duration = self.end_time - self.start_time |
| 118 |
|
| 119 |
|
| 120 |
send_throughput = self.messages_sent / duration if duration > 0 else 0 |
| 121 |
delivery_throughput = self.messages_delivered / duration if duration > 0 else 0 |
| 122 |
data_throughput_mb = (self.total_bytes / (1024 * 1024)) / duration if duration > 0 else 0 |
| 123 |
|
| 124 |
|
| 125 |
if self.delivery_latencies: |
| 126 |
avg_latency = statistics.mean(self.delivery_latencies) |
| 127 |
p50_latency = statistics.median(self.delivery_latencies) |
| 128 |
max_latency = max(self.delivery_latencies) |
| 129 |
|
| 130 |
|
| 131 |
try: |
| 132 |
quantiles = statistics.quantiles(self.delivery_latencies, n=100) |
| 133 |
p95_latency = quantiles[94] |
| 134 |
p99_latency = quantiles[98] |
| 135 |
except statistics.StatisticsError: |
| 136 |
|
| 137 |
p95_latency = self._percentile(self.delivery_latencies, 95) |
| 138 |
p99_latency = self._percentile(self.delivery_latencies, 99) |
| 139 |
else: |
| 140 |
avg_latency = p50_latency = p95_latency = p99_latency = max_latency = 0 |
| 141 |
|
| 142 |
|
| 143 |
total_attempts = self.messages_sent |
| 144 |
error_rate = self.messages_failed / total_attempts if total_attempts > 0 else 0 |
| 145 |
success_rate = self.messages_delivered / total_attempts if total_attempts > 0 else 0 |
| 146 |
|
| 147 |
|
| 148 |
if self.message_sizes: |
| 149 |
avg_message_size = statistics.mean(self.message_sizes) |
| 150 |
min_message_size = min(self.message_sizes) |
| 151 |
max_message_size = max(self.message_sizes) |
| 152 |
median_message_size = statistics.median(self.message_sizes) |
| 153 |
else: |
| 154 |
avg_message_size = min_message_size = max_message_size = median_message_size = 0 |
| 155 |
|
| 156 |
|
| 157 |
memory_growth_mb = 0 |
| 158 |
if self.initial_memory_mb and self.peak_memory_mb: |
| 159 |
memory_growth_mb = self.peak_memory_mb - self.initial_memory_mb |
| 160 |
|
| 161 |
|
| 162 |
messages_per_poll = self.messages_delivered / self.poll_count if self.poll_count > 0 else 0 |
| 163 |
buffer_full_rate = self.buffer_full_count / self.messages_sent if self.messages_sent > 0 else 0 |
| 164 |
|
| 165 |
|
| 166 |
topic_summary = {} |
| 167 |
for topic, metrics in self.topic_metrics.items(): |
| 168 |
if metrics['sent'] > 0: |
| 169 |
topic_summary[topic] = { |
| 170 |
'messages_sent': metrics['sent'], |
| 171 |
'messages_delivered': metrics['delivered'], |
| 172 |
'success_rate': metrics['delivered'] / metrics['sent'], |
| 173 |
'avg_latency_ms': statistics.mean(metrics['latencies']) if metrics['latencies'] else 0, |
| 174 |
'total_bytes': metrics['bytes'] |
| 175 |
} |
| 176 |
|
| 177 |
|
| 178 |
partition_summary = {} |
| 179 |
for partition_key, metrics in self.partition_metrics.items(): |
| 180 |
if metrics['sent'] > 0: |
| 181 |
partition_summary[partition_key] = { |
| 182 |
'messages_sent': metrics['sent'], |
| 183 |
'messages_delivered': metrics['delivered'], |
| 184 |
'success_rate': metrics['delivered'] / metrics['sent'], |
| 185 |
'avg_latency_ms': statistics.mean(metrics['latencies']) if metrics['latencies'] else 0, |
| 186 |
'total_bytes': metrics['bytes'] |
| 187 |
} |
| 188 |
|
| 189 |
return { |
| 190 |
|
| 191 |
'duration_seconds': duration, |
| 192 |
'messages_sent': self.messages_sent, |
| 193 |
'messages_delivered': self.messages_delivered, |
| 194 |
'messages_failed': self.messages_failed, |
| 195 |
'send_throughput_msg_per_sec': send_throughput, |
| 196 |
'delivery_throughput_msg_per_sec': delivery_throughput, |
| 197 |
'data_throughput_mb_per_sec': data_throughput_mb, |
| 198 |
'avg_latency_ms': avg_latency, |
| 199 |
'p95_latency_ms': p95_latency, |
| 200 |
'max_latency_ms': max_latency, |
| 201 |
'error_rate': error_rate, |
| 202 |
'success_rate': success_rate, |
| 203 |
'total_bytes': self.total_bytes, |
| 204 |
|
| 205 |
|
| 206 |
'p50_latency_ms': p50_latency, |
| 207 |
'p99_latency_ms': p99_latency, |
| 208 |
'avg_message_size_bytes': avg_message_size, |
| 209 |
'median_message_size_bytes': median_message_size, |
| 210 |
'min_message_size_bytes': min_message_size, |
| 211 |
'max_message_size_bytes': max_message_size, |
| 212 |
'memory_growth_mb': memory_growth_mb, |
| 213 |
'peak_memory_mb': self.peak_memory_mb, |
| 214 |
'messages_per_poll': messages_per_poll, |
| 215 |
'buffer_full_rate': buffer_full_rate, |
| 216 |
'poll_count': self.poll_count, |
| 217 |
'buffer_full_count': self.buffer_full_count, |
| 218 |
'topic_metrics': topic_summary, |
| 219 |
'partition_metrics': partition_summary |
| 220 |
} |
| 221 |
|
| 222 |
def _percentile(self, data: List[float], percentile: float) -> float: |
| 223 |
"""Calculate percentile of a dataset""" |
| 224 |
if not data: |
| 225 |
return 0.0 |
| 226 |
sorted_data = sorted(data) |
| 227 |
index = (percentile / 100) * (len(sorted_data) - 1) |
| 228 |
if index.is_integer(): |
| 229 |
return sorted_data[int(index)] |
| 230 |
else: |
| 231 |
lower = sorted_data[int(index)] |
| 232 |
upper = sorted_data[int(index) + 1] |
| 233 |
return lower + (upper - lower) * (index - int(index)) |
| 234 |
|
| 235 |
def _get_memory_usage(self) -> Optional[float]: |
| 236 |
"""Get current memory usage in MB""" |
| 237 |
try: |
| 238 |
|
| 239 |
if self._process is None: |
| 240 |
self._process = psutil.Process(os.getpid()) |
| 241 |
|
| 242 |
return self._process.memory_info().rss / (1024 * 1024) |
| 243 |
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): |
| 244 |
|
| 245 |
return None |
| 246 |
|
| 247 |
|
| 248 |
class MetricsBounds: |
| 249 |
"""Performance bounds for metrics validation""" |
| 250 |
|
| 251 |
def __init__(self): |
| 252 |
|
| 253 |
config_path = os.getenv("BENCHMARK_BOUNDS_CONFIG") |
| 254 |
if config_path is None: |
| 255 |
|
| 256 |
config_path = os.path.join(os.path.dirname(__file__), "producer_benchmark_bounds.json") |
| 257 |
self._load_from_config_file(config_path) |
| 258 |
|
| 259 |
def _load_from_config_file(self, config_path: str): |
| 260 |
"""Load bounds from a JSON configuration file.""" |
| 261 |
if not os.path.exists(config_path): |
| 262 |
raise FileNotFoundError(f"Config file not found: {config_path}") |
| 263 |
|
| 264 |
try: |
| 265 |
with open(config_path, 'r') as f: |
| 266 |
config = json.load(f) |
| 267 |
|
| 268 |
|
| 269 |
environment = os.getenv('BENCHMARK_ENVIRONMENT', |
| 270 |
config.get('_default_environment', 'local')) |
| 271 |
if environment not in config: |
| 272 |
available_envs = [k for k in config.keys() if not k.startswith('_')] |
| 273 |
raise ValueError( |
| 274 |
f"Environment '{environment}' not found in config. " |
| 275 |
f"Available environments: {available_envs}" |
| 276 |
) |
| 277 |
bounds_config = config[environment] |
| 278 |
print(f"Loading benchmark bounds for environment: {environment}") |
| 279 |
|
| 280 |
|
| 281 |
for key, value in bounds_config.items(): |
| 282 |
if not key.startswith('_'): |
| 283 |
setattr(self, key, value) |
| 284 |
|
| 285 |
except json.JSONDecodeError as e: |
| 286 |
raise ValueError(f"Invalid JSON in config file {config_path}: {e}") |
| 287 |
except IOError as e: |
| 288 |
raise IOError(f"Failed to read config file {config_path}: {e}") |
| 289 |
|
| 290 |
@classmethod |
| 291 |
def from_config_file(cls, config_path: str) -> 'MetricsBounds': |
| 292 |
"""Load bounds from a specific JSON configuration file.""" |
| 293 |
bounds = cls.__new__(cls) |
| 294 |
bounds._load_from_config_file(config_path) |
| 295 |
return bounds |
| 296 |
|
| 297 |
|
| 298 |
def validate_metrics(metrics: Dict[str, Any], bounds: MetricsBounds) -> tuple: |
| 299 |
""" |
| 300 |
Validate metrics against performance bounds. |
| 301 |
|
| 302 |
Returns: |
| 303 |
tuple: (is_valid, list_of_violations) |
| 304 |
""" |
| 305 |
violations = [] |
| 306 |
|
| 307 |
|
| 308 |
if metrics['send_throughput_msg_per_sec'] < bounds.min_throughput_msg_per_sec: |
| 309 |
violations.append( |
| 310 |
f"Throughput too low: {metrics['send_throughput_msg_per_sec']:.2f} msg/s " |
| 311 |
f"(minimum: {bounds.min_throughput_msg_per_sec})" |
| 312 |
) |
| 313 |
|
| 314 |
if metrics['p95_latency_ms'] > bounds.max_p95_latency_ms: |
| 315 |
violations.append( |
| 316 |
f"P95 latency too high: {metrics['p95_latency_ms']:.2f}ms " |
| 317 |
f"(maximum: {bounds.max_p95_latency_ms}ms)" |
| 318 |
) |
| 319 |
|
| 320 |
if metrics['error_rate'] > bounds.max_error_rate: |
| 321 |
violations.append( |
| 322 |
f"Error rate too high: {metrics['error_rate']:.4f} " |
| 323 |
f"(maximum: {bounds.max_error_rate})" |
| 324 |
) |
| 325 |
|
| 326 |
if metrics['success_rate'] < bounds.min_success_rate: |
| 327 |
violations.append( |
| 328 |
f"Success rate too low: {metrics['success_rate']:.4f} " |
| 329 |
f"(minimum: {bounds.min_success_rate})" |
| 330 |
) |
| 331 |
|
| 332 |
|
| 333 |
if metrics['p99_latency_ms'] > bounds.max_p99_latency_ms: |
| 334 |
violations.append( |
| 335 |
f"P99 latency too high: {metrics['p99_latency_ms']:.2f}ms " |
| 336 |
f"(maximum: {bounds.max_p99_latency_ms}ms)" |
| 337 |
) |
| 338 |
|
| 339 |
if metrics['memory_growth_mb'] > bounds.max_memory_growth_mb: |
| 340 |
violations.append( |
| 341 |
f"Memory growth too high: {metrics['memory_growth_mb']:.2f}MB " |
| 342 |
f"(maximum: {bounds.max_memory_growth_mb}MB)" |
| 343 |
) |
| 344 |
|
| 345 |
if metrics['buffer_full_rate'] > bounds.max_buffer_full_rate: |
| 346 |
violations.append( |
| 347 |
f"Buffer full rate too high: {metrics['buffer_full_rate']:.3f} " |
| 348 |
f"(maximum: {bounds.max_buffer_full_rate})" |
| 349 |
) |
| 350 |
|
| 351 |
if metrics['messages_per_poll'] < bounds.min_messages_per_poll: |
| 352 |
violations.append( |
| 353 |
f"Batch efficiency too low: {metrics['messages_per_poll']:.2f} messages/poll " |
| 354 |
f"(minimum: {bounds.min_messages_per_poll})" |
| 355 |
) |
| 356 |
|
| 357 |
return len(violations) == 0, violations |
| 358 |
|
| 359 |
|
| 360 |
def print_metrics_report(metrics: Dict[str, Any], is_valid: bool, violations: List[str]): |
| 361 |
"""Print comprehensive metrics report""" |
| 362 |
print("\n=== Performance Metrics Report ===") |
| 363 |
|
| 364 |
|
| 365 |
print(f"Duration: {metrics['duration_seconds']:.2f}s") |
| 366 |
print(f"Messages sent: {metrics['messages_sent']}") |
| 367 |
print(f"Messages delivered: {metrics['messages_delivered']}") |
| 368 |
print(f"Send throughput: {metrics['send_throughput_msg_per_sec']:.2f} msg/s") |
| 369 |
print(f"Data throughput: {metrics['data_throughput_mb_per_sec']:.2f} MB/s") |
| 370 |
|
| 371 |
|
| 372 |
print("\nLatency Metrics:") |
| 373 |
print(f" Average: {metrics['avg_latency_ms']:.2f}ms") |
| 374 |
print(f" P50: {metrics['p50_latency_ms']:.2f}ms") |
| 375 |
print(f" P95: {metrics['p95_latency_ms']:.2f}ms") |
| 376 |
print(f" P99: {metrics['p99_latency_ms']:.2f}ms") |
| 377 |
print(f" Max: {metrics['max_latency_ms']:.2f}ms") |
| 378 |
|
| 379 |
|
| 380 |
print("\nReliability:") |
| 381 |
print(f" Success rate: {metrics['success_rate']:.4f}") |
| 382 |
print(f" Error rate: {metrics['error_rate']:.4f}") |
| 383 |
|
| 384 |
|
| 385 |
print("\nMessage Size Analysis:") |
| 386 |
print(f" Average: {metrics['avg_message_size_bytes']:.0f} bytes") |
| 387 |
print(f" Median: {metrics['median_message_size_bytes']:.0f} bytes") |
| 388 |
print(f" Range: {metrics['min_message_size_bytes']:.0f} - {metrics['max_message_size_bytes']:.0f} bytes") |
| 389 |
|
| 390 |
|
| 391 |
if metrics['peak_memory_mb'] > 0: |
| 392 |
print("\nMemory Usage:") |
| 393 |
print(f" Peak: {metrics['peak_memory_mb']:.2f}MB") |
| 394 |
print(f" Growth: {metrics['memory_growth_mb']:.2f}MB") |
| 395 |
|
| 396 |
|
| 397 |
print("\nBatch Efficiency:") |
| 398 |
print(f" Messages per poll: {metrics['messages_per_poll']:.2f}") |
| 399 |
print(f" Buffer full rate: {metrics['buffer_full_rate']:.3f}") |
| 400 |
print(f" Total polls: {metrics['poll_count']}") |
| 401 |
|
| 402 |
|
| 403 |
if len(metrics['topic_metrics']) > 1: |
| 404 |
print("\nPer-Topic Metrics:") |
| 405 |
for topic, topic_metrics in metrics['topic_metrics'].items(): |
| 406 |
print(f" {topic}: {topic_metrics['messages_delivered']} msgs, " |
| 407 |
f"{topic_metrics['success_rate']:.3f} success rate, " |
| 408 |
f"{topic_metrics['avg_latency_ms']:.2f}ms avg latency") |
| 409 |
|
| 410 |
|
| 411 |
if len(metrics['partition_metrics']) > 1: |
| 412 |
print("\nPer-Partition Metrics:") |
| 413 |
for partition, partition_metrics in metrics['partition_metrics'].items(): |
| 414 |
print(f" {partition}: {partition_metrics['messages_delivered']} msgs, " |
| 415 |
f"{partition_metrics['success_rate']:.3f} success rate") |
| 416 |
|
| 417 |
|
| 418 |
print(f"\nValidation: {'PASS' if is_valid else 'FAIL'}") |
| 419 |
if violations: |
| 420 |
print("Violations:") |
| 421 |
for violation in violations: |
| 422 |
print(f" - {violation}") |
| 423 |
|
| 424 |
print("=" * 55) |