pythonapachefastapireverse-proxyhttp-status-code-502

FastAPI + Apache. 409 response from FastAPI is converted to 502. What can be the reason?


I have a FastAPI application, which, in general, works fine. My setup is Apache as a proxy and FastAPI server behind it. This is the apache config:

ProxyPass /fs http://127.0.0.1:8000/fs retry=1 acquire=3000 timeout=600 Keepalive=On disablereuse=ON
ProxyPassReverse /fs http://127.0.0.1:8000/fs

I have one endpoint that can return 409 HTTP response, if an object exists. FastAPI works correctly. I can see in logs:

INFO:     172.**.0.25:0 - "PUT /fs/Automation/123.txt HTTP/1.1" 409 Conflict

But the final response to the client is "502 Bad Gateway".

Apache error log has a record for this:

[Tue Dec 31 04:45:54.545972 2024] [proxy:error] [pid 3019178:tid 140121168807680] (32)Broken pipe: [client 172.31.0.25:63759] AH01084: pass request body failed to 127.0.0.1:8000 (127.0.0.1), referer: https://10.100.21.13/fs/view/Automation
[Tue Dec 31 04:45:54.545996 2024] [proxy_http:error] [pid 3019178:tid 140121168807680] [client 172.31.0.25:63759] AH01097: pass request body failed to 127.0.0.1:8000 (127.0.0.1) from 172.31.0.25 (), referer: https://10.100.21.13/fs/view/Automation

What can be the reason?

Another interesting thing is that it doesn't happen for any PUT request. How can I debug this? Maybe FastAPI has to return something else, some header? Or it returns too much , some extra data? How to catch this?


Solution

  • So, i have found the reason. When there is file upload you need to read the input buffer in any case, even if you want to return the error. In my case i had to add try: except: to empty the buffer when exception happens. Something like

    try:
         ... my original code
     except Exception as e:
         # Empty input buffer here to avoid proxy problems
         await request.body()
         raise e