Sobes.tech
Junior — Middle

What can cause a decrease in the performance of an application developed using FastAPI?

sobes.tech AI

Answer from AI

Performance degradation of a FastAPI application can be caused by several reasons:

  • Blocking operations in synchronous code. FastAPI is built on the asynchronous framework Starlette, so if blocking calls are used in handlers (for example, long database operations without an asynchronous driver, file reading/writing), it slows down request processing.

  • Suboptimal database operations. Lack of indexes, slow queries, absence of caching, or using synchronous drivers in asynchronous code.

  • Incorrect server configuration. For example, running the application with a single worker or without using Uvicorn/Gunicorn with multiple workers.

  • Large data volume in responses without compression or pagination.

  • Lack of caching for frequently requested data.

An example of blocking code that will slow down FastAPI:

from fastapi import FastAPI
import time

app = FastAPI()

@app.get("/block")
def blocking_endpoint():
    time.sleep(5)  # blocking delay
    return {"message": "done"}

It is better to use asynchronous calls and avoid blocking the event loop.