Phase 13 of 25 · Topic 13.4

Asynchronous Generators & async for Iteration

1Concept

An asynchronous generator combines `async def` with `yield`. It produces values asynchronously and is consumed using the `async for` loop, enabling non-blocking memory streaming over WebSockets, Kafka, or SSE channels.

2Architecture Diagram

async for message in message_stream(): ---> Non-blocking async iteration as messages arrive

3Code Example

Python 3.12
import asyncio

async def async_event_stream(count: int):
    for i in range(1, count + 1):
        await asyncio.sleep(0.01) # Simulates network packet arrival
        yield f"Event #{i}"

async def main():
    async for event in async_event_stream(3):
        print(f"Processed: {event}")

asyncio.run(main())

4Expected Output

Processed: Event #1
Processed: Event #2
Processed: Event #3

5Key Takeaways

  • Async generators implement `__aiter__()` and `__anext__()`.
  • `async for` pauses execution between items without blocking the thread.
  • Ideal for streaming LLM completions token-by-token in FastAPI endpoints.