Clarifying Python Application
The user requests a Python application using asyncio to manage thousands of concurrent web requests, but they haven't specified whether it's for a server or a client. I’m considering both options since "handle" could imply either role. The wording leans toward an HTTP client performing multiple concurrent fetches, but it's worth noting we could create an example that addresses both. However, they didn't request a specific framework like aiohttp or FastAPI, so it's a bit flexible here!Demonstrating Python Examples
I can certainly show the user two examples for handling concurrent web requests with Python.
First, I could create an async HTTP client using aiohttp that makes thousands of concurrent requests, incorporating concurrency limitations with asyncio.Semaphore or asyncio.BoundedSemaphore, while reusing sessions for efficiency.
Secondly, I could optionally illustrate a simple async web server with aiohttp or asyncio.start_server for handling HTTP requests. I want to focus on elements like using a TCPConnector to manage high concurrency and providing a runnable script that fetches a list of URLs concurrently.Planning Concise Code Examples
The user might want a server example, but even a client solution will effectively demonstrate handling thousands of concurrent I/O-bound tasks. They’re looking for concise yet informative code that isn’t overly verbose.
My plan is to explain the design briefly in a couple of short paragraphs, followed by code that features helpful comments without being excessive. I’ll ensure to use Python 3.11’s asyncio.run() and implement asyncio.Semaphore to manage the concurrency limit.Designing the Example Code
Here’s a Python example using asyncio and aiohttp to handle thousands of concurrent web requests. It sets a concurrency limit of 1000 with asyncio.Semaphore. The fetch function retrieves URLs, managing requests efficiently while handling timeouts.
In main, I create a list of URLs and configure the TCPConnector. Notably, to effectively manage thousands of requests, I should ensure the operating system’s limits on file descriptors are sufficient. I should dive right into the explanation without unnecessary details!Creating a Python Application
The user wants to create a Python application, suggesting a single-file script. I should include installation instructions at the top — pip install aiohttp is necessary. I’ll target a concurrency of 1000 tasks while demonstrating 5000 total URL requests.
I plan to present an HTTP client that uses asyncio and aiohttp, handling thousands of concurrent web requests effectively. To demonstrate this, I'll hardcode a list of URLs pointing to https://httpbin.org/delay/1 for safety, ensuring comments guide the user for replacement with real URLs. Also, I will explain the concurrency pattern succinctly and implement the code focusing on clarity. Below is a self‑contained Python script that uses asyncio and aiohttp to issue thousands of concurrent HTTP requests efficiently.
It:
- Uses a single shared
aiohttp.ClientSession (connection pooling).
- Limits concurrency with an
asyncio.Semaphore so you don’t overload your machine or target.
- Can easily be scaled to thousands of requests.
1. Install dependencies
pip install aiohttp
Requires Python 3.8+.
2. Example: async HTTP client handling thousands of concurrent requests
#!/usr/bin/env python3
"""
async_http_stress.py
Example asyncio application that sends thousands of concurrent web requests.
Usage:
python async_http_stress.py
"""
import asyncio
import time
from typing import Tuple
import aiohttp
# Configuration
TARGET_URL = "https://example.com" # Change this to your own endpoint / localhost
NUM_REQUESTS = 5000 # Total number of requests to send
MAX_CONCURRENCY = 1000 # Max simultaneous in-flight requests
async def fetch_one(
session: aiohttp.ClientSession,
url: str,
sem: asyncio.Semaphore,
idx: int,
) -> Tuple[int, int | None, int | None]:
"""
Perform a single HTTP GET request.
Returns: (index, status_code or None, response_size or None)
"""
async with sem: # enforce concurrency limit
try:
async with session.get(url) as resp:
body = await resp.read()
return idx, resp.status, len(body)
except Exception as e:
# In production, use proper logging instead of print
print(f"Request {idx} failed: {e!r}")
return idx, None, None
async def run_load_test(
url: str,
num_requests: int,
max_concurrency: int,
) -> None:
sem = asyncio.Semaphore(max_concurrency)
timeout = aiohttp.ClientTimeout(
total=30, # max time for the whole request
connect=10, # time to establish the connection
)
# limit=0 => no limit on total connections; use with care
connector = aiohttp.TCPConnector(limit=0)
async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:
tasks = [
asyncio.create_task(fetch_one(session, url, sem, i))
for i in range(num_requests)
]
started = time.perf_counter()
completed = 0
successes = 0
# Process results as they complete
for coro in asyncio.as_completed(tasks):
idx, status, size = await coro
completed += 1
if status is not None and 200 <= status < 300:
successes += 1
# Occasionally print progress
if completed % 500 == 0 or completed == num_requests:
print(
f"Completed {completed}/{num_requests} "
f"(successes: {successes}, last status: {status}, last size: {size})"
)
elapsed = time.perf_counter() - started
print("-" * 60)
print(f"Finished {num_requests} requests in {elapsed:.2f} seconds")
print(f"Throughput: {num_requests / elapsed:.2f} requests/sec")
print(f"Successes: {successes}, Failures: {num_requests - successes}")
async def main() -> None:
await run_load_test(
url=TARGET_URL,
num_requests=NUM_REQUESTS,
max_concurrency=MAX_CONCURRENCY,
)
if __name__ == "__main__":
asyncio.run(main())
3. Notes / tuning
- NUM_REQUESTS: total requests to send.
- MAX_CONCURRENCY: how many requests are in-flight at once.
- For thousands of concurrent requests, values like 500–2000 are common, but it depends on your hardware and target.
- OS limits: For very high concurrency, ensure your system’s file descriptor and TCP connection limits are high enough (e.g.,
ulimit -n on Unix).
If you instead need an async web server that can handle thousands of concurrent incoming requests, say so and I’ll provide a minimal aiohttp/asyncio server example as well.