Bird
Raised Fist0
FastAPIframework~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of broadcasting in FastAPI WebSocket applications?
easy
A. To send the same message to multiple connected clients at once
B. To send a message to only one client at a time
C. To close all client connections simultaneously
D. To authenticate clients before connection

Solution

  1. Step 1: Understand broadcasting concept

    Broadcasting means sending one message to many clients simultaneously.
  2. Step 2: Compare options with broadcasting definition

    Only 'To send the same message to multiple connected clients at once' accurately describes broadcasting.
  3. Final Answer:

    To send the same message to multiple connected clients at once -> Option A
  4. Quick Check:

    Broadcasting = send to many clients [OK]
Hint: Broadcasting means sending one message to many clients [OK]
Common Mistakes:
  • Confusing broadcasting with single client messaging
  • Thinking broadcasting closes connections
  • Mixing broadcasting with authentication
2. Which of the following is the correct way to send a message to all clients in a FastAPI WebSocket manager class?
easy
A. self.connections.send(message)
B. await self.connections.send_text(message)
C. for client in self.connections: client.send(message)
D. for client in self.connections: await client.send_text(message)

Solution

  1. Step 1: Identify correct syntax for sending messages

    In FastAPI WebSocket, sending text requires await and send_text method on each client.
  2. Step 2: Check each option for correct usage

    for client in self.connections: await client.send_text(message) loops through connections and awaits send_text, which is correct. Others miss await or use wrong methods.
  3. Final Answer:

    for client in self.connections: await client.send_text(message) -> Option D
  4. Quick Check:

    Use await and send_text per client [OK]
Hint: Use await and send_text inside a loop for all clients [OK]
Common Mistakes:
  • Forgetting to await send_text
  • Trying to send to all clients at once without loop
  • Using send instead of send_text
3. Given this snippet inside a FastAPI WebSocket manager class:
async def broadcast(self, message: str):
    for connection in self.active_connections:
        await connection.send_text(message)
What happens if self.active_connections is empty when broadcast is called?
medium
A. An IndexError is raised
B. The server crashes with a runtime error
C. No messages are sent and no error occurs
D. The message is sent to a default client

Solution

  1. Step 1: Understand for-loop behavior on empty list

    A for-loop over an empty list runs zero times and does nothing without error.
  2. Step 2: Apply to broadcast method

    If active_connections is empty, the loop sends no messages but does not raise errors.
  3. Final Answer:

    No messages are sent and no error occurs -> Option C
  4. Quick Check:

    Empty list loop = no action, no error [OK]
Hint: Empty loops run zero times without errors [OK]
Common Mistakes:
  • Assuming empty list causes errors
  • Thinking a default client receives message
  • Confusing IndexError with empty iteration
4. You have this code snippet in your FastAPI WebSocket manager:
async def broadcast(self, message: str):
    for connection in self.active_connections:
        connection.send_text(message)
Why does this code cause an error when broadcasting?
medium
A. Missing await before connection.send_text causes coroutine not awaited error
B. send_text is not a valid method on WebSocket connections
C. active_connections should be a dictionary, not a list
D. The for loop syntax is incorrect

Solution

  1. Step 1: Identify async method usage

    send_text is an async method and must be awaited to run properly.
  2. Step 2: Check code for await keyword

    The code calls send_text without await, causing coroutine not awaited error.
  3. Final Answer:

    Missing await before connection.send_text causes coroutine not awaited error -> Option A
  4. Quick Check:

    Async calls need await [OK]
Hint: Always await async send_text calls [OK]
Common Mistakes:
  • Forgetting await on async methods
  • Thinking send_text is synchronous
  • Misunderstanding active_connections type
5. You want to broadcast messages to multiple clients but also remove disconnected clients automatically. Which approach best solves this in a FastAPI WebSocket manager?
hard
A. Use a global variable to track client count instead of connections
B. Wrap send_text in try-except; on exception remove client from active_connections
C. Clear active_connections list before every broadcast
D. Send messages without error handling; disconnected clients are ignored

Solution

  1. Step 1: Understand client disconnection handling

    Disconnected clients cause send_text to raise exceptions when sending messages.
  2. Step 2: Use try-except to catch exceptions and remove clients

    Wrapping send_text in try-except allows removing disconnected clients from active_connections.
  3. Step 3: Evaluate other options

    Other approaches are inadequate: tracking client count with a global variable doesn't manage connections, sending without error handling lets exceptions propagate without cleanup, clearing the list discards active connections too.
  4. Final Answer:

    Wrap send_text in try-except; on exception remove client from active_connections -> Option B
  5. Quick Check:

    Handle errors to remove disconnected clients [OK]
Hint: Use try-except to remove disconnected clients during broadcast [OK]
Common Mistakes:
  • Ignoring exceptions during send
  • Clearing all clients mistakenly
  • Tracking count instead of connections
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard