Last active
May 9, 2025 13:29
-
-
Save GGontijo/97a928e343be8a9b8047b2fa6d6ed151 to your computer and use it in GitHub Desktop.
finding memory leaks in fastapi applications with tracemalloc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#https://www.geeksforgeeks.org/diagnosing-and-fixing-memory-leaks-in-python/ | |
from contextlib import asynccontextmanager | |
import logging | |
import tracemalloc | |
from fastapi import FastAPI, Request | |
# Start Tracemalloc | |
@asynccontextmanager | |
async def lifespan(app: FastAPI): | |
# Your code here | |
tracemalloc.start() | |
yield | |
tracemalloc.stop() | |
# Take a snapshot after every request | |
@app.middleware("http") | |
async def profile_request(request: Request, call_next): | |
# Uncomment below if you want to take snapshots for just the endpoint execution | |
#tracemalloc.start() | |
response = await call_next(request) | |
#tracemalloc.stop() | |
snapshot = tracemalloc.take_snapshot() | |
top_stats = snapshot.statistics("lineno") | |
logging.info("############################# START #############################") | |
logging.info("Top 10 lines by memory usage:") | |
for stat in top_stats[:10]: | |
logging.info(stat) | |
logging.info("############################## END ##############################") | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment