fastapi: BrokenResourceError
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
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 15
- Comments: 43 (3 by maintainers)
Commits related to this issue
- Downgrade to fastapi 0.68.2 because of BrokenResourceError exception Ref https://github.com/tiangolo/fastapi/issues/4041 — committed to GNS3/gns3-server by grossmj 3 years ago
- Fix BrokenResourceError on starlette. See https://github.com/tiangolo/fastapi/issues/4041 for more details. Add middleware for handle requests without headers in request. — committed to eliorerz/bug_master_bot by eliorerz 2 years ago
- Fix BrokenResourceError on starlette. See https://github.com/tiangolo/fastapi/issues/4041 for more details. Add middleware for handle requests without headers in request. — committed to eliorerz/bug_master_bot by eliorerz 2 years ago
- Fix BrokenResourceError on starlette. See https://github.com/tiangolo/fastapi/issues/4041 for more details. Add middleware for handle requests without headers in request. — committed to eliorerz/bug_master_bot by eliorerz 2 years ago
- pipenv: update Pipfile.lock Main motivation is to try to fix a 'BrokenResourceError' exception with FastAPI/starlette: https://github.com/tiangolo/fastapi/issues/4041 — committed to internetarchive/fatcat-scholar by bnewbold 2 years ago
- fix: 🐛 remove the PrometheusMiddleware to reduce the RAM usage Hopefully it fixes https://github.com/huggingface/datasets-server/issues/279. See https://github.com/tiangolo/fastapi/issues/4041 — committed to huggingface/datasets-server by severo 2 years ago
- Fix ram in prod (#280) * 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... — committed to huggingface/datasets-server by severo 2 years ago
This is fixed in Starlette v0.17.0, hopefully FastAPI bumps starlette again on next release
Still experiencing this issue:
Do you use
BaseHTTPMiddlewaresomewhere in your code? Either directly like:or indirectly like:
I found that most people above are experiencing this with that particular middleware, which actually uses MemoryStream of anyio.
I have been debugging and trying to replicate this, I used the original example:
With the script:
This means that the server starts handling the request, and before returning the response, the client disconnects. I was only able to replicate the error in an old environment with
starlette-0.15.0, but the error disappeared after upgrading FastAPI to the latest (currently0.75.0) that includes Starlette version0.17.1.I also tried making the server start the response in a streaming response, and making the client close the connection before the server ends sending the response, e.g.:
…but still, that didn’t trigger the exception either.
If anyone is still experiencing this, please help me find a way to replicate your error. The versions of the packages alone don’t seem to be enough to replicate it with the examples above. If you have some particular example that breaks with the current versions and that can be replicated, that would be the best way to figure out what’s happening (if there’s anything still happening) and then solve it, thanks! 🙇
The issue is still relevant. We are running FastApi using
uvicorndeployed on a k8s cluster in Digitalocean running1.22.7-do.0. More information:Operating System
Debian GNU/Linux 11 (bullseye) - container
python:3.10.2-slimFastAPI Version
0.75.0
Other libraries
anyio==3.5.0ddtrace==0.59.1starlette==0.17.1uvicorn==0.17.6Python Version
3.10.2
Traceback
Running the app outside of a docker container on a stand-alone Ubuntu 20.04 LTS server we never experienced this issue.
Seeing this issue on EKS with plenty of resources. We are using ddtrace though I doubt this is causing the issue. We are running using uvicorn as our ASGI server.
deps
full stack trace
App invocation
In case it helps others, We ran into this issue when running in k8s with low memory/cpu limits.
i catch same error with fastapi==0.70. is there any progress?
@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 theanyio.BrokenResourceErrorstaclktraces we’ve been seeing, and seems plausibly related. I put this together because we’ve been having the sameanyio.BrokenResourceErrorerrors 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?
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
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:
We have a different service which has never run into this issue, and it sets up middleware like so:
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?
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 :
By the way, the exception occured in the
/healthzendpoint, 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.I have the same problem, this is my code:
main.py
Command terminal test
Error
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
Test 2
Operating System
Linux
Operating System Details
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
We just discovered that replacing ContextMiddleware with RawContextMiddleware in my test fast_app.py makes the
anyio.EndOfStreamerrors go away.I have tested FastAPI v0.71.0 in my project and the BrokenResourceError is fixed.
I think this can be closed now that fastapi 0.71.0 bumped Starlette to 0.17.1 .
@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.