How to trigger message send of Fastapi websocket outside of Fastapi app
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
FastAPI WebSocket connections are managed inside the ASGI application context, so you cannot directly call websocket.send_text() from outside a route handler. To send messages from background tasks, external services, or other parts of your application, you need a shared connection manager that stores active WebSocket connections and exposes a method to broadcast or send targeted messages. Common patterns include an in-memory connection manager, Redis pub/sub for multi-process setups, or an asyncio queue bridge.
Basic WebSocket Setup in FastAPI
The websocket object only exists inside this handler. Once the handler returns, the connection is closed. To send messages from elsewhere, you need to store a reference to the connection.
Connection Manager Pattern
Create a class that tracks active connections and provides send/broadcast methods:
Sending from an HTTP Endpoint
The simplest way to trigger a WebSocket message externally — call an HTTP endpoint that uses the connection manager:
External services can trigger WebSocket messages by making HTTP POST requests to these endpoints.
Sending from a Background Task
Use FastAPI's BackgroundTasks or a standalone asyncio task:
Since the background task runs in the same asyncio event loop as FastAPI, it can directly call manager.broadcast().
Using an Asyncio Queue Bridge
For decoupling message producers from the WebSocket handler:
Multi-Process Setup with Redis Pub/Sub
When running multiple FastAPI workers (e.g., with Gunicorn), an in-memory connection manager only knows about connections on its own worker. Use Redis pub/sub to broadcast across workers:
This works from any process that can connect to Redis — background workers, Celery tasks, separate microservices, or management scripts.
Common Pitfalls
- Calling
websocket.send_text()from a different thread: WebSocket objects are not thread-safe. If you callsend_text()from a thread (e.g., a synchronous background job), useasyncio.run_coroutine_threadsafe(coro, loop)to schedule the send on the event loop. - In-memory manager with multiple workers: Gunicorn with multiple workers runs separate Python processes, each with its own connection manager. Client A connected to worker 1 cannot receive messages sent through worker 2's manager. Use Redis pub/sub or a shared message broker.
- Not handling
WebSocketDisconnect: If a client disconnects and you try to send a message,send_text()raises an exception. Always handleWebSocketDisconnectand remove the connection from the manager. - Blocking the event loop: Calling synchronous (blocking) functions in the WebSocket handler or background task blocks the entire event loop, preventing all WebSocket connections from sending or receiving. Use
awaitfor I/O or run blocking code inasyncio.to_thread(). - Memory leaks from stale connections: If
disconnect()is not called when clients drop (network failure without clean close), the connection manager accumulates dead WebSocket references. Implement periodic health checks or heartbeat pings to detect and clean up stale connections.
Summary
- Store active WebSocket connections in a
ConnectionManagerclass accessible throughout the app - Send messages from HTTP endpoints by calling
manager.send_to()ormanager.broadcast() - Background tasks in the same event loop can call the manager directly
- Use
asyncio.Queueto decouple message producers from WebSocket handlers - For multi-worker deployments, use Redis pub/sub to broadcast across processes
- Always handle client disconnection and clean up stale connections
Related reading
- How to turn off or handle camelCasing in JSON response ASP.NET Core?
- How to turn on front flash light programmatically in Android?
- How to unit test asynchronous APIs?
- How to update a Map or a List on AWS DynamoDB document API?
- How to truncate the time on a datetime object?
- How to tune parameters in Random Forest, using Scikit Learn?
- How to upload a file and JSON data in Postman?
- How to upload file with python requests?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.