Scale Pub/Sub across multiple server instances using Broadcaster
masterTo ensure clients receive messages regardless of which server instance they are connected to, initialize PubSubEndpoint with a broadcaster connection string. This requires installing the appropriate backend dependencies (e.g., Redis, Postgres, or Kafka).
Required dependencies:
- Redis:
pip install fastapi_websocket_pubsub[redis] - Postgres:
pip install fastapi_websocket_pubsub[postgres] - Kafka:
pip install fastapi_websocket_pubsub[kafka] - All:
pip install fastapi_websocket_pubsub[all]
Implementation pattern:
When using a broadcaster, you must manually handle the websocket route by calling endpoint.main_loop(websocket) within your websocket endpoint.
app = FastAPI()
# Use a broadcaster backend (e.g., Postgres) to sync instances
endpoint = PubSubEndpoint(broadcaster="postgres://localhost:5432/")
@app.websocket("/pubsub")
async def websocket_rpc_endpoint(websocket: WebSocket):
# Manually route the websocket to the pubsub main loop
await endpoint.main_loop(websocket)