Pub/SubバックプレーンによるWebSocketsのスケーリング
RedisのPub/Subバックプレーンを使い、複数のFastAPIインスタンス間でWebSocketメッセージをブロードキャストする方法を学びます。
「Pub/SubバックプレーンによるWebSocketsのスケーリング」はCoddyKit上の無料FastAPI Backend Development Bootcampレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはFastAPI Backend Development Bootcamp学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 FastAPI Backend Development Bootcampコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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.
よくある質問
「Pub/SubバックプレーンによるWebSocketsのスケーリング」レッスンは無料ですか?
はい。「Pub/SubバックプレーンによるWebSocketsのスケーリング」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、FastAPI Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 FastAPI Backend Development Bootcampコースには全4レッスンが含まれています。
「Pub/SubバックプレーンによるWebSocketsのスケーリング」で何を学びますか?
RedisのPub/Subバックプレーンを使い、複数のFastAPIインスタンス間でWebSocketメッセージをブロードキャストする方法を学びます。 ブラウザで直接実行するハンズオンコードでFastAPI Backend Development Bootcampを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
FastAPI Backend Development Bootcampを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのFastAPI Backend Development Bootcampは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「Pub/SubバックプレーンによるWebSocketsのスケーリング」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このFastAPI Backend Development Bootcampレッスンでコードを書いて実行できますか?
はい。すべてのFastAPI Backend Development Bootcampレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- WebSocketプロトコルの基礎
- FastAPIでWebSocketを実装する
- リアルタイムチャットアプリケーションの構築
- Pub/SubバックプレーンによるWebSocketsのスケーリング