FastAPI Reverse Proxy
A robust, streaming-capable reverse proxy for FastAPI/Starlette with built-in Latency-Based Load Balancing and Active Health Monitoring.
Features
- Async: Async by default.
- Httpx Pool: Async HTTPX Pool for proxying.
- Streaming Ready: Handles SSE (Server-Sent Events) and large payloads (such as big files) while keeping RAM usage low.
- WebSocket Support: Seamless bidirectional tunneling with automated subprotocol negotiation.
- Unified Load Balancing: Standard Round-Robin or Smart routing using a single utility.
- Latency-Based Routing: Automatically routes traffic to the fastest healthy server (HEAD probe).
- Advanced Overrides: Granular control over headers, body, and HTTP methods.
- Smart Error Mapping: Automatically converts upstream connection failures into standard HTTP 502 (Bad Gateway) and 504 (Gateway Timeout) responses.
- Resilient Handshakes: Customizable
open_timeoutfor WebSockets to prevent proxy hangs during backend connection attempts. - Version Agnostic: Automatically handles
websocketslibrary version differences (12.0+ vs Legacy).
Quick Start
Use the lifespan handler as shown for an easy launch.
The simplest way to use the proxy is to use proxy_pass and/or proxy_pass_websocket on the endpoints.
from fastapi import FastAPI, Request, WebSocket
from contextlib import asynccontextmanager
from fastapi_reverse_proxy import Proxy, proxy_pass, proxy_pass_websocket
@asynccontextmanager
async def lifespan(app: FastAPI):
async with Proxy(app):
yield
app = FastAPI(lifespan=lifespan)
# catch-all route. recommended for a reverse proxy
@app.api_route("/{path:path}", methods=["GET","POST","PUT","DELETE"]) # don't forget to add the methods.
async def index(req: Request):
"""
You always need to pass the "Request" object and to specify the host
If you don't add a path, it will be the same as the original (/login --> http://127.0.0.1/login)
"""
return await proxy_pass(req, "http://127.0.0.1:8080")
🛡️ Resilience & Error Handling
fastapi-reverse-proxy transforms upstream crashes into meaningful HTTPException responses (e.g., 502 Bad Gateway or 504 Gateway Timeout).
This allows you to implement custom failover logic, retry mechanisms, or specific error pages.
For a full implementation of a primary-to-backup failover system, see the example.
Timeout behaviour
Timeouts are configurable independently:
request_timeoutis a hard deadline covering the upstream request (including streamed uploads), response headers, and the complete streamed response. It is disabled by default.connect_timeoutlimits connection establishment.read_timeoutlimits how long the proxy waits for the next piece of upstream response data. For streaming APIs (LLM token streams, SSE, etc.), this is an inactivity timeout between chunks — it does not limit the total generation time as long as data keeps arriving.write_timeoutlimits how long sending request data may take.pool_timeoutlimits how long the request waits for an available connection from the HTTPX pool.- Each phase timeout defaults to
60.0seconds; set an individual value toNoneto disable that phase timeout.
The old timeout parameter remains supported but is deprecated. It acts as a compatibility alias for all four HTTPX phase timeouts: a non-default value applies to phases still set to their defaults, while explicit phase-specific values take priority. Passing timeout=None disables the default phase timeouts unless an explicit phase value overrides it. Prefer the explicit phase parameters for new code.
Example for a local LLM server:
return await proxy_pass(
req,
"http://127.0.0.1:8080",
request_timeout=900.0, # Maximum total request duration: 15 minutes
read_timeout=120.0, # Abort after 2 minutes without upstream data
)
For an indefinitely long-lived stream that should only time out when the upstream stops sending data, set request_timeout=None and configure read_timeout instead. Set an individual phase timeout to None to disable it.
A timeout before response headers are sent can be returned as HTTP 504 Gateway Timeout. Once streaming headers have been sent, the HTTP status cannot be changed; the proxy terminates the stream and closes the upstream response instead.
Advanced Examples:
Check examples for full examples, including:
- Websocket Proxy
- Socket.IO Proxy
- Error Handling & Failover (
examples/error_handling_example.py)
Advanced Proxying
The proxy_pass function and LoadBalancer.proxy_pass provide deep customization for upstream requests:
| Parameter | Type | Description |
|---|---|---|
request_timeout |
float | None |
Hard deadline in seconds for the complete proxied request, including response streaming. Default: None (unlimited). |
connect_timeout |
float | None |
Connection establishment timeout. Default: 60.0; None disables it. |
read_timeout |
float | None |
Maximum wait for upstream response data. Default: 60.0; None disables it. |
write_timeout |
float | None |
Maximum time to send request data upstream. Default: 60.0; None disables it. |
pool_timeout |
float | None |
Maximum wait for an available HTTPX pool connection. Default: 60.0; None disables it. |
timeout |
float | None |
Deprecated compatibility alias for all HTTPX phase timeouts. |
method |
str |
Force a specific HTTP method (e.g., "POST"). |
override_body |
bytes | str | dict | list |
Use this instead of streaming the request body. str is UTF-8 encoded; dict/list are JSON-serialized automatically (automatically sets Content-Type: application/json if not already set). |
additional_headers |
dict |
Append custom headers to the proxied request. |
override_headers |
dict |
Use these headers instead of original request headers. |
forward_query |
bool |
Whether to append the incoming query string (Default: True). |
override_host |
str |
Override the outbound Host header sent to the target (useful for multi-host/virtual-hosting backends that key off the original requested host). |
Monitoring & Configuration
HealthChecker (The Loop Owner)
The proactive component. It owns an internal asyncio background task that monitors backends.
- Immediate Start: When you enter the
async withblock (or callstart()), the checker performs an immediate check of all backends. This eliminates the "cold-start" window where backends are unknown. - Configuration Modes:
- Standard:
HealthChecker(["http://a", "http://b"], ping_path="/health") - Personalized: Pass a list of dictionaries for per-host settings:
checker = HealthChecker([ {"host": "http://api-1", "pingpath": "/v1/status", "maxrequests": 100}, {"host": "http://api-2", "pingpath": "/health"} ])
- Standard:
- Properties:
ping_path: Get or set the global health check path (default:"/").
LoadBalancer (The Decision Utility)
A normal Python object that makes routing decisions based on its source.
- Stateful: While it has no background loop, it does track state (request counts for rate-limiting and the last time it pulled data from the health checker).
- No Lifecycle Needed: It relies on the
HealthChecker(or a static list) for data and doesn't need explicitstart/stopcalls.
WebSocket Refinements
The library implements "deferred negotiation" for WebSockets:
- The proxy receives the client's supported subprotocols from
scope. - It establishes an upstream connection first.
- Once the upstream accepts a protocol, the proxy calls
websocket.accept(subprotocol=...)back to the client. - This ensures the entire tunnel (Client <-> Proxy <-> Upstream) uses the same negotiated protocol.
- Handshake Timeout: Supports a customizable
timeoutparameter (default10.0s) to prevent hangs if the backend is unresponsive. - Error Handling: Raises
fastapi.WebSocketExceptionwhen the upstream connection fails or is rejected with proper WS codes such as 1008 or 1011 - Debug: Disruptions from either side are logged on debug level.
Robustness & Safety
- Termination Safety: Resource cleanup (closing
httpxclients and sockets) is triggered even on task cancellation (BaseException). - Introspection-Based Compatibility: Uses
inspect.signatureto automatically detect version-specific parameters in thewebsocketslibrary. - RFC 7230 Compliant Header Handling: Hop-by-hop headers (
Connection,Transfer-Encoding,TE,Trailers,Keep-Alive,Proxy-Authenticate,Proxy-Authorization) are stripped from both outbound requests and responses, per spec. WebSocket handshake headers (Sec-WebSocket-Key,Upgrade, etc.) from the client are never forwarded to the target, avoiding handshake collisions. - Content-Length Safety: Always stripped from the outbound request and
recalculated by
httpx(or sent chunked when streaming), preventingLocalProtocolErrorwhenoverride_bodydiffers in size from the original request. - Content-Encoding Passthrough: Compressed upstream responses (
gzip,br, etc.) are streamed back to the client raw viaaiter_raw(), withContent-Encodingpreserved — the client decompresses it itself, avoiding corrupted/garbled response bodies.
Running Behind a Reverse Proxy (Nginx/Apache)
By default, proxy_pass and proxy_pass_websocket forward the client's original
headers as-is — they do not set or rewrite X-Real-IP, X-Forwarded-For,
X-Forwarded-Proto, or X-Forwarded-Host. If this library sits behind Nginx or
Apache (the common setup), your upstream server is responsible for setting those
headers before the request reaches this proxy:
location / {
proxy_pass http://your-fastapi-app;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
}
For WebSocket routes, Nginx also needs explicit upgrade handling:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
location /ws/ {
proxy_pass http://your-fastapi-app;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
Without this configuration, X-Forwarded-* headers will be empty or missing by
the time they reach your application.
Streaming & Response Buffering
X-Accel-Buffering: no is set automatically on every proxied response to
disable Nginx's response buffering for streamed content (SSE, chunked
transfers, large file downloads). If deploying behind Apache instead, disable
buffering via your Apache config (mod_proxy directives) — there's no
equivalent response header Apache recognizes.
Metadata
Release files for fastapi-reverse-proxy 0.4.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_reverse_proxy-0.4.1.tar.gz | 20.0 kB | With provenance | Details for fastapi_reverse_proxy-0.4.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_reverse_proxy-0.4.1-py3-none-any.whl | Python 3 | none | any | Details for fastapi_reverse_proxy-0.4.1-py3-none-any.whl |
Total release size: 36.9 kB
Release files / fastapi_reverse_proxy-0.4.1.tar.gz
| Download URL | fastapi_reverse_proxy-0.4.1.tar.gz |
|---|---|
| Size | 20.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3048305be3bf00e82f4872cccaf2030158146dbfceb97174cb77585d2b93b90e
|
|
BLAKE2b-256 checksum How to use checksums |
a387043c110b6e6d3aac0dd7ca940eef347d8ba887f3cdb50d799aeb77e310d1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logRelease files / fastapi_reverse_proxy-0.4.1-py3-none-any.whl
| Download URL | fastapi_reverse_proxy-0.4.1-py3-none-any.whl |
|---|---|
| Size | 17.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e69a1f833611591befc1a1624a86419ccd546188040189ea60fc94f4991290b4
|
|
BLAKE2b-256 checksum How to use checksums |
38e6f85b798ec5c32533b8c61d11bc676c3ad5929187bb0d6b03daf3dd69c3da
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logSecurity for fastapi-reverse-proxy 0.4.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for fastapi_reverse_proxy-0.4.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.