Concurrency & async/await in FastAPI

Concurrency & async/await in FastAPI

ยท

2 min read

This is part of my #30DaysOfFastAPI challenge. I will be using FastAPI's official documentation, foud here. Feel free to join in ๐Ÿ˜‰.

Introduction to FastAPI

Before we dive in, what is FastAPI? Well, FastAPI is a modern, fast, web framework for building APIs with Python 3.8+ based on standard Python type hints. Some of its key features include:

  • Fast: FastAPI has very high performance, on par with NodeJS and Go.

  • Fast to code.

  • Fewer bugs.

  • Intuitive.

  • Easy to use and learn.

  • Short (minimal code duplication).

  • Robust (Production-ready code with automatic interactive documentation).

  • Standard-based. Fully compatible with the open standards for APIs (OpenAPI).

Explore more about FastAPI here.

What the heck is Asynchronous code?

Asynchronous code simply means that the language has a way for informing the computer/program that at some point in the code, it will need to wait for something else to finish somewhere else.

So, while the "something else" is finishing up, the computer can go do something else.

FastAPI's documentation explains this pretty well in the documentation through the concurrency and burgers example. Check it out here.

Concurrency vs Parallelism.

Concurrency refers to an application that processes multiple tasks at the same time. It is an approach that uses a single processing unit to reduce the system's response time.

Parallelism refers to an application in which tasks are divided into smaller sub-tasks that appear to be processed concurrently or in parallel. Using multiple processors, it increases the system's throughput and computational speed. It allows single sequential CPUs to do many things "seemingly" at the same time.

Explore more about Concurrency vs Parallelism here (GeeksForGeeks) or (FastAPI's concurrent vs parallel burgers).

Async and Await using FastAPI

FastAPI allows you to take advantage of concurrency, which is very common in web development (and the main attraction of NodeJS). However, you can also take advantage of parallelism and multiprocessing (having multiple processes running in parallel) for CPU-bound workloads such as those found in machine learning systems.

Explore more about Async and Await in FastAPI here.

Coroutines.

Coroutine is simply the fancy name for the object returned by an async def function. Python understands that it is a function that can start and end, but can also be paused internally with an await statement.

However, the functionality of using asynchronous code with async and await is frequently summarized as the use of "coroutines". It is similar to Go's main feature, the "Goroutines".

As I conclude, this article relied heavily on FastAPI documentation. It is my preferred method of learning, and please feel free to explore the official documentation here.

ย