python-backend
/

Asynchronous Programming – Concurrency with Asyncio

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

python-backend

Asynchronous Programming – Concurrency with Asyncio

What is Asynchronous Programming?

Asynchronous programming is a design pattern that allows a unit of work to run separately from the primary application thread. For a Technical Lead building Flutter backends, this is crucial: it allows your server to handle thousands of concurrent API requests (like Gemini AI calls or database queries) without waiting for each one to finish before starting the next. It is about Concurrency, not necessarily parallelism.

The Event Loop Concept

At the heart of Python's asyncio is the Event Loop. Think of it as a central scheduler that manages and distributes execution of different tasks. When a task hits an I/O wait (like a network request), the loop pauses that task and moves to another one, resuming the first only when the data is ready.

  1. Coroutines: Async and Await

To create an asynchronous function, you use the async def syntax. To call it and wait for its result without blocking the loop, you use await. A function defined with async def is called a Coroutine.

PythonRead-only
1
import asyncio

async def fetch_ai_response(prompt):
    print(f"Starting AI task for: {prompt}")
    await asyncio.sleep(2)  # Simulates a non-blocking network call
    return f"Response for {prompt}"

async def main():
    # Running tasks concurrently
    task1 = fetch_ai_response("Flutter Code")
    task2 = fetch_ai_response("Python Logic")
    
    results = await asyncio.gather(task1, task2)
    print(results)

asyncio.run(main())

  1. When to use Async vs. Threading

Choosing the right concurrency model depends on the type of bottleneck your application is facing.

ModelBest ForMechanism
AsyncioI/O Bound (API calls, DB, Files)Single-threaded cooperative multitasking
ThreadingI/O Bound (Legacy code/libraries)Pre-emptive multitasking (OS managed)
MultiprocessingCPU Bound (Video encoding, Math)True parallelism using multiple CPU cores

  1. Common Pitfalls

  • Blocking the Loop: Running a synchronous, time-consuming function (like time.sleep()) inside an async def will freeze the entire event loop.
  • Forgotten Await: Calling a coroutine without await won't execute the function; it will just return a coroutine object.
  • Library Compatibility: Not all libraries support async. For example, use httpx or aiohttp instead of requests for async network calls.

Try it yourself

import asyncio

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"Started at {asyncio.get_event_loop().time()}")
    
    # This runs them concurrently
    await asyncio.gather(
        say_after(1, 'hello'),
        say_after(2, 'world')
    )

    print(f"Finished at {asyncio.get_event_loop().time()}")

asyncio.run(main())

Test Your Knowledge

Q1
of 3

Which keyword is used to pause a coroutine until the awaited task is complete?

A
wait
B
pause
C
await
D
yield
Q2
of 3

What happens if you run a blocking 'time.sleep(5)' inside an async function?

A
It only pauses that specific function
B
It freezes the entire event loop and all other concurrent tasks
C
Python automatically converts it to a non-blocking sleep
D
It throws a SyntaxError
Q3
of 3

Which module is the standard for asynchronous I/O in Python?

A
threading
B
multiprocessing
C
asyncio
D
concurrent.futures

Frequently Asked Questions

Does async make my code run faster?

Not necessarily for a single task. Async makes your application capable of handling more tasks simultaneously. It improves throughput, not necessarily raw execution speed of one task.

What is 'asyncio.run()'?

Introduced in Python 3.7, it is the standard way to run the top-level entry point (main coroutine) and manage the event loop lifecycle automatically.

Can I use async with FastAPI?

Yes! FastAPI is built natively for async. Defining routes as 'async def' allows FastAPI to handle requests extremely efficiently using the Uvicorn ASGI server.

Previous

python security

Next

python fastapi

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.