The user wants a Python CLI tool to benchmark web server performance. This is a great use case for a professional-grade tool that combines functionality with a good user interface.
Key features I should include:
- HTTP/HTTPS request benchmarking
- Concurrent connections support
- Various metrics (latency, throughput, errors)
- Different request methods (GET, POST, etc.)
- Custom headers and payloads
- Progress visualization
- Results export (JSON, CSV)
- Real-time statistics display
I'll use:
aiohttp for async HTTP requests
rich for beautiful terminal output
click for CLI argument parsing
asyncio for concurrency
time for precise timing
Let me create a comprehensive, professional CLI tool with:
- Beautiful terminal UI using Rich
- Async performance testing
- Multiple visualization modes
- Detailed statistics
- Export capabilities
- Configuration options
This will be a self-contained script without external assets.
Web Server Performance Benchmarking CLI Tool
A professional, feature-rich CLI tool for benchmarking web server performance with real-time visualization, concurrent requests, and detailed statistics.
Installation
pip install aiohttp rich click numpy
Complete Code
#!/usr/bin/env python3
"""
Web Server Performance Benchmarking CLI Tool
A professional tool for testing web server performance with real-time metrics.
"""
import asyncio
import json
import statistics
import time
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional
import csv
import sys
import aiohttp
import click
import numpy as np
from rich.console import Console
from rich.progress import (
BarColumn,
Progress,
SpinnerColumn,
TaskID,
TextColumn,
TimeElapsedColumn,
)
from rich.table import Table
from rich.live import Live
from rich.panel import Panel
from rich.layout import Layout
from rich.text import Text
class HttpMethod(Enum):
GET = "GET"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
HEAD = "HEAD"
OPTIONS = "OPTIONS"
class OutputFormat(Enum):
TABLE = "table"
JSON = "json"
CSV = "csv"
@dataclass
class RequestResult:
"""Stores the result of a single HTTP request."""
url: str
status_code: int
response_time_ms: float
success: bool
error_message: Optional[str] = None
response_size_bytes: int = 0
timestamp: float = field(default_factory=time.time)
@property
def is_error(self) -> bool:
return not self.success or self.status_code >= 400
@dataclass
class BenchmarkConfig:
"""Configuration for the benchmark run."""
url: str
method: HttpMethod = HttpMethod.GET
num_requests: int = 100
concurrency: int = 10
timeout_seconds: float = 30.0
headers: Dict[str, str] = field(default_factory=dict)
body: Optional[str] = None
verify_ssl: bool = True
follow_redirects: bool = True
@dataclass
class BenchmarkStats:
"""Aggregated statistics from benchmark run."""
total_requests: int = 0
successful_requests: int = 0
failed_requests: int = 0
total_bytes: int = 0
total_time_seconds: float = 0.0
min_response_time_ms: float = float('inf')
max_response_time_ms: float = 0.0
mean_response_time_ms: float = 0.0
median_response_time_ms: float = 0.0
p90_response_time_ms: float = 0.0
p95_response_time_ms: float = 0.0
p99_response_time_ms: float = 0.0
std_dev_ms: float = 0.0
requests_per_second: float = 0.0
bytes_per_second: float = 0.0
status_codes: Dict[int, int] = field(default_factory=dict)
errors: List[str] = field(default_factory=list)
@property
def success_rate(self) -> float:
if self.total_requests == 0:
return 0.0
return (self.successful_requests / self.total_requests) * 100
class BenchmarkRunner:
"""Async benchmark runner with real-time progress tracking."""
def __init__(self, config: BenchmarkConfig, console: Console):
self.config = config
self.console = console
self.results: List[RequestResult] = []
self.stats = BenchmarkStats()
self._progress: Optional[Progress] = None
self._task_id: Optional[TaskID] = None
async def make_request(self, session: aiohttp.ClientSession) -> RequestResult:
"""Make a single HTTP request and measure response time."""
start_time = time.perf_counter()
try:
kwargs = {
"timeout": aiohttp.ClientTimeout(total=self.config.timeout_seconds),
"ssl": self.config.verify_ssl,
"allow_redirects": self.config.follow_redirects,
}
if self.config.headers:
kwargs["headers"] = self.config.headers
if self.config.body and self.config.method in [HttpMethod.POST, HttpMethod.PUT]:
kwargs["data"] = self.config.body
async with session.request(
method=self.config.method.value,
url=self.config.url,
**kwargs
) as response:
content = await response.read()
end_time = time.perf_counter()
return RequestResult(
url=self.config.url,
status_code=response.status,
response_time_ms=(end_time - start_time) * 1000,
success=True,
response_size_bytes=len(content),
)
except asyncio.TimeoutError:
end_time = time.perf_counter()
return RequestResult(
url=self.config.url,
status_code=0,
response_time_ms=(end_time - start_time) * 1000,
success=False,
error_message="Request timed out",
)
except aiohttp.ClientError as e:
end_time = time.perf_counter()
return RequestResult(
url=self.config.url,
status_code=0,
response_time_ms=(end_time - start_time) * 1000,
success=False,
error_message=str(e),
)
except Exception as e:
end_time = time.perf_counter()
return RequestResult(
url=self.config.url,
status_code=0,
response_time_ms=(end_time - start_time) * 1000,
success=False,
error_message=f"Unexpected error: {str(e)}",
)
async def worker(
self,
session: aiohttp.ClientSession,
request_queue: asyncio.Queue,
semaphore: asyncio.Semaphore
):
"""Worker coroutine that processes requests from the queue."""
while True:
try:
# Non-blocking get with timeout
request_id = await asyncio.wait_for(request_queue.get(), timeout=0.1)
except asyncio.TimeoutError:
continue
if request_id is None:
request_queue.task_done()
break
async with semaphore:
result = await self.make_request(session)
self.results.append(result)
# Update progress
if self._progress and self._task_id is not None:
self._progress.update(self._task_id, advance=1)
request_queue.task_done()
async def run_benchmark(self) -> BenchmarkStats:
"""Execute the full benchmark with concurrent workers."""
self.results = []
self.stats = BenchmarkStats()
connector = aiohttp.TCPConnector(
limit=self.config.concurrency * 2,
limit_per_host=self.config.concurrency,
)
start_time = time.time()
# Create progress display
self._progress = Progress(
SpinnerColumn(),
TextColumn("[bold blue]{task.description}", justify="right"),
BarColumn(bar_width=None),
TextColumn("[progress.percentage]{task.percentage:>3.1f}%"),
TextColumn("•"),
TextColumn("[cyan]{task.completed}/{task.total} requests"),
TextColumn("•"),
TimeElapsedColumn(),
console=self.console,
transient=True,
)
with self._progress:
self._task_id = self._progress.add_task(
"Benchmarking",
total=self.config.num_requests
)
async with aiohttp.ClientSession(connector=connector) as session:
# Create request queue
request_queue: asyncio.Queue = asyncio.Queue()
for i in range(self.config.num_requests):
await request_queue.put(i)
# Create semaphore for concurrency control
semaphore = asyncio.Semaphore(self.config.concurrency)
# Create worker tasks
workers = []
for _ in range(self.config.concurrency):
worker_task = asyncio.create_task(
self.worker(session, request_queue, semaphore)
)
workers.append(worker_task)
# Wait for all requests to complete
await request_queue.join()
# Signal workers to stop
for _ in range(self.config.concurrency):
await request_queue.put(None)
# Wait for all workers to finish
await asyncio.gather(*workers)
end_time = time.time()
self._compute_statistics(end_time - start_time)
return self.stats
def _compute_statistics(self, total_time: float):
"""Compute aggregate statistics from all results."""
if not self.results:
return
self.stats.total_time_seconds = total_time
self.stats.total_requests = len(self.results)
# Separate successful and failed requests
successful_results = [r for r in self.results if not r.is_error]
failed_results = [r for r in self.results if r.is_error]
self.stats.successful_requests = len(successful_results)
self.stats.failed_requests = len(failed_results)
# Collect response times
response_times = [r.response_time_ms for r in successful_results]
if response_times:
self.stats.min_response_time_ms = min(response_times)
self.stats.max_response_time_ms = max(response_times)
self.stats.mean_response_time_ms = statistics.mean(response_times)
self.stats.median_response_time_ms = statistics.median(response_times)
# Percentiles using numpy for accuracy
rt_array = np.array(response_times)
self.stats.p90_response_time_ms = float(np.percentile(rt_array, 90))
self.stats.p95_response_time_ms = float(np.percentile(rt_array, 95))
self.stats.p99_response_time_ms = float(np.percentile(rt_array, 99))
self.stats.std_dev_ms = float(np.std(rt_array))
# Throughput calculations
self.stats.total_bytes = sum(r.response_size_bytes for r in successful_results)
if total_time > 0:
self.stats.requests_per_second = self.stats.total_requests / total_time
self.stats.bytes_per_second = self.stats.total_bytes / total_time
# Status code distribution
for result in self.results:
code = result.status_code if result.success else 0
self.stats.status_codes[code] = self.stats.status_codes.get(code, 0) + 1
# Collect unique errors
seen_errors = set()
for result in failed_results:
if result.error_message and result.error_message not in seen_errors:
seen_errors.add(result.error_message)
self.stats.errors.append(result.error_message)
class ResultsFormatter:
"""Format and display benchmark results."""
def __init__(self, stats: BenchmarkStats, console: Console):
self.stats = stats
self.console = console
def display_table(self):
"""Display results in a rich table format."""
layout = Layout()
# Summary Panel
summary_table = Table(show_header=False, box=None, padding=(0, 2))
summary_table.add_column("Metric", style="cyan")
summary_table.add_column("Value", style="green", justify="right")
summary_table.add_row("Total Requests", f"{self.stats.total_requests:,}")
summary_table.add_row(
"Successful / Failed",
f"[green]{self.stats.successful_requests:,}[/green] / [red]{self.stats.failed_requests:,}[/red]"
)
summary_table.add_row("Success Rate", f"{self.stats.success_rate:.2f}%")
summary_table.add_row("Total Time", f"{self.stats.total_time_seconds:.3f}s")
summary_table.add_row("Requests/sec", f"{self.stats.requests_per_second:.2f}")
summary_table.add_row(
"Data Transferred",
f"{self._format_bytes(self.stats.total_bytes)}"
)
summary_table.add_row(
"Throughput",
f"{self._format_bytes(self.stats.bytes_per_second)}/s"
)
# Latency Panel
latency_table = Table(show_header=False, box=None, padding=(0, 2))
latency_table.add_column("Metric", style="cyan")
latency_table.add_column("Value", style="yellow", justify="right")
latency_table.add_row("Min", f"{self.stats.min_response_time_ms:.2f}ms")
latency_table.add_row("Max", f"{self.stats.max_response_time_ms:.2f}ms")
latency_table.add_row("Mean", f"{self.stats.mean_response_time_ms:.2f}ms")
latency_table.add_row("Median", f"{self.stats.median_response_time_ms:.2f}ms")
latency_table.add_row("Std Dev", f"{self.stats.std_dev_ms:.2f}ms")
# Percentiles Panel
percentiles_table = Table(show_header=False, box=None, padding=(0, 2))
percentiles_table.add_column("Percentile", style="cyan")
percentiles_table.add_column("Value", style="magenta", justify="right")
percentiles_table.add_row("P90", f"{self.stats.p90_response_time_ms:.2f}ms")
percentiles_table.add_row("P95", f"{self.stats.p95_response_time_ms:.2f}ms")
percentiles_table.add_row("P99", f"{self.stats.p99_response_time_ms:.2f}ms")
# Status Codes Panel
status_table = Table(title="Status Codes", show_header=True, header_style="bold")
status_table.add_column("Code", style="cyan")
status_table.add_column("Count", style="green", justify="right")
status_table.add_column("Percentage", style="yellow", justify="right")
for code, count in sorted(self.stats.status_codes.items()):
percentage = (count / self.stats.total_requests * 100) if self.stats.total_requests > 0 else 0
code_style = "green" if 200 <= code < 300 else "yellow" if 300 <= code < 400 else "red"
status_table.add_row(
f"[{code_style}]{code}[/{code_style}]",
str(count),
f"{percentage:.1f}%"
)
# Display all panels
self.console.print()
self.console.print(Panel(summary_table, title="[bold]Summary[/bold]", border_style="blue"))
self.console.print()
# Display latency tables side by side using columns
from rich.columns import Columns
self.console.print(Columns([
Panel(latency_table, title="[bold]Latency[/bold]", border_style="green"),
Panel(percentiles_table, title="[bold]Percentiles[/bold]", border_style="magenta"),
]))
self.console.print()
self.console.print(status_table)
# Display errors if any
if self.stats.errors:
error_table = Table(title="Errors", show_header=True, header_style="bold red")
error_table.add_column("#", style="dim")
error_table.add_column("Error Message", style="red")
for i, error in enumerate(self.stats.errors[:10], 1): # Show max 10 errors
error_table.add_row(str(i), error[:80] + "..." if len(error) > 80 else error)
self.console.print()
self.console.print(error_table)
def _format_bytes(self, bytes_count: int) -> str:
"""Format bytes to human readable format."""
for unit in ['B', 'KB', 'MB', 'GB']:
if bytes_count < 1024:
return f"{bytes_count:.2f} {unit}"
bytes_count /= 1024
return f"{bytes_count:.2f} TB"
def to_json(self) -> str:
"""Export results as JSON."""
return json.dumps({
"summary": {
"total_requests": self.stats.total_requests,
"successful_requests": self.stats.successful_requests,
"failed_requests": self.stats.failed_requests,
"success_rate_percent": self.stats.success_rate,
"total_time_seconds": self.stats.total_time_seconds,
"requests_per_second": self.stats.requests_per_second,
"total_bytes": self.stats.total_bytes,
"bytes_per_second": self.stats.bytes_per_second,
},
"latency": {
"min_ms": self.stats.min_response_time_ms,
"max_ms": self.stats.max_response_time_ms,
"mean_ms": self.stats.mean_response_time_ms,
"median_ms": self.stats.median_response_time_ms,
"std_dev_ms": self.stats.std_dev_ms,
},
"percentiles": {
"p90_ms": self.stats.p90_response_time_ms,
"p95_ms": self.stats.p95_response_time_ms,
"p99_ms": self.stats.p99_response_time_ms,
},
"status_codes": self.stats.status_codes,
"errors": self.stats.errors,
"timestamp": datetime.now().isoformat(),
}, indent=2)
def to_csv(self) -> str:
"""Export results as CSV."""
import io
output = io.StringIO()
writer = csv.writer(output)
# Write header
writer.writerow(["Metric", "Value", "Unit"])
# Write data
writer.writerow(["Total Requests", self.stats.total_requests, ""])
writer.writerow(["Successful Requests", self.stats.successful_requests, ""])
writer.writerow(["Failed Requests", self.stats.failed_requests, ""])
writer.writerow(["Success Rate", f"{self.stats.success_rate:.2f}", "%"])
writer.writerow(["Total Time", f"{self.stats.total_time_seconds:.3f}", "s"])
writer.writerow(["Requests/sec", f"{self.stats.requests_per_second:.2f}", "req/s"])
writer.writerow(["Min Response Time", f"{self.stats.min_response_time_ms:.2f}", "ms"])
writer.writerow(["Max Response Time", f"{self.stats.max_response_time_ms:.2f}", "ms"])
writer.writerow(["Mean Response Time", f"{self.stats.mean_response_time_ms:.2f}", "ms"])
writer.writerow(["Median Response Time", f"{self.stats.median_response_time_ms:.2f}", "ms"])
writer.writerow(["P90", f"{self.stats.p90_response_time_ms:.2f}", "ms"])
writer.writerow(["P95", f"{self.stats.p95_response_time_ms:.2f}", "ms"])
writer.writerow(["P99", f"{self.stats.p99_response_time_ms:.2f}", "ms"])
writer.writerow(["Std Dev", f"{self.stats.std_dev_ms:.2f}", "ms"])
return output.getvalue()
# CLI Definition using Click
@click.group(invoke_without_command=True)
@click.option('--url', '-u', required=True, help='Target URL to benchmark')
@click.option('--requests', '-n', default=100, show_default=True,
help='Total number of requests')
@click.option('--concurrency', '-c', default=10, show_default=True,
help='Number of concurrent connections')
@click.option('--method', '-m', default='GET', show_default=True,
type=click.Choice(['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']),
help='HTTP method')
@click.option('--timeout', '-t', default=30.0, show_default=True,
help='Request timeout in seconds')
@click.option('--header', '-H', multiple=True,
help='Custom header (format: "Key: Value")')
@click.option('--body', '-b', default=None,
help='Request body for POST/PUT')
@click.option('--no-verify-ssl', is_flag=True,
help='Disable SSL certificate verification')
@click.option('--no-redirects', is_flag=True,
help='Disable following redirects')
@click.option('--output', '-o', type=click.Path(),
help='Output file path')
@click.option('--format', '-f', default='table', show_default=True,
type=click.Choice(['table', 'json', 'csv']),
help='Output format')
@click.version_option(version='1.0.0')
@click.pass_context
def cli(ctx, url, requests, concurrency, method, timeout, header, body,
no_verify_ssl, no_redirects, output, format):
"""
🔥 Web Server Performance Benchmarking Tool
A powerful CLI tool to measure web server performance with concurrent
requests, detailed statistics, and multiple output formats.
Examples:
# Basic benchmark
python benchmark.py -u https://example.com
# 1000 requests with 50 concurrent connections
python benchmark.py -u https://api.example.com -n 1000 -c 50
# POST request with JSON body
python benchmark.py -u https://api.example.com/users -m POST \\
-H "Content-Type: application/json" -b '{"name": "test"}'
# Export results as JSON
python benchmark.py -u https://example.com -f json -o results.json
"""
# Parse headers
headers = {}
for h in header:
if ':' in h:
key, value = h.split(':', 1)
headers[key.strip()] = value.strip()
# Create configuration
config = BenchmarkConfig(
url=url,
method=HttpMethod[method],
num_requests=requests,
concurrency=concurrency,
timeout_seconds=timeout,
headers=headers,
body=body,
verify_ssl=not no_verify_ssl,
follow_redirects=not no_redirects,
)
# Create console
console = Console()
# Display configuration
console.print()
config_panel = Table(show_header=False, box=None, padding=(0, 2))
config_panel.add_column("Setting", style="dim")
config_panel.add_column("Value", style="cyan")
config_panel.add_row("Target URL", url)
config_panel.add_row("Method", method)
config_panel.add_row("Requests", f"{requests:,}")
config_panel.add_row("Concurrency", str(concurrency))
config_panel.add_row("Timeout", f"{timeout}s")
console.print(Panel(config_panel, title="[bold]Benchmark Configuration[/bold]",
border_style="cyan"))
console.print()
# Run benchmark
try:
runner = BenchmarkRunner(config, console)
stats = asyncio.run(runner.run_benchmark())
# Format and display results
formatter = ResultsFormatter(stats, console)
if format == 'table':
formatter.display_table()
elif format == 'json':
output_text = formatter.to_json()
console.print(output_text)
elif format == 'csv':
output_text = formatter.to_csv()
console.print(output_text)
# Write to file if specified
if output:
with open(output, 'w') as f:
if format == 'json':
f.write(formatter.to_json())
elif format == 'csv':
f.write(formatter.to_csv())
else:
# Default to JSON for file output if table was selected
f.write(formatter.to_json())
console.print(f"\n[green]Results saved to: {output}[/green]")
except KeyboardInterrupt:
console.print("\n[yellow]Benchmark cancelled by user.[/yellow]")
sys.exit(130)
except Exception as e:
console.print(f"\n[red]Error: {str(e)}[/red]")
sys.exit(1)
def main():
"""Entry point for the CLI."""
cli()
if __name__ == '__main__':
main()
Features
| Feature | Description |
|---|
| 🚀 Concurrent Requests | Configurable concurrency level for realistic load testing |
| 📊 Detailed Metrics | Min/Max/Mean/Median response times, percentiles (P90/P95/P99) |
| 📈 Throughput Analysis | Requests per second, bytes transferred |
| 🔧 Flexible Configuration | Custom headers, body, HTTP methods, SSL options |
| 📁 Multiple Output Formats | Table, JSON, CSV export |
| 🎯 Status Code Analysis | Distribution of HTTP status codes |
| ⚠️ Error Tracking | Captures and displays errors |
Usage Examples
# Basic benchmark (100 requests, 10 concurrent)
python benchmark.py -u https://httpbin.org/get
# Heavy load test (1000 requests, 100 concurrent)
python benchmark.py -u https://api.example.com/endpoint -n 1000 -c 100
# POST request with JSON body
python benchmark.py -u https://httpbin.org/post -m POST \
-H "Content-Type: application/json" \
-b '{"test": "data"}'
# Export results to JSON file
python benchmark.py -u https://example.com -n 500 -f json -o results.json
# CSV output for analysis
python benchmark.py -u https://api.example.com -f csv -o benchmark.csv
# Disable SSL verification (for testing)
python benchmark.py -u https://self-signed.example.com --no-verify-ssl
Sample Output
╭─────────── Benchmark Configuration ───────────╮
│ Target URL https://httpbin.org/get │
│ Method GET │
│ Requests 100 │
│ Concurrency 10 │
│ Timeout 30.0s │
╰───────────────────────────────────────────────╯
╭─────────────────── Summary ───────────────────╮
│ Total Requests 100 │
│ Successful / Failed 100 / 0 │
│ Success Rate 100.00% │
│ Total Time 2.341s │
│ Requests/sec 42.72 │
│ Data Transferred 45.23 KB │
│ Throughput 19.31 KB/s │
╰───────────────────────────────────────────────╯
╭─────────── Latency ───────────╮ ╭───────── Percentiles ─────────╮
│ Min 18.23ms │ │ P90 45.67ms │
│ Max 89.12ms │ │ P95 52.34ms │
│ Mean 28.45ms │ │ P99 78.91ms │
│ Median 25.12ms │ │ │
│ Std Dev 12.34ms │ │ │
╰──────────────────────────────╯ ╰────────────────────────────────╯
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Status Codes ┃
┡━━━━━━┯━━━━━━━┯━━━━━━━━━━━━┩
│ Code │ Count │ Percentage │
├──────┼───────┼────────────┤
│ 200 │ 100 │ 100.0% │
└──────┴───────┴────────────┘
This tool provides professional-grade benchmarking capabilities with beautiful terminal output and comprehensive statistics!