0
0
FastAPIframework~20 mins

Broadcasting to multiple clients in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Broadcasting Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when multiple clients connect to a FastAPI WebSocket endpoint using a shared broadcaster?

Consider a FastAPI WebSocket endpoint that uses a single broadcaster instance to send messages to all connected clients. What is the expected behavior when three clients connect and one client sends a message?

FastAPI
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi_broadcast import Broadcast

app = FastAPI()
broadcaster = Broadcast("memory://")

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    await broadcaster.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await broadcaster.send(data)
    except WebSocketDisconnect:
        await broadcaster.disconnect(websocket)
ANo clients receive any messages because the broadcaster does not support multiple clients.
BOnly the client that sent the message receives it back through the broadcaster.
CAll connected clients receive the message sent by any one client through the broadcaster.
DThe server crashes because multiple clients cannot share the same broadcaster instance.
Attempts:
2 left
💡 Hint

Think about how a broadcaster is designed to distribute messages.

📝 Syntax
intermediate
1:30remaining
Which code snippet correctly initializes a FastAPI Broadcast instance for in-memory broadcasting?

Choose the correct way to create a Broadcast instance that uses in-memory transport for message broadcasting.

Abroadcaster = Broadcast("memory://")
Bbroadcaster = Broadcast("redis://localhost")
Cbroadcaster = Broadcast()
Dbroadcaster = Broadcast("http://memory")
Attempts:
2 left
💡 Hint

Check the URI scheme for in-memory transport.

🔧 Debug
advanced
2:30remaining
Why does this FastAPI WebSocket broadcasting code raise a RuntimeError?

Examine the code below. It raises a RuntimeError: 'Task attached to a different loop'. What is the cause?

FastAPI
from fastapi import FastAPI, WebSocket
from fastapi_broadcast import Broadcast
import asyncio

app = FastAPI()
broadcaster = Broadcast("memory://")

@app.on_event("startup")
async def startup_event():
    await broadcaster.connect()

@app.on_event("shutdown")
async def shutdown_event():
    await broadcaster.disconnect()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    await broadcaster.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await broadcaster.send(data)
    except Exception as e:
        print(e)
AThe code is missing an await before broadcaster.send causing the error.
BThe WebSocket was not accepted before connecting to the broadcaster.
CThe broadcaster URI is invalid causing the RuntimeError.
DThe broadcaster instance was connected in the startup event loop but used in a different event loop for WebSocket connections.
Attempts:
2 left
💡 Hint

Consider how asyncio event loops work with tasks and connections.

state_output
advanced
2:00remaining
What is the value of 'connected_clients' after three clients connect and one disconnects?

Given the code below, what is the value of connected_clients after three clients connect and then one disconnects?

FastAPI
from fastapi import FastAPI, WebSocket
from fastapi_broadcast import Broadcast

app = FastAPI()
broadcaster = Broadcast("memory://")
connected_clients = set()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    connected_clients.add(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await broadcaster.send(data)
    except Exception:
        connected_clients.remove(websocket)
A2
B3
C1
D0
Attempts:
2 left
💡 Hint

Think about how the set changes when clients connect and disconnect.

🧠 Conceptual
expert
3:00remaining
Which statement best describes the role of the Broadcast instance in FastAPI WebSocket communication?

Choose the statement that correctly explains how the Broadcast instance facilitates communication among multiple WebSocket clients in FastAPI.

AIt limits the number of clients that can connect simultaneously to prevent server overload.
BIt acts as a central message hub that receives messages from any client and forwards them to all connected clients, enabling real-time group communication.
CIt encrypts messages between clients to ensure secure peer-to-peer communication without server intervention.
DIt stores all messages permanently and allows clients to retrieve message history on demand.
Attempts:
2 left
💡 Hint

Focus on the broadcasting role rather than storage or security features.