Skip to content

asyncio: run newly scheduled callbacks eagerly before polling for I/O #160760

Description

@asvetlov

Feature or enhancement

Currently, BaseEventLoop._run_once() runs only the callbacks that were ready when the iteration started. Callbacks scheduled by those callbacks wait for the next iteration, which first polls the selector (select()/epoll_wait()) with a zero timeout. Code that resolves futures, wakes tasks or chains call_soon() therefore pays for one I/O poll per hop, even when there is no I/O to process.

The good example is using asyncio.Queue: await q.put(item) pushes an item into the queue and wakes up the getter on the next event loop iteration only.
The same is true with network protocols: StreamReaderProtocol.data.received() feeds data to StreamReader and wakes await reader.read() after selector.select() call. Custom code that works with asyncio protocols (or loop.sock_recv()) explicitly suffers from the same problem.
If the code uses more moving parts, e.g. protocol->message-parser->user-code, each indirection level adds its own delayed call that increases latency.

I propose letting the loop keep running newly scheduled callbacks for a short, bounded time before it polls for I/O again (“eager processing”).

If after running scheduled callbacks (asyncio.Handler instances) there are new callbacks registered for the next loop iteration, they are executed immediately.

The implementation adds time- and count-based limits for eager callback execution for preventing possible infinite callbacks chain.

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/an-eager-way-to-set-result-on-asyncio-future/106161/27

Linked PRs

Activity

  1. added
    type-feature
    on Oct 27, 2026
  2. YvesDup commented on Oct 27, 2026

    @YvesDup
    Contributor

    The good example is using asyncio.Queue: await q.put(item) pushes an item into the queue and wakes up the getter on the next event loop iteration only.

    If I clearly understand your description, does it cover and fix the following example, that breaks the FIFO's order of a queue ?

    import asyncio
    
    async def simple_exemple():
       n = 0
       q = asyncio.Queue(1)
    
       asyncio.create_task(q.put(n:=n+1))
       print(f"put: {n}")
       asyncio.create_task(q.put(n:=n+1))
       print(f"put: {n}")
       await asyncio.sleep(0.0)
    
       print(f"\tget: {await q.get()}")
    
       q.put_nowait(n:=n+1)
       print(f"put: {n}")
    
       print(f"\tget: {await q.get()}")
       print(f"\tget: {await q.get()}")
    
    asyncio.run(simple_exemple())

    The output result is:

        put: 1
        put: 2
           get: 1
        put: 3
           get: 3
           get: 2
  3. added 6 commits that reference this issue on Oct 28, 2026
  4. asvetlov commented on Oct 29, 2026

    @asvetlov
    ContributorAuthor

    @YvesDup no, the PR doesn't fix the example; the order is the same.

  5. added a commit that references this issue on Nov 3, 2026
  6. self-assigned this
    on Nov 22, 2026
  7. moved this from Todo to In Progress in asyncioon Nov 22, 2026
  8. kumaraditya303 commented on Nov 26, 2026

    @kumaraditya303
    Contributor

    An alternative idea (suggested by Claude) which I think is simpler: instead of running the newly scheduled callbacks in the same iteration, keep the iterations as they are and just skip the select() call when it is redundant.

    When _ready is non-empty, _run_once() already polls with timeout=0. We could skip that call if the last real poll was recent enough (say less than 100 µs ago and less than N iterations ago), and poll as usual otherwise.

    • Batches, callback order and stop() semantics stay exactly the same, so there is no need for _eager_state, the leftover counts or the extra iteration after stop(). The lost-callbacks hang goes away with it.
    • The budget is counted from the last real poll, using the self.time() call _run_once() already makes for timers. A slow batch then forces a poll on the next iteration, so the poll gap can't double.
    • Timers are still checked on every iteration, only the selector call is skipped.
    • asyncio.sleep(0) just sets a "poll on the next iteration" flag.
  9. kumaraditya303 commented on Nov 26, 2026

    @kumaraditya303
    Contributor

    To be clear I am still not convinced how useful this is, this needs to be benchmarked on various workloads to check if this is worth adding not just microbenchmarks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

topic-asynciotype-feature

Projects

  • Status
    In Progress

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions