Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BrokenResourceError #4041

Closed
9 tasks done
SarloAkrobata opened this issue Oct 12, 2021 · 43 comments
Closed
9 tasks done

BrokenResourceError #4041

SarloAkrobata opened this issue Oct 12, 2021 · 43 comments

Comments

@SarloAkrobata
Copy link

SarloAkrobata commented Oct 12, 2021

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

app.py

import time
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware


app = FastAPI()


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


@app.get("/")
def read_root():
    time.sleep(4)
    return {"Hello": "World"}


if __name__ == "__main__":
    uvicorn.run(app="app:app", port=8000)

script.py

import requests as requests

r = requests.get(f"http://127.0.0.1:8000", timeout=2)

Description

If you trigger script.py, error will appear.
After upgrade fastapi to 0.70.0 In some requests in our application its apearing this error. So what we can do? What is problem?

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "venv/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 398, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "venv/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "venv/lib/python3.8/site-packages/fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "venv/lib/python3.8/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc
  File "venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "venv/lib/python3.8/site-packages/starlette/middleware/base.py", line 57, in __call__
    task_group.cancel_scope.cancel()
  File "venv/lib/python3.8/site-packages/anyio/_backends/_asyncio.py", line 567, in __aexit__
    raise exceptions[0]
  File "venv/lib/python3.8/site-packages/starlette/middleware/base.py", line 30, in coro
    await self.app(scope, request.receive, send_stream.send)
  File "venv/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc
  File "venv/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "venv/lib/python3.8/site-packages/starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "venv/lib/python3.8/site-packages/starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "venv/lib/python3.8/site-packages/starlette/routing.py", line 64, in app
    await response(scope, receive, send)
  File "venv/lib/python3.8/site-packages/starlette/responses.py", line 139, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "venv/lib/python3.8/site-packages/starlette/exceptions.py", line 68, in sender
    await send(message)
  File "venv/lib/python3.8/site-packages/anyio/streams/memory.py", line 205, in send
    raise BrokenResourceError
anyio.BrokenResourceError

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.70.0

Python Version

3.8

Additional Context

No response

@SarloAkrobata SarloAkrobata added the question Question or problem label Oct 12, 2021
@WouldYouKindly
Copy link

This looks like a starlette issue: encode/starlette#1284

@tonal
Copy link

tonal commented Oct 15, 2021

Exception in ASGI application
BrokenResourceError: null
  File "uvicorn/protocols/http/h11_impl.py", line 373, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "starlette/middleware/errors.py", line 181, in __call__
    raise exc
  File "starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "starlette/middleware/base.py", line 57, in __call__
    task_group.cancel_scope.cancel()
  File "anyio/_backends/_asyncio.py", line 567, in __aexit__
    raise exceptions[0]
  File "starlette/middleware/base.py", line 30, in coro
    await self.app(scope, request.receive, send_stream.send)
  File "starlette/exceptions.py", line 82, in __call__
    raise exc
  File "starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "starlette/routing.py", line 64, in app
    await response(scope, receive, send)
  File "starlette/responses.py", line 139, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "starlette/exceptions.py", line 68, in sender
    await send(message)
  File "anyio/streams/memory.py", line 205, in send
    raise BrokenResourceError

Operating System

Linux

FastAPI Version

0.70.0

Python Version

3.9.7

@alejosv
Copy link

alejosv commented Oct 20, 2021

I have the same problem, this is my code:

main.py

# -*- coding: utf-8 -*-


from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from pony.orm import *

from models_pony.name_basics import NameBasics as pn_name_basics

api = FastAPI() 


@api.middleware('http')
async def process_request(request: Request, call_next):
    return await call_next(request)


@api.get('/namebasics/id/{id}')
async def get_namebasic_by_id(id:int):
    with db_session:
         result = (pn_name_basics[id]).to_dict()
    return JSONResponse(result)



@api.get('/namebasics/ncost/{ncost}')
async def get_namebasic_by_ncost(ncost:str):
    with db_session:
        result = (pn_name_basics.get(ncost=ncost)).to_dict()
    return JSONResponse(result)



@api.get('/namebasics/year/{year}')
async def get_namebasic_by_year(year:str):
    with db_session:
        results = select(p for p in pn_name_basics if p.birth_year == year)[:]
        _results = [i.to_dict() for i in results]
        _results = jsonable_encoder(_results)
    return JSONResponse(_results)



