1. Home
  2. Blog
  3. Software Development

Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

asyncio lets one Python program wait on many slow things at once, such as network calls, without threads. We timed sequential versus concurrent code, broke things on purpose, and measured the one mistake that quietly removes every benefit.

10 min read
Python asyncio explained: async, await, gather and TaskGroup with real timings

Key takeaways

  • asyncio runs many waiting tasks on one thread, switching between them at each await.
  • Three 0.5-second waits took 1.52 s one after another and 0.50 s with asyncio.gather.
  • Prefer asyncio.TaskGroup (Python 3.11+): when one task fails, the others are cancelled.
  • A blocking call such as time.sleep inside a coroutine stalls everything. Use async libraries or asyncio.to_thread.

A script fetches data from three APIs, each taking half a second. Run one after another, that is 1.5 seconds of mostly waiting. With asyncio, the program starts all three requests, waits for them together, and finishes in about half a second. That is the whole idea: while one task waits, another can run.

We simulated slow I/O with asyncio.sleep and timed everything on Python 3.13. All timings and outputs below come from that run.

What is asyncio?

asyncio is Python’s built-in library for writing concurrent code with the async and await keywords. It uses an event loop: a scheduler that runs one piece of code at a time and, whenever that code reaches an await on something not ready yet, switches to another task that can make progress. This is called cooperative multitasking. It is similar in spirit to the JavaScript event loop.

It is concurrency, not parallelism. Only one piece of Python code runs at any instant; the gain comes from overlapping the waiting.

When asyncio helps, and when it does not

Workload Best tool
Many network calls, web servers, websockets, chat bots asyncio
A few blocking I/O calls in existing code Threads (concurrent.futures)
Heavy CPU work: maths, image processing, parsing Processes (multiprocessing)
A simple script making one request Plain synchronous code

asyncio shines when there are many things to wait on, from dozens to thousands. It does nothing for code that keeps the CPU busy.

Coroutines and await

import asyncio

async def fetch(name, delay, fail=False):
    await asyncio.sleep(delay)          # stands in for a network call
    if fail:
        raise ConnectionError(f"{name} failed")
    return f"{name} ok"

async def sequential():
    return [await fetch("a", 0.5), await fetch("b", 0.5), await fetch("c", 0.5)]

asyncio.run(sequential())
# ['a ok', 'b ok', 'c ok'] in 1.52s

async def defines a coroutine function. Calling it does not run it; it creates a coroutine object. await runs a coroutine and waits for its result, letting the event loop do other work meanwhile. asyncio.run() starts the event loop and runs the top-level coroutine.

Notice the timing. Awaiting three things one after another is still sequential: 1.52 seconds. Writing async does not make code concurrent by itself.

Running things concurrently with gather

async def concurrent():
    return await asyncio.gather(fetch("a", 0.5), fetch("b", 0.5), fetch("c", 0.5))

# ['a ok', 'b ok', 'c ok'] in 0.50s

asyncio.gather schedules all three at once and waits for all of them. The total time dropped to the longest single wait, 0.50 seconds, three times faster. Results come back in the same order as the arguments, not the order they finished.

Errors with gather

await asyncio.gather(fetch("a", 0.1), fetch("b", 0.2, fail=True))
# gather raised: b failed

await asyncio.gather(fetch("a", 0.1), fetch("b", 0.2, fail=True),
                     return_exceptions=True)
# ['a ok', ConnectionError('b failed')]

By default, the first exception propagates to the caller. A subtle detail: the other awaitables are not cancelled; they keep running in the background. With return_exceptions=True, errors come back as values in the result list, so you can handle each one. That suits jobs where partial success is acceptable, such as checking the status of many URLs.

TaskGroup: structured concurrency

Python 3.11 added asyncio.TaskGroup, which is now the recommended way to run tasks together:

try:
    async with asyncio.TaskGroup() as tg:
        t1 = tg.create_task(fetch("a", 0.1))
        t2 = tg.create_task(fetch("b", 0.05, fail=True))
        t3 = tg.create_task(fetch("c", 1.0))
except* ConnectionError as eg:
    print([str(e) for e in eg.exceptions], t3.cancelled())

# ['b failed'] True

When task b failed, the group cancelled the still-running task c, waited for everything to settle, and raised an ExceptionGroup, caught here with the except* syntax. Nothing was left running in the background. This “all succeed or all stop” behaviour is why it is called structured concurrency, and it prevents a class of bugs where orphaned tasks keep working after their caller has given up. It uses the same async with pattern described in our context managers guide.

Timeouts

try:
    async with asyncio.timeout(0.2):
        await fetch("slow", 1.0)
except TimeoutError:
    print("timeout after 0.2s")

