frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

Open in hackernews

The Fundamentals of Asyncio

https://github.com/anordin95/a-conceptual-overview-of-asyncio/blob/main/readme.md
106•anordin95•8h ago

Comments

anordin95•8h ago
I've used Python's asyncio a couple times now, but never really felt confident in my mental model of how it fundamentally works and therefore how I can best leverage it. The official docs provide decent documentation for each specific function in the package, but, in my opinion, lack a cohesive overview of the systems design and architecture. Something that could help the user understand the why and how behind the recommended patterns. And a way to help the user make informed decisions about which tool in the asyncio toolkit they ought to grab, or to recognize when asyncio is the entirely wrong toolkit. This is my attempt to fill that gap.
sandeep1998•8h ago
thank you for that.
whinvik•7h ago
This is excellent. Thanks.
omh1280•7h ago
Great read!

Python asyncio can really screw up your runtime performance if you use it poorly. And it's _really_ easy to use poorly.

Consider a FastAPI server using asyncio instead of threading. _Any_ time you drop down into a synchrononous API, you better be sure that you're not doing anything slow. For example, encoding or decoding JSON in Python actually grabs the GIL depending on what library you're using, and then you have no hope of releasing control back to asyncio.

kccqzy•5h ago
That's a GIL problem not an async problem. Even if you choose to ditch asyncio and use threads, you still need to care about the GIL. And when I use asyncio I don't worry about CPU-bound tasks like encoding or decoding JSON; I worry about some library doing I/O synchronously regardless of whether such library releases the GIL or not.
bb88•4h ago
This is spot on. GIL-less python will be a thing, and when it happens, there will still be no reason to combine asyncIO with thread primitives. Waiting for IO can be spun off into a new thread, and it will work as you expect it would.

Trying to combine mental models of asyncio and threading is a model for pure insanity.

boomer_joe•12m ago
I fail to see why. You can have an event loop per thread, and a hypothetical requirement of wanting to make sure all compute in each thread is spent inside of its event loop (assuming OS level parallelism). Eg a latency-sensitive server in thread A and a logger in thread B (dont even need the event loop there for this example)
deathanatos•3h ago
JSON encoding is, as someone else points out, a GIL problem, but I want to add that even if you do JSON encoding in an async context:

  async def foo(…):
    json.dumps(d)  # you're blocking the event loop
You're still going to block on it.

  def sync_foo(…):
    json.dumps(d)  # you're holding the GIL … and so blocking here too
Short of resolving the GIL somehow (either by getting ridding of it, which I think is still a WIP though it has been "merged", I believe) or subinterpreters, etc., JSON is inherently going to need to hold the GIL while it walks the structure it is encoding. (Unlike a large file I/O, where it might be possible to release the GIL during the I/O if we have a strong ref to an immutable buffer.)
kevmo314•2h ago
This is more of a usability problem. In the second example, it's obvious that `json.dumps()` blocks everything else and it can be readily observed. It's not obvious that it blocks in the former and I've encountered many surprised coworkers despite it seeming obvious to me.

I think a lot of people assume you can slap `async` onto the function signature and it will not block anything anymore. I've had PRs come through that literally added `async` to a completely synchronous function with that misunderstanding.

alex5207•7h ago
[About the event loop]

> She's behind the scenes managing resources. Some power is explicitly granted to her, but a lot of her ability to get things done comes from the respect & cooperation of her subordinates.

What a wonderful paragraph. Playful, yet with a deep meaning. It makes the article a joy to read.

cadamsdotcom•6h ago
Awesome job closing a gap in the asyncio docs - wonder if it could be contributed back & be added!
paulgb•6h ago
This is great! Thanks for writing it.

One nit, the unquoted quotes in this file seem to be a parse error (I replaced the inner ones with single quotes and it ran) https://github.com/anordin95/a-conceptual-overview-of-asynci...

anordin95•5h ago
Ah, I'm so glad to hear it. And, thank you for the nit/feedback! I generally use python3.12 for my work which doesn't error out on that line. However, python3.11 and below will raise a SyntaxError on it. I've fixed the issue there and in a few other places and pushed the changes :)
Izkata•5h ago
> Frankly, I'm not sure why that design decision was made and find it rather confuses the meaning of await: asynchronously wait.

I've always understood it to mean "wait for asynchronous object", not that the wait itself is asynchronous. It's just an English word that roughly means "wait for", that was chosen for the nice "a" prefix for asynchronous stuff.

anordin95•5h ago
Mmm fair point! Though, coroutines aren't really asynchronous objects in that usage, right? Since `await coroutine` would run that coroutine synchronously.
throwawaymaths•3h ago
i don't think that's the case. an await coroutine requires you to be asynchronous because you are implicitly suspending yourself until the awaited function completes (and through however many suspensions the awaited function creates). an await can never be synchronous, you need to pull in an event loop to close between asynchronous functions and sync-land, not an await.
ISO-morphism•3h ago
This is great, thank you! Python's asyncio has certainly confused me more than other languages' async-await implementations.

Nit in [1]: When timing durations inside of a program it's best to avoid the system clock as it can and does jump around. For Python, prefer time.monotonic() or time.perf_counter() over time.time() in those situations.

[1] https://github.com/anordin95/a-conceptual-overview-of-asynci...

rtpg•3h ago
I like how asyncio could just be built off of generators, and how it all ... well it mostly works, and it works well enough for people who care enough to make a whole async stack.

I am very unhappy with asyncio leading to the gold rush of a lot of people writing "async-capable" libraries that all make (IMO) really gnarly design decisions in the process. I have seen loads of newer Python projects that take async-capable libraries that make life harder for people who like shipping stable software.

Meanwhile a lot of existing libraries/frameworks that just have more "serious" overall designs have to churn quite a bit to support sync and async workflows.

I care a lot about Django getting async ORM support in theory, but at this point I don't know how that's happening. My current mentality is crossing my fingers that something akin to virtual threads[0] happens

[0]: https://discuss.python.org/t/add-virtual-threads-to-python/9...

eurleif•3h ago
You could use gevent. It uses green threads, so that the code you write looks like synchronous code. It can also monkeypatch core networking modules so that existing code will work without changes (including the Django ORM).
quotemstr•3h ago
Why would anyone want to use asyncio over trio. The latter is one of the few structured concurrency systems that doesn't make me want to pry my eyeballs out with a spoon.
dboreham•1h ago
Change title to "The Fundamentals of Python Asyncio"? As is it seems like the article is going to be about the generic subject of async i/o.

Global hack on Microsoft Sharepoint hits U.S., state agencies, researchers say

https://www.washingtonpost.com/technology/2025/07/20/microsoft-sharepoint-hack/
434•spenvo•1d ago•200 comments

AI comes up with bizarre physics experiments, but they work

https://www.quantamagazine.org/ai-comes-up-with-bizarre-physics-experiments-but-they-work-20250721/
33•pseudolus•1h ago•5 comments

Uv: Running a script with dependencies

https://docs.astral.sh/uv/guides/scripts/#running-a-script-with-dependencies
124•Bluestein•3h ago•39 comments

If writing is thinking then what happens if AI is doing the writing and reading?

https://hardcoresoftware.learningbyshipping.com/p/234-if-writing-is-thinking
68•whobre•3h ago•46 comments

What went wrong inside recalled Anker PowerCore 10000 power banks?

https://www.lumafield.com/article/what-went-wrong-inside-these-recalled-power-banks
304•walterbell•8h ago•151 comments

AccountingBench: Evaluating LLMs on real long-horizon business tasks

https://accounting.penrose.com/
401•rickcarlino•9h ago•108 comments

Don't bother parsing: Just use images for RAG

https://www.morphik.ai/blog/stop-parsing-docs
186•Adityav369•9h ago•56 comments

TrackWeight: Turn your MacBook's trackpad into a digital weighing scale

https://github.com/KrishKrosh/TrackWeight
471•wtcactus•11h ago•121 comments

A brief history of primary coding languages

