توسيع WebSockets باستخدام وسيط Pub/Sub
تعلّم بث رسائل WebSocket عبر عدة مثيلات من FastAPI باستخدام وسيط Redis pub/sub.
توسيع WebSockets باستخدام وسيط Pub/Sub درس مجاني في FastAPI Backend Development Bootcamp على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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.
تعلم FastAPI Backend Development Bootcamp مع معلم ذكاء اصطناعي — مجانًا
اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.
- الدورات
- 21
- الدروس
- 84
الأسئلة الشائعة
هل درس «توسيع WebSockets باستخدام وسيط Pub/Sub» مجاني؟
نعم — نص درس «توسيع WebSockets باستخدام وسيط Pub/Sub» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة FastAPI Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.
ماذا ستتعلم في «توسيع WebSockets باستخدام وسيط Pub/Sub»؟
تعلّم بث رسائل WebSocket عبر عدة مثيلات من FastAPI باستخدام وسيط Redis pub/sub. تتمرن على FastAPI Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ FastAPI Backend Development Bootcamp؟
لا تُشترط خبرة سابقة. FastAPI Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.
كم من الوقت يستغرق درس «توسيع WebSockets باستخدام وسيط Pub/Sub»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس FastAPI Backend Development Bootcamp هذا؟
نعم. كل درس في FastAPI Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- أساسيات بروتوكول WebSocket
- تنفيذ WebSockets في FastAPI
- بناء تطبيق دردشة في الوقت الفعلي
- توسيع WebSockets باستخدام وسيط Pub/Sub