The user wants a Python CLI tool to benchmark web server performance. I need to create concise yet essential Python code and design the CLI to include features like sending HTTP requests and measuring latency, throughput, error rates, and concurrency.
Although the user didn't specify an environment, I'll give them a script using either the standard library with requests, or httpx with asyncio for driving concurrency effectively. Using argparse would help keep dependencies minimal while still being effective.Designing Tool Features
I’m outlining the features for the CLI tool, which should include options for URL, method, headers, body, the number of requests, concurrency, timeout, and keep-alive settings. I’ll implement concurrency limits using asyncio semaphores and record latency, status codes, and errors for each request. Afterward, I’ll compute various metrics, like total requests, successful requests, requests per second, and latency stats.
For the output, a summary should be printed, maybe in JSON format. I’ll need to include the main guard and instructions for running the tool as well.Structuring the Tool Development
The user requested a development, so I need to provide some explanation, but nothing overly detailed. I should keep verbosity around a 2 out of 10 and organize it effectively.
I’ll start with a brief bullet list of features, followed by the full source code. After that, I'll include concise instructions for usage, possibly with an example.
For implementation, I’m using httpx.AsyncClient to manage concurrency with asyncio. Each worker will return its request duration and status, and I’ll gather all results using await asyncio.gather(...) to keep it simple.Designing Memory Management and Concurrency
For memory management, using O(n_requests) should be fine for moderate loads, like 100k requests. Since this is a tutorial tool, I think it’s acceptable; however, we might prefer streaming updates instead, so let's skip that for now.
I’m thinking that results can be structured as a list of tuples including success status, status code, elapsed time, response size, and any errors. In the worker function, I’ll reuse the same client for keep-alive support, implementing concurrency with a semaphore to manage the maximum number of tasks in flight. Each worker will wait for its turn to send requests.Defining Option Arguments and Metrics
I'm setting up option arguments for the tool, which will accept parameters like the URL, number of requests, concurrency, HTTP method, headers, and more. For latencies, we’ll compute percentiles; a simple function will do it based on sorting the latencies.
I need to define how to calculate requests per second too, which depends on the total success counts and total duration. Using argparse will help set everything up. I must also be cautious about edge cases like failed requests and ensure that concurrency doesn't exceed the number of requests. Once I draft the code, I’ll note the dependencies at the top and ensure compatibility with Python 3.8+. Below is a self‑contained Python CLI tool that benchmarks a web server by sending concurrent HTTP requests and reporting latency/throughput statistics.
It uses asyncio + httpx for efficient concurrency.
Features
Concurrent HTTP requests with configurable concurrency (-c) and total requests (-n)
Supports HTTP methods, headers, and request body
Reports:
Total / successful / failed requests
Requests per second
Transfer rate (bytes/sec)
Latency min/avg/max and percentiles (50/75/90/95/99)
Simple CLI interface (using argparse)
Code: webbench.py
python
Usage
Install dependency:
bash
pip install httpx
Save the script as webbench.py and make it executable:
bash
chmod +x webbench.py
Run some benchmarks:
bash
# Basic GET benchmark
./webbench.py https://example.com -n 200 -c 20
# POST with JSON body and header
./webbench.py https://api.example.com/endpoint \
-m POST \
-H "Content-Type: application/json" \
-d '{"foo": "bar"}' \
-n 1000 -c 50
# Using HTTP/2 and ignoring TLS verification
./webbench.py https://your-server.test -n 5000 -c 100 --http2 --insecure
If you want, I can extend this to support a “duration mode” (run for N seconds instead of N requests), CSV/JSON output, or plotting latency histograms.
#!/usr/bin/env python3
import argparse
import asyncio
import statistics
import sys
import time
from typing import Dict, List, Optional, Tuple
try:
import httpx
except ImportError:
print("This tool requires the 'httpx' package. Install it with:")
print(" pip install httpx")
sys.exit(1)
def parse_headers(header_list: List[str]) -> Dict[str, str]:
headers: Dict[str, str] = {}
for h in header_list:
if ":" not in h:
raise ValueError(f"Invalid header format: '{h}', expected 'Name: Value'")
name, value = h.split(":", 1)
headers[name.strip()] = value.strip()
return headers
def percentile(data: List[float], p: float) -> float:
"""
Compute the p-th percentile (0-100) of a list using linear interpolation.
"""
if not data:
return 0.0
if p <= 0:
return min(data)
if p >= 100:
return max(data)
data_sorted = sorted(data)
k = (len(data_sorted) - 1) * (p / 100.0)
f = int(k)
c = min(f + 1, len(data_sorted) - 1)
if f == c:
return data_sorted[int(k)]
d0 = data_sorted[f] * (c - k)
d1 = data_sorted[c] * (k - f)
return d0 + d1
async def worker(
index: int,
client: httpx.AsyncClient,
method: str,
url: str,
headers: Dict[str, str],
data: Optional[str],
semaphore: asyncio.Semaphore,
) -> Tuple[bool, Optional[int], float, int, Optional[str]]:
"""
Perform a single HTTP request and return metrics.
Returns:
(success, status_code, latency_seconds, response_size_bytes, error_message)
"""
async with semaphore:
start = time.perf_counter()
try:
response = await client.request(method, url, headers=headers, content=data)
elapsed = time.perf_counter() - start
size = len(response.content or b"")
success = 200 <= response.status_code < 400
return success, response.status_code, elapsed, size, None
except Exception as exc:
elapsed = time.perf_counter() - start
return False, None, elapsed, 0, str(exc)
async def run_benchmark(args: argparse.Namespace) -> None:
method = args.method.upper()
url = args.url
headers = parse_headers(args.header or [])
data = args.data
total_requests = args.requests
concurrency = min(args.concurrency, total_requests)
timeout = httpx.Timeout(args.timeout)
limits = httpx.Limits(max_keepalive_connections=concurrency, max_connections=concurrency)
semaphore = asyncio.Semaphore(concurrency)
async with httpx.AsyncClient(
timeout=timeout,
limits=limits,
verify=not args.insecure,
http2=args.http2,
follow_redirects=args.follow_redirects,
) as client:
start_time = time.perf_counter()
tasks = [
asyncio.create_task(
worker(i, client, method, url, headers, data, semaphore)
)
for i in range(total_requests)
]
results = await asyncio.gather(*tasks)
end_time = time.perf_counter()
elapsed_total = end_time - start_time
# Aggregate results
latencies: List[float] = []
total_bytes = 0
total_success = 0
total_failed = 0
status_counts: Dict[Optional[int], int] = {}
for success, status, latency, size, error in results:
if success:
total_success += 1
latencies.append(latency)
else:
total_failed += 1
total_bytes += size
status_counts[status] = status_counts.get(status, 0) + 1
# Compute statistics
rps = total_requests / elapsed_total if elapsed_total > 0 else 0.0
tput = total_bytes / elapsed_total if elapsed_total > 0 else 0.0
print("\n=== Web Benchmark Results ===")
print(f"Target URL: {url}")
print(f"Method: {method}")
print(f"Total requests: {total_requests}")
print(f"Concurrency: {concurrency}")
print(f"Total time: {elapsed_total:.4f} sec")
print(f"Requests per second: {rps:.2f} [#/sec]")
print(f"Transfer rate: {tput/1024:.2f} [KB/sec] ({tput/1024/1024:.2f} MB/sec)")
print(f"Successful requests: {total_success}")
print(f"Failed requests: {total_failed}")
print("\nStatus code distribution:")
for status, count in sorted(status_counts.items(), key=lambda x: (x[0] is None, x[0])):
label = "ERROR" if status is None else str(status)
print(f" {label}: {count}")
if latencies:
lat_min = min(latencies)
lat_max = max(latencies)
lat_mean = statistics.mean(latencies)
lat_median = statistics.median(latencies)
p50 = percentile(latencies, 50)
p75 = percentile(latencies, 75)
p90 = percentile(latencies, 90)
p95 = percentile(latencies, 95)
p99 = percentile(latencies, 99)
print("\nLatency (seconds):")
print(f" Min: {lat_min:.6f}")
print(f" Mean: {lat_mean:.6f}")
print(f" Median: {lat_median:.6f}")
print(f" Max: {lat_max:.6f}")
print(f" P50: {p50:.6f}")
print(f" P75: {p75:.6f}")
print(f" P90: {p90:.6f}")
print(f" P95: {p95:.6f}")
print(f" P99: {p99:.6f}")
else:
print("\nNo successful requests; latency statistics unavailable.")
def build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Simple HTTP benchmarking tool (Python + httpx).",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("url", help="Target URL to benchmark")
parser.add_argument(
"-n",
"--requests",
type=int,
default=100,
help="Total number of requests to perform",
)
parser.add_argument(
"-c",
"--concurrency",
type=int,
default=10,
help="Number of multiple requests to make at a time",
)
parser.add_argument(
"-m",
"--method",
default="GET",
help="HTTP method to use",
)
parser.add_argument(
"-H",
"--header",
action="append",
help="Custom header to include in request, e.g., 'User-Agent: mybench'. "
"Can be specified multiple times.",
)
parser.add_argument(
"-d",
"--data",
help="Request body to send (for POST/PUT/PATCH, etc.)",
)
parser.add_argument(
"--timeout",
type=float,
default=10.0,
help="Request timeout in seconds",
)
parser.add_argument(
"--insecure",
action="store_true",
help="Disable TLS certificate verification",
)
parser.add_argument(
"--http2",
action="store_true",
help="Enable HTTP/2 if supported by the server",
)
parser.add_argument(
"--follow-redirects",
action="store_true",
help="Follow HTTP redirects",
)
return parser
def main() -> None:
parser = build_arg_parser()
args = parser.parse_args()
if args.requests <= 0:
parser.error("--requests must be positive")
if args.concurrency <= 0:
parser.error("--concurrency must be positive")
try:
asyncio.run(run_benchmark(args))
except KeyboardInterrupt:
print("\nInterrupted by user.")
if __name__ == "__main__":
main()