Scalare i WebSocket con un backplane Pub/Sub
Impari a inviare broadcast dei messaggi WebSocket tra più istanze FastAPI usando un backplane Redis pub/sub.
Scalare i WebSocket con un backplane Pub/Sub è una lezione FastAPI Backend Development Bootcamp gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento FastAPI Backend Development Bootcamp, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
The Multi-Instance Problem
A single FastAPI process can hold WebSocket connections in memory. But in production you run multiple instances behind a load balancer.
A message arriving on instance A cannot reach a client connected to instance B unless the instances share state.
What is a Backplane?
A backplane is a shared messaging channel that every instance subscribes to. When one instance receives an event, it publishes to the backplane and all instances relay it to their local clients.
Redis Pub/Sub
Redis pub/sub is a popular backplane: a PUBLISH to a channel is delivered to every SUBSCRIBEr in real time.
PUBLISH chat:room1 "hello"
SUBSCRIBE chat:room1Local Connection Manager
Each instance still tracks its own connected clients in memory.
class ConnectionManager:
def __init__(self):
self.active = []
async def broadcast_local(self, msg):
for ws in self.active:
await ws.send_text(msg)Publishing to Redis
Instead of broadcasting locally, publish incoming messages to a Redis channel.
import redis.asyncio as redis
r = redis.Redis()
async def publish(channel, message):
await r.publish(channel, message)Subscribing on Startup
Each instance opens a Redis subscription and listens in a background task.
async def listen():
pubsub = r.pubsub()
await pubsub.subscribe("chat:room1")
async for msg in pubsub.listen():
if msg["type"] == "message":
await manager.broadcast_local(msg["data"])Wiring It with Lifespan
Start the listener when the app boots using FastAPI lifespan events.
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app):
task = asyncio.create_task(listen())
yield
task.cancel()The Full Message Flow
Client to instance A then A publishes to Redis then Redis fans out to A and B then each relays to its local clients.
Now any client receives any message regardless of which instance it connected to.
Per-Room Channels
Use one Redis channel per chat room so instances only receive messages relevant to their connected clients.
channel = "chat:" + room_id
await r.publish(channel, payload)Avoiding Echo Loops
Because the publisher also receives its own message via the subscription, broadcast only from the listener, not directly, to avoid sending twice.
Sticky Sessions vs Stateless
With a backplane, instances become effectively stateless for messaging, so you no longer need sticky sessions on the load balancer for delivery to work.
Quick Check
Test your scaling knowledge.
Recap
You learned to scale real-time apps horizontally:
- In-memory managers only reach local clients
- A Redis pub/sub backplane fans messages out across instances
- Use per-room channels and avoid echo loops
This pattern lets WebSocket apps scale to many instances behind a load balancer.
Impara FastAPI Backend Development Bootcamp con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 21
- Lezioni
- 84
Domande Frequenti
La lezione «Scalare i WebSocket con un backplane Pub/Sub» è gratuita?
Sì — il testo completo di «Scalare i WebSocket con un backplane Pub/Sub» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso FastAPI Backend Development Bootcamp, passa a CoddyKit PRO. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.
Cosa imparerò in «Scalare i WebSocket con un backplane Pub/Sub»?
Impari a inviare broadcast dei messaggi WebSocket tra più istanze FastAPI usando un backplane Redis pub/sub. Eserciti FastAPI Backend Development Bootcamp con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare FastAPI Backend Development Bootcamp?
Non è richiesta alcuna esperienza precedente. FastAPI Backend Development Bootcamp su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Scalare i WebSocket con un backplane Pub/Sub»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione FastAPI Backend Development Bootcamp?
Sì. Ogni lezione FastAPI Backend Development Bootcamp include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Fondamenti del protocollo WebSocket
- Implementare WebSocket in FastAPI
- Creare un'applicazione di chat in tempo reale
- Scalare i WebSocket con un backplane Pub/Sub