https://eclecticlight.co/2025/07/19/a-brief-history-of-primary-coding-languages/
18•ingve•2d ago•7 comments

Losing language features: some stories about disjoint unions

https://graydon2.dreamwidth.org/318788.html
36•Bogdanp•3d ago•4 comments

The surprising geography of American left-handedness (2015)

https://www.washingtonpost.com/news/wonk/wp/2015/09/22/the-surprising-geography-of-american-left-handedness/
6•roktonos•5h ago•0 comments

New records on Wendelstein 7-X

https://www.iter.org/node/20687/new-records-wendelstein-7-x
191•greesil•11h ago•83 comments

Jujutsu for Busy Devs

https://maddie.wtf/posts/2025-07-21-jujutsu-for-busy-devs
66•Bogdanp•2h ago•51 comments

Scarcity, Inventory, and Inequity: A Deep Dive into Airline Fare Buckets

https://blog.getjetback.com/scarcity-inventory-and-inequity-a-deep-dive-into-airline-fare-buckets/
82•bdev12345•7h ago•30 comments

Erlang 28 on GRiSP Nano using only 16 MB

https://www.grisp.org/blog/posts/2025-06-11-grisp-nano-codebeam-sto
107•plainOldText•7h ago•6 comments

FCC to eliminate gigabit speed goal and scrap analysis of broadband prices

https://arstechnica.com/civis/threads/fcc-to-eliminate-gigabit-speed-goal-and-scrap-analysis-of-broadband-prices.1508451/page-2
96•Bluestein•3h ago•34 comments

Spice Data (YC S19) Is Hiring a Product Associate (New Grad)

https://www.ycombinator.com/companies/spice-data/jobs/RJz1peY-product-associate-new-grad
1•richard_pepper•5h ago

Occasionally USPS sends me pictures of other people's mail

https://the418.substack.com/p/a-bug-in-the-mail
157•shayneo•11h ago•154 comments

Game Genie Retrospective: The Best NES Accessory Ever Was Unlicensed

https://tedium.co/2025/07/21/the-game-genie-generation/
110•coloneltcb•8h ago•46 comments

The Fundamentals of Asyncio

https://github.com/anordin95/a-conceptual-overview-of-asyncio/blob/main/readme.md
106•anordin95•8h ago•21 comments

NASA's X-59 Quiet Supersonic Aircraft Begins Taxi Tests

https://www.nasa.gov/image-article/nasas-x-59-quiet-supersonic-aircraft-begins-taxi-tests/
4•rbanffy•2d ago•0 comments

Yoni Appelbaum on the real villians behind our housing and mobility problems

https://www.riskgaming.com/p/how-jane-jacobs-got-americans-stuck
47•serviette•6h ago•46 comments

UK backing down on Apple encryption backdoor after pressure from US

https://arstechnica.com/tech-policy/2025/07/uk-backing-down-on-apple-encryption-backdoor-after-pressure-from-us/
444•azalemeth•12h ago•305 comments

Sutton SignWriting is a writing system for sign languages

https://en.m.wikipedia.org/wiki/SignWriting
23•janpot•2d ago•6 comments

The daily life of a medieval king

https://www.medievalists.net/2025/07/medieval-king-daily-life/
271•diodorus•4d ago•155 comments

What Will Become of the CIA?

https://www.newyorker.com/magazine/2025/07/28/the-mission-the-cia-in-the-21st-century-tim-weiner-book-review
67•Michelangelo11•8h ago•96 comments

Show HN: Lotas – Cursor for RStudio

https://www.lotas.ai/
58•jorgeoguerra•8h ago•26 comments

Jqfmt like gofmt, but for jq

https://github.com/noperator/jqfmt
134•Bluestein•9h ago•41 comments

In a major reversal, the world bank is backing mega dams (2024)

https://e360.yale.edu/features/world-bank-hydro-dams
35•prmph•5h ago•50 comments

I've launched 37 products in 5 years and not doing that again

https://www.indiehackers.com/post/ive-launched-37-products-in-5-years-and-not-doing-that-again-0b66e6e8b3
97•AlexandrBel•14h ago•87 comments