Skip to content

Background Tasks stuck other requests when i use a http middleware #4616

@w-Bro

Description

@w-Bro

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

import time

from fastapi import FastAPI, BackgroundTasks, Request, Response
from loguru import logger

app = FastAPI()


@app.middleware("http")
async def logger_request(request: Request, call_next) -> Response:
    logger.debug(f"http middleware [{request.url}]")
    response = await call_next(request)
    return response


class Worker:
    def __init__(self, arg):
        self.arg = arg
        logger.debug(f"worker[{arg}] init")

    def work(self):
        for i in range(10):
            logger.debug(f"worker[{self.arg}] work[{i}]")
            time.sleep(1)


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/work/{worker_id}")
async def work(back_task: BackgroundTasks, worker_id: int):
    worker = Worker(worker_id)
    back_task.add_task(worker.work)

    return {"message": f"work[{worker_id}] created"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

Description

  • router "/work/{worker_id}" would create a task(a sync task, actually) on backgroud, after calling it, other new requests will stuck until the task finish
  • it just happen when i use a http middleware
  • i knew it is a starlette issue but i could not find a solution yet, anybody tell me how to solve this?

Operating System

Windows

Operating System Details

No response

FastAPI Version

0.74.1

Python Version

Python 3.7.10

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions