Skip to content

Lesson 7 of 9 · 26m

asyncio Transports and Streams Without Mysticism

Understand the event loop, protocols, transports, and stream helpers — then write async network code that does not block the entire service.

asyncio is not magic parallelism. It is cooperative scheduling over nonblocking I/O. One task runs until it awaits, then another runs. If a task performs blocking work, every connection pauses behind it. Once that mental model lands, asyncio's abstractions stop feeling arbitrary.

Streams are the high-level interface

import asyncio

async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
    while line := await reader.readline():
        writer.write(line.upper())
        await writer.drain()
    writer.close()
    await writer.wait_closed()

async def main():
    server = await asyncio.start_server(handle, "127.0.0.1", 8080)
    async with server:
        await server.serve_forever()

asyncio.run(main())

readline handles buffering across partial reads. writer.write copies data into asyncio's buffer; it does not mean the peer received it. await writer.drain() yields control when buffers are too full, giving the event loop time to flush and preventing memory growth.

Protocols and transports expose the machinery

A Transport owns the socket and writes bytes. A Protocol receives callbacks: connection_made, data_received, connection_lost. Streams are implemented on top of these primitives. Use protocols when you need datagrams, custom buffering, or precise lifecycle control. Use streams for most TCP application code.

class Echo(asyncio.Protocol):
    def connection_made(self, transport):
        self.transport = transport

    def data_received(self, data):
        self.transport.write(data)

Callbacks do not await. If you need async work, schedule it with asyncio.create_task and handle exceptions explicitly.

Cancellation is normal control flow

When a client disconnects, a task times out, or shutdown starts, tasks can be cancelled. asyncio.CancelledError is not a bug in itself. Cleanup belongs in finally or contextlib.aclosing. Swallowing cancellation by catching broad Exception is an old asyncio mistake that causes shutdown hangs.

Never block the loop

These calls are loop poison: time.sleep, synchronous database drivers, CPU-heavy parsing of huge frames, subprocess calls through blocking APIs. Use await asyncio.sleep, async drivers, asyncio.to_thread for bounded blocking work, or a process pool for CPU-bound work. Measure before scattering threads everywhere; a small piece of blocking work can dominate tail latency.

Timeouts belong around operations

asyncio.wait_for(reader.readline(), timeout=5) protects one operation. A connection idle timeout is different from a total request deadline. Decide both. Also handle concurrent shutdown: closing the writer does not guarantee the peer read remaining bytes unless the protocol says so.

Field notes

  • Unhandled task exceptions often appear only at process exit; attach done callbacks or use TaskGroup on modern Python.
  • drain() is mandatory in high-throughput writers, not optional polish.
  • Use asyncio.start_unix_server for trusted local IPC when filesystem permissions are simpler than TCP auth.
  • Debug hangs with asyncio debug mode and slow-task callbacks during development.
  • A single event loop plus a few focused threads is usually simpler than many loops in many threads.

Was this lesson helpful?

Sign in to rate