УДК 004.42 International Journal Of Professional Science №10(2)

Asynchronous programming in Python for website availability monitoring: an experimental comparison of concurrency models

Volf Vladislav Aleksandrovich
Khvostova Tatyana Vladimirovna

1. Samara International Aerospace Lyceum, 11th grade student, Samara, Russia
2. Samara International Aerospace Lyceum, Computer Science Teacher, Samara, Russia

Abstract:

The study compares the time and memory costs of three concurrency models from the Python standard library when they check website availability, and derives design rules for a monitoring service. A local asyncio stub server emulated up to 5000 websites with fixed response delays of 100–500 ms; 5% of the sites returned HTTP 503. Three clients were tested: sequential requests (urllib), a thread pool (ThreadPoolExecutor) and asyncio coroutines limited by a semaphore. Each configuration ran three times, and the median time and peak resident memory were recorded. A sequential pass over 1000 sites took about 294 s. With 1000 threads it took 1.02 s, and asyncio at the same limit needed 0.64 s while using 29–33% less memory. At an equal limit of 100 concurrent requests, threads and asyncio differed by less than 1% and stayed within 14% of the theoretical bound. All clients classified the sites identically. Under moderate load the concurrency limit sets the duration of a monitoring round, whatever the model; asyncio becomes the better choice at hundreds of simultaneous checks. The paper proposes a formula for choosing the limit and rules for timeouts, repeat checks and multi-point monitoring.

Keywords:

asynchronous programming, Python, asyncio, multithreading, website monitoring, uptime, HTTP.

Introduction

For a local bakery or repair shop, the website is often the first place a customer meets the business. If it goes down on Friday evening and nobody notices, the owner may hear about it on Monday from an annoyed client. Engineers who run large services consider silent outages unacceptable and build alerting into everything they operate [1]. Small sites need at least a simple version of the same care.

The author builds websites for freelance clients and wrote a monitor for them. Every minute it requests each site, reads the status code of the answer [2] and sends a message if the code is not 200. Free tools such as Uptime Kuma [3] or the Blackbox exporter from the Prometheus project [4] could do the same, but a home-made monitor connects more easily to the author’s own hosting and messenger. As the list of client sites grew, one practical question kept returning: how should requests be sent so that a full round always fits into one minute? This paper answers it with measurements.

A request to a site takes almost no processor time. Nearly all its duration is idle waiting for the remote server. A monitor that asks sites one by one spends a whole minute waiting for every two hundred sites with a 0.3 s answer time, and once the list grows past that, rounds start to overlap. The way out is to run many requests at once, and Python offers several ways to do it.

The aim is to measure on a single workload how much time and memory each way needs, and to turn the numbers into design decisions for a real monitor. The work covers a short review of how threads and an event loop handle network waiting, a stub server that imitates slow and broken sites so that every run meets the same conditions, timing and memory measurements for three clients on 100, 1000 and 5000 sites, and conclusions for the author’s own tool.

Background: two ways to wait for many sites at once

Keeping thousands of network conversations open on one machine is an old engineering problem. D. Kegel’s note on ten thousand clients [5] collected the answers known at the end of the 1990s, and in simplified form they fall into two families.

The first gives every site its own thread. A check is plain blocking code, and the operating system runs many copies of it side by side, switching away from any thread stuck on the network. The code is easy to read. Python adds one complication: the global interpreter lock lets only one thread execute Python code at a time [6]. For this job the lock matters little, since a thread releases it while waiting for a socket. The real cost is that each thread is an operating-system object with its own stack, and starting and switching thousands of them is expensive. Plans to make the lock optional [7] would not remove that cost.

The second family uses a single thread that asks the operating system which sockets have news and resumes exactly the piece of work waiting on each. Researchers have argued over the two for decades. J. Ousterhout claimed that threads cause more bugs than they are worth in most programs [8]. R. von Behren, J. Condit and E. Brewer replied that poor thread libraries, and not threads themselves, are to blame [9], while the SEDA design of M. Welsh, D. Culler and E. Brewer mixed both ideas [10]. With the experts split, measuring the monitor’s own case looked more useful than choosing by opinion.

Python supports the second approach through the asyncio module, available since version 3.4 [11], and the async and await keywords added in 3.5 [12]. A function marked async can stop at an await, let the loop serve other work and later resume from the same line [13; 14]. The check still reads top to bottom, as in the threaded version, but a paused check is a small object in memory rather than an operating-system thread.

Materials and Methods

