| 1 |
""" |
| 2 |
Consumer benchmark metrics collection and validation for Kafka performance testing. |
| 3 |
|
| 4 |
Implements consumer-specific metrics tracking including poll latencies, |
| 5 |
consumption rates, per-topic breakdowns, and reliability analysis. |
| 6 |
""" |
| 7 |
import time |
| 8 |
import statistics |
| 9 |
from typing import List, Dict, Any |
| 10 |
from collections import defaultdict |
| 11 |
import psutil |
| 12 |
|
| 13 |
|
| 14 |
class ConsumerMetricsCollector: |
| 15 |
"""Collects comprehensive performance metrics for consumer testing.""" |
| 16 |
|
| 17 |
def __init__(self, operation_type: str = "poll", serialization_type: str = None): |
| 18 |
|
| 19 |
self.start_time = None |
| 20 |
self.end_time = None |
| 21 |
|
| 22 |
|
| 23 |
self.operation_type = operation_type |
| 24 |
self.serialization_type = serialization_type |
| 25 |
|
| 26 |
|
| 27 |
self.messages_consumed = 0 |
| 28 |
self.operation_attempts = 0 |
| 29 |
self.operation_timeouts = 0 |
| 30 |
self.operation_errors = 0 |
| 31 |
self.operation_latencies = [] |
| 32 |
self.error_messages = [] |
| 33 |
|
| 34 |
|
| 35 |
self.total_bytes = 0 |
| 36 |
self.message_sizes = [] |
| 37 |
|
| 38 |
|
| 39 |
self.offsets_consumed = defaultdict(dict) |
| 40 |
|
| 41 |
|
| 42 |
self.initial_memory_mb = None |
| 43 |
self.peak_memory_mb = 0 |
| 44 |
|
| 45 |
|
| 46 |
self.consume_call_count = 0 |
| 47 |
self.empty_consume_count = 0 |
| 48 |
|
| 49 |
|
| 50 |
self._process = None |
| 51 |
|
| 52 |
def start(self): |
| 53 |
"""Start metrics collection""" |
| 54 |
self.start_time = time.time() |
| 55 |
self.initial_memory_mb = self._get_memory_usage() |
| 56 |
|
| 57 |
def record_api_call(self, operation_latency_ms: float): |
| 58 |
"""Record a consumer API call (poll or consume) with its latency""" |
| 59 |
self.operation_attempts += 1 |
| 60 |
self.operation_latencies.append(operation_latency_ms) |
| 61 |
|
| 62 |
def record_timeout(self, topic: str = "unknown"): |
| 63 |
"""Record a consumer operation timeout""" |
| 64 |
self.operation_timeouts += 1 |
| 65 |
|
| 66 |
def record_error(self, error_msg: str, topic: str = "unknown"): |
| 67 |
"""Record a consumer error""" |
| 68 |
self.operation_errors += 1 |
| 69 |
self.error_messages.append(error_msg) |
| 70 |
|
| 71 |
def record_processed_message(self, message_size: int, topic: str, partition: int, |
| 72 |
offset: int, operation_latency_ms: float): |
| 73 |
"""Record a successfully processed message""" |
| 74 |
self.messages_consumed += 1 |
| 75 |
self.total_bytes += message_size |
| 76 |
self.message_sizes.append(message_size) |
| 77 |
|
| 78 |
|
| 79 |
self.offsets_consumed[topic][partition] = offset |
| 80 |
|
| 81 |
|
| 82 |
self._update_memory_usage() |
| 83 |
|
| 84 |
def finalize(self): |
| 85 |
"""Finalize metrics collection""" |
| 86 |
self.end_time = time.time() |
| 87 |
|
| 88 |
def record_batch_operation(self, messages_returned: int): |
| 89 |
"""Record a batch operation (consume() call) and how many messages it returned""" |
| 90 |
self.consume_call_count += 1 |
| 91 |
if messages_returned == 0: |
| 92 |
self.empty_consume_count += 1 |
| 93 |
|
| 94 |
def _get_memory_usage(self) -> float: |
| 95 |
"""Get current memory usage in MB""" |
| 96 |
if psutil is None: |
| 97 |
return 0.0 |
| 98 |
try: |
| 99 |
if self._process is None: |
| 100 |
self._process = psutil.Process() |
| 101 |
return self._process.memory_info().rss / (1024 * 1024) |
| 102 |
except (psutil.Error, OSError): |
| 103 |
return 0.0 |
| 104 |
|
| 105 |
def _update_memory_usage(self): |
| 106 |
"""Update peak memory usage""" |
| 107 |
current_memory = self._get_memory_usage() |
| 108 |
if current_memory > self.peak_memory_mb: |
| 109 |
self.peak_memory_mb = current_memory |
| 110 |
|
| 111 |
def _percentile(self, data, percentile): |
| 112 |
"""Calculate percentile for datasets where quantiles() fails""" |
| 113 |
if not data: |
| 114 |
return 0 |
| 115 |
sorted_data = sorted(data) |
| 116 |
k = (len(sorted_data) - 1) * percentile / 100.0 |
| 117 |
f = int(k) |
| 118 |
c = k - f |
| 119 |
if f == len(sorted_data) - 1: |
| 120 |
return sorted_data[f] |
| 121 |
return sorted_data[f] * (1 - c) + sorted_data[f + 1] * c |
| 122 |
|
| 123 |
def get_summary(self) -> Dict[str, Any]: |
| 124 |
"""Get consumer-specific metrics summary""" |
| 125 |
if not self.start_time or not self.end_time: |
| 126 |
return {} |
| 127 |
|
| 128 |
duration = self.end_time - self.start_time |
| 129 |
|
| 130 |
|
| 131 |
consumption_rate = self.messages_consumed / duration if duration > 0 else 0 |
| 132 |
operation_rate = self.operation_attempts / duration if duration > 0 else 0 |
| 133 |
|
| 134 |
|
| 135 |
operation_error_rate = (self.operation_errors / self.operation_attempts |
| 136 |
if self.operation_attempts > 0 else 0) |
| 137 |
operation_success_rate = ((self.operation_attempts - self.operation_timeouts - |
| 138 |
self.operation_errors) / self.operation_attempts |
| 139 |
if self.operation_attempts > 0 else 0) |
| 140 |
|
| 141 |
|
| 142 |
if self.operation_latencies: |
| 143 |
avg_operation_latency = statistics.mean(self.operation_latencies) |
| 144 |
p50_operation_latency = statistics.median(self.operation_latencies) |
| 145 |
max_operation_latency = max(self.operation_latencies) |
| 146 |
|
| 147 |
try: |
| 148 |
quantiles = statistics.quantiles(self.operation_latencies, n=100) |
| 149 |
p95_operation_latency = quantiles[94] |
| 150 |
p99_operation_latency = quantiles[98] |
| 151 |
except statistics.StatisticsError: |
| 152 |
p95_operation_latency = self._percentile(self.operation_latencies, 95) |
| 153 |
p99_operation_latency = self._percentile(self.operation_latencies, 99) |
| 154 |
else: |
| 155 |
avg_operation_latency = p50_operation_latency = p95_operation_latency = ( |
| 156 |
p99_operation_latency) = max_operation_latency = 0 |
| 157 |
|
| 158 |
|
| 159 |
if self.message_sizes: |
| 160 |
avg_message_size = statistics.mean(self.message_sizes) |
| 161 |
min_message_size = min(self.message_sizes) |
| 162 |
max_message_size = max(self.message_sizes) |
| 163 |
median_message_size = statistics.median(self.message_sizes) |
| 164 |
else: |
| 165 |
avg_message_size = min_message_size = max_message_size = median_message_size = 0 |
| 166 |
|
| 167 |
|
| 168 |
memory_growth_mb = 0 |
| 169 |
if self.initial_memory_mb and self.peak_memory_mb: |
| 170 |
memory_growth_mb = self.peak_memory_mb - self.initial_memory_mb |
| 171 |
|
| 172 |
|
| 173 |
messages_per_consume = self.messages_consumed / self.consume_call_count if self.consume_call_count > 0 else 0 |
| 174 |
empty_consume_rate = self.empty_consume_count / self.consume_call_count if self.consume_call_count > 0 else 0 |
| 175 |
|
| 176 |
|
| 177 |
base_summary = { |
| 178 |
'start_time': self.start_time, |
| 179 |
'end_time': self.end_time, |
| 180 |
'duration_seconds': duration |
| 181 |
} |
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
op_name = self.operation_type |
| 186 |
|
| 187 |
consumer_metrics = { |
| 188 |
|
| 189 |
'messages_consumed': self.messages_consumed, |
| 190 |
'consumption_rate_msg_per_sec': consumption_rate, |
| 191 |
'data_throughput_mb_per_sec': (self.total_bytes / (1024 * 1024)) / duration if duration > 0 else 0, |
| 192 |
'avg_latency_ms': avg_operation_latency, |
| 193 |
'p50_latency_ms': p50_operation_latency, |
| 194 |
'p95_latency_ms': p95_operation_latency, |
| 195 |
'p99_latency_ms': p99_operation_latency, |
| 196 |
'max_latency_ms': max_operation_latency, |
| 197 |
'error_rate': operation_error_rate, |
| 198 |
'success_rate': operation_success_rate, |
| 199 |
'total_bytes': self.total_bytes, |
| 200 |
|
| 201 |
|
| 202 |
'avg_message_size_bytes': avg_message_size, |
| 203 |
'median_message_size_bytes': median_message_size, |
| 204 |
'min_message_size_bytes': min_message_size, |
| 205 |
'max_message_size_bytes': max_message_size, |
| 206 |
'memory_growth_mb': memory_growth_mb, |
| 207 |
'peak_memory_mb': self.peak_memory_mb, |
| 208 |
|
| 209 |
|
| 210 |
f'{op_name}_attempts': self.operation_attempts, |
| 211 |
f'{op_name}_rate_per_sec': operation_rate, |
| 212 |
f'{op_name}_timeouts': self.operation_timeouts, |
| 213 |
f'{op_name}_errors': self.operation_errors, |
| 214 |
f'messages_per_{op_name}': messages_per_consume, |
| 215 |
f'empty_{op_name}_rate': empty_consume_rate, |
| 216 |
f'{op_name}_call_count': self.consume_call_count, |
| 217 |
f'empty_{op_name}_count': self.empty_consume_count, |
| 218 |
} |
| 219 |
|
| 220 |
base_summary.update(consumer_metrics) |
| 221 |
return base_summary |
| 222 |
|
| 223 |
|
| 224 |
class ConsumerMetricsBounds: |
| 225 |
"""Performance bounds for consumer metrics validation""" |
| 226 |
|
| 227 |
def __init__(self, |
| 228 |
min_consumption_rate: float = 1.0, |
| 229 |
max_avg_latency_ms: float = 5000.0, |
| 230 |
max_p95_latency_ms: float = 10000.0, |
| 231 |
min_success_rate: float = 0.90, |
| 232 |
max_error_rate: float = 0.05, |
| 233 |
max_memory_growth_mb: float = 600.0, |
| 234 |
min_messages_per_consume: float = 0.5, |
| 235 |
max_empty_consume_rate: float = 0.5): |
| 236 |
self.min_consumption_rate = min_consumption_rate |
| 237 |
self.max_avg_latency_ms = max_avg_latency_ms |
| 238 |
self.max_p95_latency_ms = max_p95_latency_ms |
| 239 |
self.min_success_rate = min_success_rate |
| 240 |
self.max_error_rate = max_error_rate |
| 241 |
|
| 242 |
self.max_memory_growth_mb = max_memory_growth_mb |
| 243 |
self.min_messages_per_consume = min_messages_per_consume |
| 244 |
self.max_empty_consume_rate = max_empty_consume_rate |
| 245 |
|
| 246 |
|
| 247 |
def validate_consumer_metrics(metrics: Dict[str, Any], bounds: ConsumerMetricsBounds) -> tuple[bool, List[str]]: |
| 248 |
"""Validate consumer metrics against performance bounds""" |
| 249 |
violations = [] |
| 250 |
|
| 251 |
|
| 252 |
consumption_rate = metrics.get('consumption_rate_msg_per_sec', 0) |
| 253 |
if consumption_rate < bounds.min_consumption_rate: |
| 254 |
violations.append(f"Consumption rate {consumption_rate:.2f} msg/s below minimum {bounds.min_consumption_rate}") |
| 255 |
|
| 256 |
|
| 257 |
avg_latency = metrics.get('avg_latency_ms', 0) |
| 258 |
if avg_latency > bounds.max_avg_latency_ms: |
| 259 |
violations.append(f"Average latency {avg_latency:.2f}ms exceeds maximum {bounds.max_avg_latency_ms}ms") |
| 260 |
|
| 261 |
p95_latency = metrics.get('p95_latency_ms', 0) |
| 262 |
if p95_latency > bounds.max_p95_latency_ms: |
| 263 |
violations.append(f"P95 latency {p95_latency:.2f}ms exceeds maximum {bounds.max_p95_latency_ms}ms") |
| 264 |
|
| 265 |
|
| 266 |
success_rate = metrics.get('success_rate', 0) |
| 267 |
if success_rate < bounds.min_success_rate: |
| 268 |
violations.append(f"Success rate {success_rate:.4f} below minimum {bounds.min_success_rate}") |
| 269 |
|
| 270 |
|
| 271 |
error_rate = metrics.get('error_rate', 0) |
| 272 |
if error_rate > bounds.max_error_rate: |
| 273 |
violations.append(f"Error rate {error_rate:.4f} exceeds maximum {bounds.max_error_rate}") |
| 274 |
|
| 275 |
|
| 276 |
memory_growth = metrics.get('memory_growth_mb', 0) |
| 277 |
if memory_growth > bounds.max_memory_growth_mb: |
| 278 |
violations.append(f"Memory growth {memory_growth:.2f}MB exceeds maximum {bounds.max_memory_growth_mb}MB") |
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
if 'messages_per_consume' in metrics: |
| 283 |
messages_per_consume = metrics.get('messages_per_consume', 0) |
| 284 |
if messages_per_consume < bounds.min_messages_per_consume: |
| 285 |
violations.append(f"Messages per consume {messages_per_consume:.2f} " |
| 286 |
f"below minimum {bounds.min_messages_per_consume}") |
| 287 |
|
| 288 |
empty_consume_rate = metrics.get('empty_consume_rate', 0) |
| 289 |
if empty_consume_rate > bounds.max_empty_consume_rate: |
| 290 |
violations.append(f"Empty consume rate {empty_consume_rate:.3f} " |
| 291 |
f"exceeds maximum {bounds.max_empty_consume_rate}") |
| 292 |
|
| 293 |
|
| 294 |
is_valid = len(violations) == 0 |
| 295 |
return is_valid, violations |
| 296 |
|
| 297 |
|
| 298 |
def print_consumer_metrics_report(metrics: Dict[str, Any], is_valid: bool, violations: List[str], |
| 299 |
consumer_type: str = None, batch_size: int = None, serialization_type: str = None): |
| 300 |
"""Print simplified consumer metrics report""" |
| 301 |
|
| 302 |
op_name = "consume" |
| 303 |
if any(key.startswith('poll_') for key in metrics.keys()): |
| 304 |
op_name = "poll" |
| 305 |
|
| 306 |
|
| 307 |
header_parts = ["Consumer Performance Report"] |
| 308 |
if consumer_type: |
| 309 |
header_parts.append(f"{consumer_type.upper()}") |
| 310 |
if op_name == "consume" and batch_size is not None: |
| 311 |
header_parts.append(f"{op_name.upper()}(batch_size={batch_size})") |
| 312 |
if serialization_type: |
| 313 |
header_parts.append(f"serialization_type={serialization_type}") |
| 314 |
else: |
| 315 |
header_parts.append(f"{op_name.upper()}()") |
| 316 |
|
| 317 |
header = " - ".join(header_parts) |
| 318 |
print(f"\n=== {header} ===") |
| 319 |
|
| 320 |
|
| 321 |
print(f"Duration: {metrics.get('duration_seconds', 0):.2f}s") |
| 322 |
print(f"Messages consumed: {metrics.get('messages_consumed', 0)}") |
| 323 |
print(f"Consumption throughput: {metrics.get('consumption_rate_msg_per_sec', 0):.2f} msg/s") |
| 324 |
print(f"Data throughput: {metrics.get('data_throughput_mb_per_sec', 0):.4f} MB/s") |
| 325 |
|
| 326 |
|
| 327 |
print("\nLatency Metrics:") |
| 328 |
print(f" Average: {metrics.get('avg_latency_ms', 0):.2f}ms") |
| 329 |
print(f" P50: {metrics.get('p50_latency_ms', 0):.2f}ms") |
| 330 |
print(f" P95: {metrics.get('p95_latency_ms', 0):.2f}ms") |
| 331 |
print(f" P99: {metrics.get('p99_latency_ms', 0):.2f}ms") |
| 332 |
print(f" Max: {metrics.get('max_latency_ms', 0):.2f}ms") |
| 333 |
|
| 334 |
|
| 335 |
print("\nReliability:") |
| 336 |
print(f" Error rate: {metrics.get('error_rate', 0):.4f}") |
| 337 |
|
| 338 |
|
| 339 |
print("\nMessage Size Analysis:") |
| 340 |
print(f" Average: {metrics.get('avg_message_size_bytes', 0):.0f} bytes") |
| 341 |
print(f" Median: {metrics.get('median_message_size_bytes', 0):.0f} bytes") |
| 342 |
print(f" Range: {metrics.get('min_message_size_bytes', 0):.0f} - " |
| 343 |
f"{metrics.get('max_message_size_bytes', 0):.0f} bytes") |
| 344 |
|
| 345 |
|
| 346 |
if metrics.get('peak_memory_mb', 0) > 0: |
| 347 |
print("\nMemory Usage:") |
| 348 |
print(f" Peak: {metrics.get('peak_memory_mb', 0):.2f}MB") |
| 349 |
print(f" Growth: {metrics.get('memory_growth_mb', 0):.2f}MB") |
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
op_name = "consume" |
| 354 |
if any(key.startswith('poll_') for key in metrics.keys()): |
| 355 |
op_name = "poll" |
| 356 |
|
| 357 |
|
| 358 |
if op_name == "consume": |
| 359 |
print(f"\n{op_name.title()} Efficiency:") |
| 360 |
print(f" Messages per {op_name}(): {metrics.get(f'messages_per_{op_name}', 0):.2f}") |
| 361 |
print(f" Empty {op_name} rate: {metrics.get(f'empty_{op_name}_rate', 0):.3f}") |
| 362 |
print(f" Total {op_name}() calls: {metrics.get(f'{op_name}_call_count', 0)}") |
| 363 |
|
| 364 |
|
| 365 |
print("\nValidation:") |
| 366 |
if is_valid: |
| 367 |
print(" All performance bounds satisfied") |
| 368 |
else: |
| 369 |
print(" Performance bounds violations:") |
| 370 |
for violation in violations: |
| 371 |
print(f" - {violation}") |
| 372 |
|
| 373 |
print("=" * 50) |