0
0
FastAPIframework~8 mins

Startup and shutdown events in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: Startup and shutdown events
MEDIUM IMPACT
This concept affects the initial server readiness time and graceful shutdown, impacting how fast the app starts serving requests and releases resources.
Running heavy blocking code during startup
FastAPI
import asyncio
from fastapi import FastAPI
app = FastAPI()

@app.on_event("startup")
async def startup_event():
    await asyncio.sleep(0)  # Non-blocking placeholder
    print("App started")
Using async non-blocking code allows the server to start quickly without delay.
📈 Performance GainStartup completes immediately, improving LCP and reducing server downtime.
Running heavy blocking code during startup
FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.on_event("startup")
def startup_event():
    import time
    time.sleep(5)  # Blocking delay
    print("App started")
Blocking the event loop during startup delays server readiness, increasing time before it can handle requests.
📉 Performance CostBlocks server startup for 5 seconds, delaying LCP and user interaction.
Performance Comparison
PatternBlocking BehaviorStartup DelayShutdown DelayVerdict
Blocking synchronous startup codeBlocks event loopDelays startup by secondsN/A[X] Bad
Non-blocking async startup codeNon-blockingImmediate startupN/A[OK] Good
No resource cleanup on shutdownN/AN/AProlonged shutdown, leaks[X] Bad
Async resource cleanup on shutdownNon-blockingN/AFast, clean shutdown[OK] Good
Rendering Pipeline
Startup and shutdown events run outside the browser rendering pipeline but affect server readiness and resource cleanup, indirectly impacting user experience by controlling server availability.
Server Initialization
Resource Management
⚠️ BottleneckBlocking synchronous code during startup or shutdown delays server availability.
Optimization Tips
1Avoid blocking synchronous code in startup events to reduce server readiness delay.
2Use asynchronous code for startup and shutdown handlers to keep the server responsive.
3Always clean up resources properly during shutdown to prevent leaks and slow shutdown.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance issue with blocking synchronous code in FastAPI startup events?
AIt delays server readiness and blocks handling requests
BIt increases CSS paint time
CIt causes layout shifts in the browser
DIt reduces JavaScript bundle size
DevTools: Network and Console panels
How to check: Use Network panel to see when server starts responding; check Console for startup logs. During shutdown, monitor server logs and resource release messages.
What to look for: Look for delays in server response after startup and any errors or warnings during shutdown indicating resource leaks.