Timing the clients against real sites would give noisy numbers and would load other people’s servers with thousands of requests. The author therefore wrote a stand-in server of about 30 lines, also on asyncio, that imitates many sites. Each address of the form /i stands for one site. Every site gets its own pause before answering, drawn once from the range 100–500 ms, which gives a mean of 300 ms. One site in twenty always returns 503 Service Unavailable and plays the broken site. Pauses and failures come from the fixed seed 42, so every run, and anyone repeating the work, meets the same “internet”.

Three clients were compared. The sequential one checks sites in turn with the standard urllib module. The multithreaded one runs the same check function in a ThreadPoolExecutor with a given number of threads. The asynchronous one uses asyncio streams and caps open connections with a semaphore. All three rely on the standard library only, so the results reflect the concurrency models and not third-party libraries. Listing 1 shows the core of the asynchronous client.

Listing 1. Asynchronous check with a concurrency limit

async def check(url, sem):

    async with sem:                    # concurrency limit

        try:

            reader, writer = await asyncio.wait_for(

                asyncio.open_connection(HOST, PORT), 5)

            writer.write(build_request(url))

            await writer.drain()

            status_line = await asyncio.wait_for(reader.readline(), 5)

            writer.close()

            return int(status_line.split()[1])

        except Exception:

            return -1                  # connection error or timeout

results = await asyncio.gather(*(check(u, sem) for u in urls))

Each configuration ran three times as a separate process, and the median time is reported. Memory is the peak resident set size (RSS) of the client process. The tests ran on a Linux virtual machine with 2 CPU cores and Python 3.11. The sequential client ran on 100 sites only, since a full pass over 1000 would take about five minutes; its 1000-site figure is a linear extrapolation.

Results

Table 1 and Figure 1 show the results. In every run all models classified the sites identically: of 1000 sites, 951 were available and 49 failed with status 503, with no connection errors or timeouts. Concurrency did not affect the correctness of the checks.

Table 1

Time and memory required to check the sites (median of three runs)

Model Concurrency limit URLs Time, s (median) Peak memory (RSS), MB
Sequential (urllib) 1 100 29.41 22.9
Sequential (urllib), extrapolated 1 1000 ≈ 294 —
Thread pool (urllib) 20 1000 15.66 25.5
Thread pool (urllib) 100 1000 3.41 27.9
asyncio streams 100 1000 3.38 25.2
Thread pool (urllib) 1000 1000 1.02 44.0
asyncio streams 1000 1000 0.64 31.2
Thread pool (urllib) 1000 5000 3.03 57.0
asyncio streams 1000 5000 2.01 38.3

Fig. 1. Time to check 1000 sites with different concurrency models (logarithmic scale)

Concurrency cuts the time by two orders of magnitude. The sequential client spent on average 0.294 s per site, the mean emulated delay, so 1000 sites would take about 294 s: almost five minutes, longer than a typical one-minute check interval. The asynchronous client with a limit of 1000 connections finished the same work in 0.64 s, about 460 times faster.

With equal limits the models perform almost the same. At a limit of 100 the thread pool and asyncio finished in 3.41 s and 3.38 s. The theoretical bound is 1000 sites / 100 parallel checks × 0.3 s = 3.0 s, and both stayed close to it. The program spends nearly all its time waiting for the network, and the model barely matters. The pool of 20 threads agrees: 15.66 s against a bound of 15.0 s.

Raising the limit to 1000 separates the two. Asyncio finished in 0.64 s, near the lower bound of 0.5 s (the longest delay of a single site), while the thread pool needed 1.02 s, 1.6 times longer, and 44.0 MB of memory against 31.2 MB. At 5000 sites the gap held: 3.03 s and 57.0 MB for threads, 2.01 s and 38.3 MB for asyncio. The extra cost of threads comes from creating and switching operating-system threads, each with its own stack.

Discussion

Limitations

These numbers come from a simplified world. Both programs ran on one virtual machine, so there was no real network between them: no lost packets, no name lookups and no HTTPS handshakes, all of which add delay in practice. Real sites also answer with a long tail of slow responses instead of an even spread, and only the standard library was tested; aiohttp or httpx would probably shift the absolute times. Because all clients faced the same stub server, their comparison remains valid, but the absolute seconds should not be read as a forecast for the internet.

Practical recommendations

For a few dozen sites a ThreadPoolExecutor is the least code. With 30–50 client sites the difference from Table 1 does not appear, since it opened only at a limit of 1000. Asyncio pays off once the list reaches hundreds.

The limit can be calculated from the check interval: limit ≥ sites × average answer time ÷ interval. For 2000 sites, 0.3 s and a 60 s interval this gives only 10 parallel requests, far below “as many as possible” and gentler on the clients’ servers.

Connecting and reading need separate timeouts, for example 3 s and 5 s, because a site that accepts a connection and never sends the body can freeze a check forever. M. Nygard counts timeouts among the basic patterns that stop one slow component from dragging down the rest [15].

A single timeout may be a hiccup of the monitor’s own connection, so an alert should go out only if the site fails again after, say, 30 s. This filters most one-off glitches.

If the server running the monitor loses its network, every client site looks dead at once. A second copy in another data centre tells “the site is down” from “my monitor is down” [1].

Finally, the monitor should store answer times along with up/down status. A site that slides from 0.3 s to 3 s is usually in trouble before it fails. J. Brutlag showed how Holt–Winters forecasting can flag such unusual behaviour in network measurements [16], and testing it on the monitor’s own history is the author’s next step.

Conclusions

Three Python clients checked a thousand stand-in sites and were timed. Any concurrent client shrank a five-minute sequential round to under a second. At the same cap on simultaneous requests threads and asyncio finished in practically the same time, so the cap is the first number to choose. Only at a cap of 1000 did asyncio pull ahead, running 1.5–1.6 times faster and using roughly a third less memory. A monitor meant to grow to hundreds or thousands of sites should therefore be built on asyncio.

The next version of the author’s monitor will use asyncio with a semaphore, two timeouts and a repeat check. Open tasks are a test over the real internet with HTTPS, a comparison with aiohttp and httpx, and detection of slow-downs in the stored answer times.

References

1. Beyer B., Jones C., Petoff J., Murphy N. R. Site Reliability Engineering: How Google Runs Production Systems. – Sebastopol: O’Reilly Media, 2016. – 552 p.
2. Fielding R., Nottingham M., Reschke J. HTTP Semantics. RFC 9110. – IETF, 2022. – DOI 10.17487/RFC9110.
3. Uptime Kuma [Electronic resource] // GitHub. – URL: https://github.com/louislam/uptime-kuma (accessed: 07.10.2026).
4. Blackbox exporter [Electronic resource] // Prometheus project, GitHub. – URL: https://github.com/prometheus/blackbox_exporter (accessed: 07.10.2026).
5. Kegel D. The C10K problem [Electronic resource]. – 1999. – URL: http://www.kegel.com/c10k.html (accessed: 07.10.2026).
6. Beazley D. Understanding the Python GIL [Electronic resource] // PyCon 2010. – URL: https://www.dabeaz.com/python/UnderstandingGIL.pdf (accessed: 07.10.2026).
7. Gross S. PEP 703 – Making the Global Interpreter Lock Optional in CPython [Electronic resource]. – 2023. – URL: https://peps.python.org/pep-0703/ (accessed: 07.10.2026).
8. Ousterhout J. Why Threads Are a Bad Idea (for most purposes) // Invited talk at the USENIX Annual Technical Conference. – San Diego, 1996.
9. von Behren R., Condit J., Brewer E. Why Events Are a Bad Idea (for High-Concurrency Servers) // Proceedings of the 9th Workshop on Hot Topics in Operating Systems (HotOS IX). – USENIX, 2003.
10. Welsh M., Culler D., Brewer E. SEDA: An Architecture for Well-Conditioned, Scalable Internet Services // Proceedings of the 18th ACM Symposium on Operating Systems Principles (SOSP ’01). – 2001. – P. 230–243. – DOI 10.1145/502034.502057.
11. van Rossum G. PEP 3156 – Asynchronous IO Support Rebooted: the “asyncio” Module [Electronic resource]. – 2012. – URL: https://peps.python.org/pep-3156/ (accessed: 07.10.2026).
12. Selivanov Y. PEP 492 – Coroutines with async and await syntax [Electronic resource]. – 2015. – URL: https://peps.python.org/pep-0492/ (accessed: 07.10.2026).
13. asyncio – Asynchronous I/O // Python 3 documentation [Electronic resource]. – Python Software Foundation. – URL: https://docs.python.org/3/library/asyncio.html (accessed: 07.10.2026).
14. Ramalho L. Fluent Python: Clear, Concise, and Effective Programming. 2nd ed. – Sebastopol: O’Reilly Media, 2022.
15. Nygard M. T. Release It! Design and Deploy Production-Ready Software. 2nd ed. – Raleigh: Pragmatic Bookshelf, 2018.
16. Brutlag J. D. Aberrant Behavior Detection in Time Series for Network Monitoring // Proceedings of the 14th Systems Administration Conference (LISA 2000). – USENIX, 2000. – P. 139–146.
 

Без рубрики