@api.get('/namebasics/yearalive/{yearalive}')
async def get_namebasic_by_yearalive(yearalive:str):
    with db_session:
        results = select(p for p in pn_name_basics if p.birth_year == yearalive and p.death_year is None)[:]
        _results = [i.to_dict() for i in results]
        _results = jsonable_encoder(_results)
    return JSONResponse(_results)

Command terminal test

wrk --duration 20s --threads 2 --connections 5 http://0.0.0.0:8000/namebasics/id/1024
Running 20s test @ http://0.0.0.0:8000/namebasics/id/1024
  2 threads and 5 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     8.54ms    9.84ms 112.06ms   91.46%
    Req/Sec   289.56    154.88   565.00     59.00%
  11538 requests in 20.05s, 3.66MB read
Requests/sec:    575.56
Transfer/sec:    187.17KB

Error

[2021-10-20 01:50:45 +0000] [5117] [ERROR] Exception in ASGI application
Traceback (most recent call last):
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/base.py", line 57, in __call__
    task_group.cancel_scope.cancel()
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/_backends/_asyncio.py", line 567, in __aexit__
    raise exceptions[0]
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/_backends/_asyncio.py", line 604, in _run_wrapped_task
    await coro
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/base.py", line 30, in coro
    await self.app(scope, request.receive, send_stream.send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 64, in app
    await response(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/responses.py", line 139, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 68, in sender
    await send(message)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/streams/memory.py", line 205, in send
    raise BrokenResourceError
anyio.BrokenResourceError
[2021-10-20 01:50:45 +0000] [5117] [ERROR] Exception in ASGI application
Traceback (most recent call last):
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/base.py", line 57, in __call__
    task_group.cancel_scope.cancel()
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/_backends/_asyncio.py", line 567, in __aexit__
    raise exceptions[0]
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/_backends/_asyncio.py", line 604, in _run_wrapped_task
    await coro
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/base.py", line 30, in coro
    await self.app(scope, request.receive, send_stream.send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 64, in app
    await response(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/responses.py", line 139, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 68, in sender
    await send(message)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/streams/memory.py", line 205, in send
    raise BrokenResourceError
anyio.BrokenResourceError
[2021-10-20 01:50:45 +0000] [5116] [ERROR] Exception in ASGI application
Traceback (most recent call last):
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/base.py", line 57, in __call__
    task_group.cancel_scope.cancel()
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/_backends/_asyncio.py", line 567, in __aexit__
    raise exceptions[0]
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/_backends/_asyncio.py", line 604, in _run_wrapped_task
    await coro
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/base.py", line 30, in coro
    await self.app(scope, request.receive, send_stream.send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 64, in app
    await response(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/responses.py", line 139, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 68, in sender
    await send(message)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/streams/memory.py", line 205, in send
    raise BrokenResourceError
anyio.BrokenResourceError
[2021-10-20 01:50:45 +0000] [5116] [ERROR] Exception in ASGI application
Traceback (most recent call last):
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/base.py", line 57, in __call__
    task_group.cancel_scope.cancel()
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/_backends/_asyncio.py", line 567, in __aexit__
    raise exceptions[0]
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/_backends/_asyncio.py", line 604, in _run_wrapped_task
    await coro
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/middleware/base.py", line 30, in coro
    await self.app(scope, request.receive, send_stream.send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/routing.py", line 64, in app
    await response(scope, receive, send)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/responses.py", line 139, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/starlette/exceptions.py", line 68, in sender
    await send(message)
  File "/lxcshared/benchmark.git/Python/src/.venv/site-packages/anyio/streams/memory.py", line 205, in send
    raise BrokenResourceError
anyio.BrokenResourceError

Something that strikes me is that the application does not crash. The error is not displayed if I remove the middleware like issues encode/starlette/issues/1284 and the performance of the requests is better.

Test 1

wrk --duration 20s --threads 2 --connections 5 http://0.0.0.0:8000/namebasics/id/1024
Running 20s test @ http://0.0.0.0:8000/namebasics/id/1024
  2 threads and 5 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     3.42ms    5.01ms  90.24ms   92.50%
    Req/Sec   807.40    461.95     1.66k    54.25%
  32149 requests in 20.02s, 10.21MB read
Requests/sec:   1606.09
Transfer/sec:    522.29KB

Test 2

wrk --duration 20s --threads 2 --connections 5 http://0.0.0.0:8000/namebasics/id/1024
Running 20s test @ http://0.0.0.0:8000/namebasics/id/1024
  2 threads and 5 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     2.33ms    4.77ms  60.69ms   95.11%
    Req/Sec     1.34k   326.30     1.85k    87.75%
  53350 requests in 20.00s, 16.94MB read
Requests/sec:   2666.88
Transfer/sec:    867.27KB

Operating System

Linux

Operating System Details

lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 21.04
Release:	21.04
Codename:	hirsute

FastAPI Version

0.70.0

Python Version

3.6.12
pypy 7.3.3 with GCC 10.2.1

Additional Context

Web server: gunicorn 20.1.0 with worker class uvicorn.workers.UvicornWorker

@havardthom
Copy link

This is fixed in Starlette v0.17.0, hopefully FastAPI bumps starlette again on next release

@iamnotagentleman
Copy link

any progress? i have same problem too

@ixuuux
Copy link

ixuuux commented Dec 6, 2021

I hide the error message like this:

async def _hide_anyio_BrokenResourceError(*args, **kwargs):
    # hide `anyio.BrokenResourceError`
    pass

@app.middleware('http')
async def before_each_endpoint(request: Request, call_next: RequestResponseEndpoint):
    response = await call_next(request)
    if await request.is_disconnected():
        # hide `anyio.BrokenResourceError`
        return _hide_anyio_BrokenResourceError
    return response

But I don’t know the hidden dangers of doing this

@alejosv
Copy link

alejosv commented Dec 6, 2021

@ixuuux I think hide the error message it isn't recommended, definitely something wrong happening and this could produce unexpected behaviors, so I do think it's dangerous IMHO.

@ixuuux
Copy link

ixuuux commented Dec 7, 2021

@alejosv Thank you, I am also worried about hiding error messages, so I don’t plan to do this.

@Actticus
Copy link

i catch same error with fastapi==0.70. is there any progress?

@Kvasela
Copy link

Kvasela commented Dec 15, 2021

I've catched the same error with fastapi==0.70
When fastapi configured through gunicorn with uvicorn worker and behind nginx with proxy_pass upstream over unix socket.
In such configuration when xhr request becomes canceled (in browser) throws BrokenResourceError
Canceled requests

@raveenb
Copy link

raveenb commented Dec 24, 2021

i am also facing the same problem, my sentry logs are filled with this error

@Actticus
Copy link

@raveenb I downgraded fastapi version to 0.68.2 and BrokenResourceError is "fixed"

@raveenb
Copy link

raveenb commented Dec 25, 2021

@Actticus thanks for the suggestion, let me give it a try

@nsoranzo
Copy link

nsoranzo commented Jan 8, 2022

This is fixed in Starlette v0.17.0, hopefully FastAPI bumps starlette again on next release

I think this can be closed now that fastapi 0.71.0 bumped Starlette to 0.17.1 .

@havardthom
Copy link

I have tested FastAPI v0.71.0 in my project and the BrokenResourceError is fixed.

@alejosv
Copy link

alejosv commented Jan 11, 2022

I have tested FastAPI v0.71.0 in my project and the BrokenResourceError is fixed.

@havardthom are you use a middleware?

@havardthom
Copy link

I have tested FastAPI v0.71.0 in my project and the BrokenResourceError is fixed.

@havardthom are you use a middleware?

Yes

eliorerz added a commit to eliorerz/bug_master_bot that referenced this issue Jan 14, 2022
…ore details.

Add middleware for handle requests without headers in request.
eliorerz added a commit to eliorerz/bug_master_bot that referenced this issue Jan 14, 2022
…ore details.

Add middleware for handle requests without headers in request.
eliorerz added a commit to eliorerz/bug_master_bot that referenced this issue Jan 14, 2022
…ore details.

Add middleware for handle requests without headers in request.
@henriklindgren
Copy link

This is fixed in Starlette v0.17.0, hopefully FastAPI bumps starlette again on next release

I think this can be closed now that fastapi 0.71.0 bumped Starlette to 0.17.1 .

I have tested FastAPI v0.71.0 in my project and the BrokenResourceError is fixed.

Still seeing this with

starlette==0.17.1
fastapi==0.71.0
BrokenResourceError: null
  File "uvicorn/protocols/http/h11_impl.py", line 373, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "starlette/middleware/errors.py", line 181, in __call__
    raise exc
  File "starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "starlette/middleware/base.py", line 57, in __call__
    task_group.cancel_scope.cancel()
  File "anyio/_backends/_asyncio.py", line 567, in __aexit__
    raise exceptions[0]
  File "starlette/middleware/base.py", line 30, in coro
    await self.app(scope, request.receive, send_stream.send)
  File "starlette/middleware/cors.py", line 84, in __call__
    await self.app(scope, receive, send)
  File "starlette/exceptions.py", line 82, in __call__
    raise exc
  File "starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "starlette/routing.py", line 64, in app
    await response(scope, receive, send)
  File "starlette/responses.py", line 139, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "starlette/exceptions.py", line 68, in sender
    await send(message)
  File "anyio/streams/memory.py", line 205, in send
    raise BrokenResourceError

Using the middleware db session pattern, similar to

@app.middleware('http')
async def db_session_middleware(request, call_next):
    try:
        request.state.db = SessionLocal()
        response = await call_next(request)
        request.state.db.commit()
    except Exception:
        request.state.db.rollback()
        response = Response('Internal server error', status_code=500)
    finally:
        request.state.db.close()
    return response

@prsangappa
Copy link

Still seeing this issue

starlette==0.17.1
fastapi==0.72.0
WouldBlock: null
  File "anyio/streams/memory.py", line 193, in send
    self.send_nowait(item)
  File "anyio/streams/memory.py", line 186, in send_nowait
    raise WouldBlock
BrokenResourceError: null
  File "ddtrace/contrib/asgi/middleware.py", line 178, in __call__
    reraise(exc_type, exc_val, exc_tb)
  File "six.py", line 719, in reraise
    raise value
  File "ddtrace/contrib/asgi/middleware.py", line 173, in __call__
    return await self.app(scope, receive, wrapped_send)
  File "starlette/exceptions.py", line 82, in __call__
    raise exc
  File "starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "starlette/routing.py", line 64, in app
    await response(scope, receive, send)
  File "starlette/responses.py", line 156, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "starlette/exceptions.py", line 68, in sender
    await send(message)
  File "ddtrace/contrib/asgi/middleware.py", line 170, in wrapped_send
    return await send(message)
  File "starlette_exporter/middleware.py", line 132, in wrapped_send
    await send(message)
  File "anyio/streams/memory.py", line 205, in send
    raise BrokenResourceError

@henriklindgren
Copy link

@prsangappa Could you check what version you have for anyio? I went to 3.5.0 now and so far so good (together with fastapi 0.72.0 and starlette 0.17.1). Asking because I saw the following change went into anyio 3.5.0, see agronholm/anyio@3877a80#diff-81debd08048a10458b2748d33fe4c0229c1697dc0faa027ccd6bc9d4262137ffR138

@prsangappa
Copy link

I have anyio 3.5.0.

@henriklindgren
Copy link

so far so good

Nope, got another one

WouldBlock: null
  File "anyio/streams/memory.py", line 193, in send
    self.send_nowait(item)
  File "anyio/streams/memory.py", line 186, in send_nowait
    raise WouldBlock

BrokenResourceError: null
  File "starlette/exceptions.py", line 82, in __call__
    raise exc
  File "starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "starlette/routing.py", line 64, in app
    await response(scope, receive, send)
  File "starlette/responses.py", line 156, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "starlette/exceptions.py", line 68, in sender
    await send(message)
  File "anyio/streams/memory.py", line 205, in send
    raise BrokenResourceError

@github-actions
Copy link
Contributor

Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.

bnewbold added a commit to internetarchive/fatcat-scholar that referenced this issue Mar 22, 2022
Main motivation is to try to fix a 'BrokenResourceError' exception with
FastAPI/starlette:
tiangolo/fastapi#4041
@dimoschi
Copy link

The issue is still relevant. We are running FastApi using uvicorn deployed on a k8s cluster in Digitalocean running 1.22.7-do.0. More information:

Operating System

Debian GNU/Linux 11 (bullseye) - container python:3.10.2-slim

FastAPI Version

0.75.0

Other libraries

anyio==3.5.0
ddtrace==0.59.1
starlette==0.17.1
uvicorn==0.17.6

Python Version

3.10.2

Traceback

Traceback (most recent call last):
  File "starlette/middleware/cors.py", line 84, in __call__
              await self.app(scope, receive, send)
  File "ddtrace/contrib/asgi/middleware.py", line 178, in __call__
              reraise(exc_type, exc_val, exc_tb)
  File "six.py", line 719, in reraise
              raise value
  File "ddtrace/contrib/asgi/middleware.py", line 173, in __call__
              return await self.app(scope, receive, wrapped_send)
  File "starlette/exceptions.py", line 82, in __call__
                  raise exc
  File "starlette/exceptions.py", line 71, in __call__
              await self.app(scope, receive, sender)
  File "fastapi/middleware/asyncexitstack.py", line 21, in __call__
                      raise e
  File "fastapi/middleware/asyncexitstack.py", line 18, in __call__
                      await self.app(scope, receive, send)
  File "starlette/routing.py", line 656, in __call__
                  await route.handle(scope, receive, send)
  File "starlette/routing.py", line 259, in handle
              await self.app(scope, receive, send)
  File "starlette/routing.py", line 64, in app
          await response(scope, receive, send)
  File "starlette/responses.py", line 156, in __call__
          await send({"type": "http.response.body", "body": self.body})
  File "starlette/exceptions.py", line 68, in sender
              await send(message)
  File "ddtrace/contrib/asgi/middleware.py", line 170, in wrapped_send
              return await send(message)
  File "anyio/streams/memory.py", line 205, in send
                  raise BrokenResourceError
anyio.BrokenResourceError

Traceback (most recent call last):
  File "anyio/streams/memory.py", line 193, in send
              self.send_nowait(item)
  File "anyio/streams/memory.py", line 186, in send_nowait
              raise WouldBlock
anyio.WouldBlock

Running the app outside of a docker container on a stand-alone Ubuntu 20.04 LTS server we never experienced this issue.

@cbernet
Copy link

cbernet commented Apr 26, 2022

I just got this issue as well for the first time, with fastapi 0.75.0.
I'm running on a kubernetes cluster from the most recent python 3.9 image.

Maybe it's related : this issue occured only a few days after I set up sentry, with its ASGI middleware : https://docs.sentry.io/platforms/python/guides/asgi/

Here is how I integrated it in FastAPI :

from sentry_sdk.integrations.asgi import SentryAsgiMiddleware


alembic.check_revisions()
app = FastAPI(version="1.1.0")

sentry_url = os.environ.get("SENTRY_URL")
if sentry_url:

    def strip_paths(sampling_context):
        path = sampling_context["asgi_scope"]["path"]
        if path in ["/healthz"]:
            return 0.0
        else:
            return 1.0

    sentry_sdk.init(
        sentry_url,
        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        # traces_sample_rate=0.,
        traces_sampler=strip_paths,
        # before_send=strip_paths,
    )
    app.add_middleware(SentryAsgiMiddleware)

By the way, the exception occured in the /healthz endpoint, that I'm filtering out of sentry. It's quite rare, as Kubernetes makes tens of thousands of calls to this endpoint per day. The exception occured only once so far.

@haf
Copy link

haf commented May 3, 2022

I'm also getting this, very often when using the CPU and network in the same process.

These thing eventually crash the process because they make health checks fail.

ERROR:    event="" timestamp=2022-05-03T06:45:08+0000 name="serve_mmm" source="mid.py:25"
Traceback (most recent call last):
  File "/venv/lib/python3.9/site-packages/anyio/streams/memory.py", line 193, in send
    self.send_nowait(item)
  File "/venv/lib/python3.9/site-packages/anyio/streams/memory.py", line 186, in send_nowait
    raise WouldBlock
anyio.WouldBlock

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/app/svc/serve-mmm/serve_mmm/mid.py", line 23, in __call__
    await self.app(scope, receive, send_wrapper)
  File "/venv/lib/python3.9/site-packages/starlette/middleware/cors.py", line 84, in __call__
    await self.app(scope, receive, send)
  File "/venv/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc
  File "/venv/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/venv/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__
    raise e
  File "/venv/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
    await self.app(scope, receive, send)
  File "/venv/lib/python3.9/site-packages/starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "/venv/lib/python3.9/site-packages/starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "/venv/lib/python3.9/site-packages/starlette/routing.py", line 64, in app
    await response(scope, receive, send)
  File "/venv/lib/python3.9/site-packages/starlette/responses.py", line 156, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "/venv/lib/python3.9/site-packages/starlette/exceptions.py", line 68, in sender
    await send(message)
  File "/app/svc/serve-mmm/serve_mmm/mid.py", line 20, in send_wrapper
    await send(message)
  File "/venv/lib/python3.9/site-packages/opentelemetry/instrumentation/asgi/__init__.py", line 409, in otel_send
    await send(message)
  File "/venv/lib/python3.9/site-packages/anyio/streams/memory.py", line 205, in send
    raise BrokenResourceError

All the middleware you see (like mid.py) just calls the next handler in the middlware chain.

starlette = "0.17.1"
version = "0.75.2"
version = "0.17.6"

Python 3.9.10.

@liavkoren
Copy link

liavkoren commented May 4, 2022

@tiangolo I have a set of files that will reliably, and quickly reproduce an AnyIO stream error when using ContextMiddleware, but don't when ContextMiddleware is removed.

The stack trace is not the same as the ones above -- this test setup raises anyio.EndOfStream, but it involves many of the same same modules as the anyio.BrokenResourceError staclktraces we've been seeing, and seems plausibly related. I put this together because we've been having the same anyio.BrokenResourceError errors in production, using fastapi 0.75.2.

Could this issue be reopened, as there seems to be a number of other people who are also running into this?

@liavkoren
Copy link

We just discovered that replacing ContextMiddleware with RawContextMiddleware in my test fast_app.py makes the anyio.EndOfStream errors go away.

@haf
Copy link

haf commented May 5, 2022

@liavkoren The problem being most of these inheritance:s are deep inside libraries, right?

@liavkoren
Copy link

liavkoren commented May 5, 2022

We switched our CorrelationIdPlugin to use RawContextMiddleware (which doesn't inherit from the starlette baseMiddleware) and deployed that to prod yesterday at 4pm. We haven't had any BrokenResourceErrors since:

app.add_middleware(RawContextMiddleware, plugins=[plugins.CorrelationIdPlugin()])

We have a different service which has never run into this issue, and it sets up middleware like so:


middleware = [
    Middleware(RawContextMiddleware),
    Middleware(ContextMiddleware, plugins=(plugins.CorrelationIdPlugin(),)),
    Middleware(CORSMiddleware...)
]

More of a workaround than a fix (what the heck is RawContextMiddleware doing? How is it different from starlette baseMiddleware? Is this bad? Who knows! I looked at the source for both very briefly and decided that things were not dire enough that I needed to go down those rabbit holes right now.] However, it has silenced the BrokenResourceErrors coming out of our /health endpoint since 4pm yesterday, and all our tests still pass and no one has yelled at us yet so.. cool?

@MrSalman333
Copy link

I just got this issue as well for the first time, with fastapi 0.75.0. I'm running on a kubernetes cluster from the most recent python 3.9 image.

Maybe it's related : this issue occured only a few days after I set up sentry, with its ASGI middleware : https://docs.sentry.io/platforms/python/guides/asgi/

Here is how I integrated it in FastAPI :

from sentry_sdk.integrations.asgi import SentryAsgiMiddleware


alembic.check_revisions()
app = FastAPI(version="1.1.0")

sentry_url = os.environ.get("SENTRY_URL")
if sentry_url:

    def strip_paths(sampling_context):
        path = sampling_context["asgi_scope"]["path"]
        if path in ["/healthz"]:
            return 0.0
        else:
            return 1.0

    sentry_sdk.init(
        sentry_url,
        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        # traces_sample_rate=0.,
        traces_sampler=strip_paths,
        # before_send=strip_paths,
    )
    app.add_middleware(SentryAsgiMiddleware)

By the way, the exception occured in the /healthz endpoint, that I'm filtering out of sentry. It's quite rare, as Kubernetes makes tens of thousands of calls to this endpoint per day. The exception occured only once so far.

same

@stregouet
Copy link

First thanks tiangolo and all others fastapi contributors for providing such a cool and valuable tool!

I'm currently migrating a wsgi app to a full fastapi app and I'm also facing this BrokenResourceError.

Here is a minimal repro:

app.py

import time
from fastapi import FastAPI, Request
from fastapi.middleware.wsgi import WSGIMiddleware

import fla

app = FastAPI()


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


@app.get("/")
def read_root():
    time.sleep(4)
    return {"Hello": "World from fastpi route"}

app.mount("/wsgi", WSGIMiddleware(fla.app), name="flask")

fla.py

import time
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    time.sleep(4)
    return "<p>Hello, World! from flask route</p>"

client.py

import requests

r = requests.get(f"http://127.0.0.1:8000/wsgi/", timeout=2)

I run uvicorn app:app and then python client.py and I get BrokenResourceError.

Finally here is libraries versions:

fastapi           0.77.1
starlette         0.19.1
uvicorn           0.17.6

The relevant part is combination of app.middleware("http") and WSGIMiddleware removing one or the other and then BrokenResourceError disappears. Also note that requesting fastapi route is fine, only wsgi route generates the error.

severo added a commit to huggingface/dataset-viewer that referenced this issue May 17, 2022
severo added a commit to huggingface/dataset-viewer that referenced this issue May 17, 2022
* fix: 🐛 reserve 256M for the API and nginx pods

The API service seems to need about 52M:

```
process_virtual_memory_bytes 7.59681024e+08
process_resident_memory_bytes 5.2195328e+07
```

* fix: 🐛 remove the PrometheusMiddleware to reduce the RAM usage

Hopefully it fixes
#279. See
tiangolo/fastapi#4041
@don4of4
Copy link

don4of4 commented May 26, 2022

@cbernet We are also seeing this issue when using Sentry.io. Did you end up coming up with a solution?

@cbernet
Copy link

cbernet commented May 27, 2022

@don4of4 we didn't try and find a solution as the problem is very rare. It only happened once since my first report. I can't really conclude about sentry. In fact, without sentry, it could be that we would still be unaware of this issue. So maybe sentry simply revealed this issue, and it's unrelated.

@StefanoLia
Copy link

I had this issue as well, but after updating the libraries to these versions it got much better:

fastapi           0.77.1
starlette         0.19.1
uvicorn           0.17.6

Now when the client tries to receive large volume of data (>400MB), it got a 502 Bad Gateway error while FAST API reports 200 on the log file in the server. I am using GZipMiddleware and returning json data.

Have any of you had the same issue or can help me?

Thanks!

@panla
Copy link

panla commented Jul 1, 2022

env

  • fastapi==0.78.0
  • starlette==0.19.1
  • loguru==0.6.0
  • httptools==0.4.0
  • anyio==3.6.1
  • uvicorn==0.17.6
  • uvloop==0.16.0
  • in docker

code

from loguru import logger

logger.remove()

PATH = './x.log'
LEVEL = 'INFO'

logger.add(
    PATH, level=LEVEL, rotation="00:00", backtrace=True, diagnose=True, enqueue=True, compression='tar.gz'
)

error

00:00:08.886 | ERROR    | apps.libs.exception:log_message:20 - Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/anyio/streams/memory.py", line 209, in send
    self.send_nowait(item)
  File "/usr/local/lib/python3.9/site-packages/anyio/streams/memory.py", line 202, in send_nowait
    raise WouldBlock
anyio.WouldBlock

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 93, in __call__
    raise exc
  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
    await self.app(scope, receive, sender)
  File "/usr/local/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__
    raise e
  File "/usr/local/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 670, in __call__
    await route.handle(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 266, in handle
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 68, in app
    await response(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/responses.py", line 162, in __call__
    await send({"type": "http.response.body", "body": self.body})
  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 79, in sender
    await send(message)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in _send
    await send(message)
  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 79, in sender
    await send(message)
  File "/usr/local/lib/python3.9/site-packages/anyio/streams/memory.py", line 221, in send
    raise BrokenResourceError
anyio.BrokenResourceError

desc

had appeared once,
at 00:00 a big log file ---> x.log.tar.gz 
and get error.

don't know whose fault it is, loguru?, fastapi? starlette? anyio?

@JarroVGIT
Copy link
Contributor

Do you use BaseHTTPMiddleware somewhere in your code? Either directly like:

class CustomMiddleware(BaseHTTPMiddleware:
    pass

or indirectly like:

@app.middleware('http')
def middlewarefunc():
    pass

I found that most people above are experiencing this with that particular middleware, which actually uses MemoryStream of anyio.

@tiangolo tiangolo reopened this Feb 27, 2023
Repository owner locked and limited conversation to collaborators Feb 27, 2023
@tiangolo tiangolo converted this issue into discussion #6617 Feb 27, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Projects
None yet
Development

No branches or pull requests