await asyncio.wait_for(fetch("slow", 1.0), 0.2)   # also raises TimeoutError

Every network call should have a timeout; a request that hangs forever can freeze a whole service. asyncio.timeout() (Python 3.11+) can wrap a block of several awaits, while wait_for wraps one. Both cancel the slow operation when time runs out.

The blocking-call mistake

This is the most damaging asyncio bug, because the code still works, just slowly:

async def bad():
    time.sleep(0.5)                          # blocks the whole event loop

async def good():
    await asyncio.to_thread(time.sleep, 0.5) # runs in a worker thread

await asyncio.gather(bad(), bad(), bad())    # 1.50s
await asyncio.gather(good(), good(), good()) # 0.53s

Three “concurrent” calls to bad() took 1.50 seconds, exactly as long as running them in sequence. time.sleep does not await, so the event loop could not switch tasks; everything froze until it finished. The same happens with requests.get(), synchronous database drivers, large file reads and heavy calculations inside a coroutine.

Tip: Run your app with asyncio.run(main(), debug=True) or PYTHONASYNCIODEBUG=1 while developing. Debug mode logs any task step that blocks the event loop for longer than a threshold, which points straight at hidden blocking calls.

Forgetting await

c = fetch("x", 0.01)
print(type(c).__name__)    # coroutine

Without await, you get a coroutine object, not a result, and the code inside never runs. Python warns “coroutine was never awaited” when such an object is garbage-collected, but only at runtime. Type checkers such as mypy can catch many of these mistakes earlier, because the coroutine type does not match what the code expects.

Limiting concurrency

Starting 10,000 requests at once can overwhelm the server you are calling, trip its rate limits, or exhaust your own connections. A semaphore caps how many run at a time:

sem = asyncio.Semaphore(3)

async def job(i):
    async with sem:
        await asyncio.sleep(0.1)

await asyncio.gather(*(job(i) for i in range(10)))
# 10 jobs, limit 3: peak 3, took 0.42s

Never more than three jobs ran at once, and ten 0.1-second jobs finished in about 0.42 seconds, four rounds of up to three. Without the limit they would finish in 0.1 seconds, but a real API might start rejecting requests.

Async libraries

asyncio only helps if the code you call is async too. Common choices include httpx and aiohttp for HTTP, asyncpg and async SQLAlchemy for databases, and FastAPI or Starlette for web servers. For a library with no async version, wrap calls in asyncio.to_thread, as in our good() example. Async code tends to spread: once a function awaits, its callers must be async too, so plan where the async boundary sits in your application.

Testing async code

pytest needs a plugin to run coroutine tests; pytest-asyncio and AnyIO’s pytest plugin are the common choices, letting you write async def test_... functions. Use short fake delays, mock network calls, and include tests for timeouts, cancellation and one task failing among several, since those paths are where async bugs hide. Our pytest fixtures guide covers the setup side.

Should you go async? A quick checklist

  • Is most of the time spent waiting? Measure first. If a request spends 90% of its time in network or database calls, async can help. If it spends that time computing, it will not.
  • Do your libraries support it? An async web framework calling a synchronous database driver gains little and risks blocking the loop.
  • How many things happen at once? Three API calls can be handled fine with a thread pool. Thousands of open connections are where asyncio clearly wins.
  • Is the team ready? Async code changes how errors, cancellation and testing work. Start with one service or one script, not a full rewrite.

Many successful projects mix both: an async web layer for handling many connections, with CPU-heavy work sent to background workers or separate processes.

Final thoughts

asyncio overlaps waiting, not computing. Our three half-second waits dropped from 1.52 to 0.50 seconds with gather, but a single time.sleep in the wrong place erased the gain entirely. Use TaskGroup for related tasks, add timeouts to every external call, cap concurrency with a semaphore, and keep blocking work out of the event loop.

Frequently asked questions

What is asyncio in Python?

asyncio is the standard library for concurrent code using async and await. An event loop switches between tasks whenever one is waiting, so many I/O operations can overlap on a single thread.

Is asyncio faster than threads?

For large numbers of network-bound tasks it is usually more efficient, since tasks are lightweight. For a few blocking calls, threads are simpler. Neither helps CPU-bound work; use processes for that.

What is the difference between gather and TaskGroup?

Both run tasks concurrently. TaskGroup cancels the remaining tasks when one fails and raises an ExceptionGroup. gather by default raises the first error without cancelling the others.

Why is my async code not faster?

Usually because of blocking calls such as time.sleep or requests.get inside coroutines, or because awaits run one after another. Use async libraries, asyncio.to_thread, and gather or TaskGroup.

What happens if I forget await?

You get a coroutine object instead of a result, and its code never runs. Python warns that the coroutine was never awaited.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →