Pub/Sub 백플레인으로 WebSockets 확장하기
Redis Pub/Sub 백플레인을 사용해 여러 FastAPI 인스턴스에 WebSocket 메시지를 브로드캐스트하는 방법을 배웁니다.
Pub/Sub 백플레인으로 WebSockets 확장하기은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
“Pub/Sub 백플레인으로 WebSockets 확장하기”에서 뭘 배우나요?
Redis Pub/Sub 백플레인을 사용해 여러 FastAPI 인스턴스에 WebSocket 메시지를 브로드캐스트하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 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에서 WebSockets 구현
- 실시간 채팅 애플리케이션 만들기
- Pub/Sub 백플레인으로 WebSockets 확장하기