0
0
FastAPIframework~8 mins

Sending and receiving messages in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: Sending and receiving messages
MEDIUM IMPACT
This affects how quickly messages are sent and received over the network, impacting server response time and user interaction speed.
Handling message sending and receiving in a FastAPI app
FastAPI
from fastapi import FastAPI
import asyncio
app = FastAPI()

@app.post('/send')
async def send_message(message: str):
    # Simulate async processing
    await asyncio.sleep(0.1)
    return {'status': 'sent'}
Using async def and non-blocking await allows server to handle other requests concurrently, improving responsiveness.
📈 Performance GainNon-blocking, reduces INP, improves server throughput
Handling message sending and receiving in a FastAPI app
FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.post('/send')
def send_message(message: str):
    # Simulate heavy processing
    import time
    time.sleep(5)
    return {'status': 'sent'}
Blocking the request with time.sleep delays response, causing slow user experience and server thread blocking.
📉 Performance CostBlocks server worker for 5 seconds, increasing INP and reducing throughput
Performance Comparison
PatternServer BlockingConcurrencyResponse TimeVerdict
Synchronous blocking with time.sleepHigh (blocks worker)Low (serial requests)Slow (delays response)[X] Bad
Asynchronous with await asyncio.sleepLow (non-blocking)High (handles many requests)Fast (quick response)[OK] Good
Rendering Pipeline
Message sending and receiving in FastAPI affects the server's ability to quickly process requests and send responses, which impacts the time until the browser can update UI after user interaction.
Server Processing
Network Transfer
Browser Rendering
⚠️ BottleneckServer Processing when blocking synchronous code is used
Core Web Vital Affected
INP
This affects how quickly messages are sent and received over the network, impacting server response time and user interaction speed.
Optimization Tips
1Avoid blocking calls like time.sleep in FastAPI endpoints.
2Use async def and await for non-blocking message processing.
3Monitor request durations in DevTools Network tab to catch slow responses.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with using time.sleep in a FastAPI message handler?
AIt causes layout shifts in the browser
BIt blocks the server worker, delaying other requests
CIt increases network latency
DIt reduces CSS selector efficiency
DevTools: Network
How to check: Open DevTools, go to Network tab, send a message request, and observe the time taken for the request to complete.
What to look for: Look for long request durations indicating blocking; shorter times indicate better async handling.