{"id":916,"hash":"3849e4e936f54b0cd1907564533c6f3289c4553fdbc4b416d76348ac1743ebb8","pattern":"RuntimeError: No response returned in FastAPI when refresh request","full_message":"I got this error in my application and i didn't know why.\nAfter many search and debugging just figured out that it happens when i refresh my request before getting response(cancel request and send another request while processing previous request). Because of that my application need more than 2 seconds to respond, i get too many of this type of error.\n\nSo far i know its from my middleware but i don't know why it happens and what should i do.\n\nAny idea how to fix this issue ?\n\nThis is the error i get:\n\nERROR:    Exception in ASGI application\nTraceback (most recent call last):\n  File \"/usr/local/lib/python3.9/site-packages/anyio/streams/memory.py\", line 81, in receive\n    return self.receive_nowait()\n  File \"/usr/local/lib/python3.9/site-packages/anyio/streams/memory.py\", line 76, in receive_nowait\n    raise WouldBlock\nanyio.WouldBlock\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py\", line 35, in call_next\n    message = await recv_stream.receive()\n  File \"/usr/local/lib/python3.9/site-packages/anyio/streams/memory.py\", line 101, in receive\n    raise EndOfStream\nanyio.EndOfStream\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/usr/local/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py\", line 367, in run_asgi\n    result = await app(self.scope, self.receive, self.send)\n  File \"/usr/local/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py\", line 75, in __call__\n    return await self.app(scope, receive, send)\n  File \"/usr/local/lib/python3.9/site-packages/fastapi/applications.py\", line 208, in __call__\n    await super().__call__(scope, receive, send)\n  File \"/usr/local/lib/python3.9/site-packages/starlette/applications.py\", line 112, in __call__\n    await self.middleware_stack(scope, receive, send)\n  File \"/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py\", line 181, in __call__\n    raise exc\n  File \"/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py\", line 159, in __call__\n    await self.app(scope, receive, _send)\n  File \"/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py\", line 55, in __call__\n    response = await self.dispatch_func(request, call_next)\n  File \"/gateway/./app/core/middlewares.py\", line 26, in dispatch\n    response = await call_next(request)\n  File \"/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py\", line 37, in call_next\n    raise RuntimeError(\"No response returned.\")\nRuntimeError: No response returned.\n\nand this is my middleware:\n\nclass LoggerMiddleWare(BaseHTTPMiddleware):\n\n    def __init__(self, app: ASGIApp):\n        super().__init__(app)\n        self.logger = logging.getLogger(self.__class__.__name__)\n        self.logger.setLevel(logging.INFO)\n        file_handler = logging.FileHandler('api.log')\n        file_handler.setFormatter(JSONFormatter())\n        self.logger.addHandler(file_handler)\n        self.logger.addFilter(APIFilter())\n\n    async def dispatch(self, request: Request, call_next):\n        request.state.services = {}\n        response = await call_next(request)\n        self.logger.info(None, extra={'request': request, 'response': response})\n\n        return response\n\nI'm using fastapi 0.73 and starlette 0.17.1.\n\nTo reproduce this issue, we need to add two middlewares.\n\nA minimal reproducible example can be found here: https://github.com/encode/starlette/issues/1634#issuecomment-1124806406","ecosystem":"pypi","package_name":"fastapi","package_version":null,"solution":"Update: As of 14 Nov 2022, this has been fixed in starlette==0.21.0 and fastapi==0.87.0.\n\nThis is due to how starlette uses anyio memory object streams with StreamingResponse in BaseHTTPMiddleware.\n\nWhen you cancel a request, the ASGI app receives the \"http.disconnect\" message.\nAfter your route function returns, your last middleware will await response(...).\nStreamingResponse's async def __call__ will call self.listen_for_disconnect and then task_group.cancel_scope.cancel() since the request is already disconnected. The stream is closed by the cancellation check in await checkpoint() of MemoryObjectSendStream.send before it has a chance to send the \"http.response.start\" message.\nYour second-to-last and earlier middlewares will encounter anyio.EndOfStream while await recv_stream.receive() in this part of BaseHTTPMiddleware's __call__ method:\ntry:\n    message = await recv_stream.receive()\nexcept anyio.EndOfStream:\n    if app_exc is not None:\n        raise app_exc\n    raise RuntimeError(\"No response returned.\")\n\nassert message[\"type\"] == \"http.response.start\"\n\n#4 is why, to reproduce this issue, we need two middlewares that inherit BaseHTTPMiddleware.\n\nWorkaround 1\nYou can subclass BaseHTTPMiddleware to ignore that exception if the request is disconnected:\n\nclass MyBaseHTTPMiddleware(BaseHTTPMiddleware):\n\n    async def __call__(self, scope, receive, send):\n        try:\n            await super().__call__(scope, receive, send)\n        except RuntimeError as exc:\n            if str(exc) == 'No response returned.':\n                request = Request(scope, receive=receive)\n                if await request.is_disconnected():\n                    return\n            raise\n\n    async def dispatch(self, request, call_next):\n        raise NotImplementedError()\n\nUsage:\n\n# class LoggerMiddleWare(BaseHTTPMiddleware):\nclass LoggerMiddleWare(MyBaseHTTPMiddleware):\n\nWorkaround 2\nActually, only the outermost BaseHTTPMiddleware needs to handle the exception, so you can just implement a SuppressNoResponseReturnedMiddleware and put it as your first middleware:\n\nclass SuppressNoResponseReturnedMiddleware(BaseHTTPMiddleware):\n\n    async def dispatch(self, request, call_next):\n        try:\n            return await call_next(request)\n        except RuntimeError as exc:\n            if str(exc) == 'No response returned.' and await request.is_disconnected():\n                return Response(status_code=HTTP_204_NO_CONTENT)\n            raise\n\nReference: https://github.com/encode/starlette/discussions/1527#discussioncomment-2234702","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/71222144/runtimeerror-no-response-returned-in-fastapi-when-refresh-request","votes":25,"created_at":"2026-04-19T04:51:59.339142+00:00","updated_at":"2026-04-19T04:51:59.339142+00:00"}