0
0
FastAPIframework~3 mins

Why WebSockets enable real-time communication in FastAPI - The Real Reasons

Choose your learning style9 modes available
The Big Idea

Discover how WebSockets turn slow waiting into instant action!

The Scenario

Imagine you have a chat app where users want to see new messages instantly. Without WebSockets, the app must keep asking the server repeatedly, "Any new messages?" like knocking on a door every few seconds.

The Problem

This constant asking wastes time and resources. It can slow down the app, cause delays, and make users wait before seeing new messages. It feels clunky and not smooth at all.

The Solution

WebSockets open a direct, always-on connection between the user and the server. This lets the server send new messages immediately without waiting for the user to ask, making communication instant and smooth.

Before vs After
Before
import time
import requests

while True:
    response = requests.get('http://example.com/check_messages')
    if response.json().get('new_message'):
        print('New message!')
    time.sleep(5)
After
from fastapi import WebSocket

async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f'New message: {data}')
What It Enables

It enables real-time apps like live chats, games, and notifications that feel instant and responsive.

Real Life Example

Think of a live sports score app that updates scores the moment a goal is scored, without you refreshing the page.

Key Takeaways

Manual checking for updates is slow and inefficient.

WebSockets keep a constant connection for instant data flow.

This makes apps feel fast, live, and interactive.