question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

BackgroundTasks can't work with middleware

See original GitHub issue

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 asyncio
from fastapi import Request, BackgroundTasks, FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


async def test_sleep():
    print('test')
    await asyncio.sleep(9999)


@app.post("/test")
async def test(background_tasks: BackgroundTasks):
    background_tasks.add_task(test_sleep)
    return 'test'


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    response = await call_next(request)
    return response

Description

When use middleware, the second request to ‘http://127.0.0.1:8000/test’ will be pending. If I remove middleware, everything works fine. I know it’s the middleware problem, but I don’t known how to fix it.

Operating System

Linux

Operating System Details

Ubuntu 20.04

FastAPI Version

0.66.1

Python Version

3.9.5

Additional Context

No response

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:2
  • Comments:8

github_iconTop GitHub Comments

2reactions
havardthomcommented, Sep 14, 2021

This is a known starlette issue https://github.com/encode/starlette/issues/919

1reaction
yujiri8commented, May 15, 2022

I’m seeing a probably related issue but with different symptoms than skk294 or the ones described in the starlette issue. Here is my code:

import asyncio
from fastapi import FastAPI, BackgroundTasks, Request

app = FastAPI()

@app.get("/")
def endpoint(bg: BackgroundTasks):
	bg.add_task(f)

async def f():
	print('starting background task')
	await asyncio.sleep(1)
	print('finished background task')

@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
    print('starting middleware')
    response = await call_next(request)
    print('finishing middleware')
    return response

Python 3.10.4, Fastapi 0.78.0, Uvicorn 0.17.6

The symptom is that the background task hangs as soon as it encounters await asyncio.sleep. Future requests will go the same way: I see “finishing middleware”, and “starting background task”, but never “finished background task”. If I remove the middleware, it works.

Interestingly this only happens with asyncio: if I replace asyncio.sleep with time.sleep (and remove the await), it works even with the middleware.

Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI Background task in middleware - Stack Overflow
I'm trying to add background tasks to ...
Read more >
Solve the drawbacks with FastAPI BackgroundTasks - Johachi
Drawbacks of FastAPI's BackgroundTask and how to solve them.
Read more >
CORS (Cross-Origin Resource Sharing) - FastAPI
Import CORSMiddleware . Create a list of allowed origins (as strings). Add it as a "middleware" to your FastAPI application. You can also ......
Read more >
Why you don't need RPA, but Middleware as a Service is the ...
Because not every application used is compatible with the others. Middleware then acts as a translator to mediate between the applications or two...
Read more >
The Background on Background Tasks in .NET 6 - YouTube
There are lots of scenarios for background tasks ranging from a task that ... as well as a deep dive on how these...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found