Question: I am developing an API which accesses a MariaDB. I use SQLAlchemy for DB-access and encountered a strange memory leak while inserting data. When I insert data and there is no error, everything is normal. RAM consumption goes up but when the transaction is finished it goes down again as expected. That is not the case when an IntegrityError occurs due to the unique index in the table. Everytime I start a new insert and the error occurs, the ram consumption goes up and never down again. In my project, I use FastAPI and a uvicorn server to run the api, but for further investigation I narrowed down the problem to a compact 90-liner and have the same behaviour. The test script automatically creates the table, but the DB (etetete) has to be created manually. What am I missing here? Python Version 3.12 Latest MariaDB in freshly created Docker Container pip list output: Package Version ----------------- ------- greenlet 3.0.3 mariadb 1.1.10 packaging 24.0 pip 24.0 SQLAlchemy 2.0.29 typing_extensions 4.11.0  Python test script: import time from sqlalchemy import create_engine,Index,String from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import mapped_column from sqlalchemy.orm import Mapped from sqlalchemy.orm import Session class Base(DeclarativeBase): pass class Person(Base): __tablename__ = "person" __table_args__ = ( Index("age","children","number",unique=True), ) id: Mapped[int] = mapped_column(primary_key=True,autoincrement=True) age: Mapped[int] children: Mapped[int] number: Mapped[int] name: Mapped[str] = mapped_column(String(20)) prename: Mapped[str] = mapped_column(String(20)) def generatePersons(nValues): persons = [] for i in range(0,nValues): persons.append(Person( age=i, children=i, number=i, name="Smith", prename="John" )) return persons #DB TEST FUNCTIONS--------------- def testDb(nValues): print("Start") engine = create_engine("mariadb+mariadbconnector://root:12345@localhost:3306/etetete") Base.metadata.create_all(engine) s = Session(engine) persons = generatePersons(nValues) try: s.add_all(persons) s.commit() except Exception as e: print("error" + str(e)) s.rollback() finally: s.expunge_all() s.expire_all() s.close() engine.clear_compiled_cache() engine.dispose() print("End") def testDbContextManager(nValues): print("Start") engine = create_engine("mariadb+mariadbconnector://root:12345@localhost:3306/etetete") Base.metadata.create_all(engine) persons = generatePersons(nValues) with Session(engine) as s: try: s.add_all(persons) s.commit() except Exception as e: print("error"+str(e)) print("End") #---------------DB TEST FUNCTIONS def executeTest(): for i in range(0,100): start = time.time() # testDb(200000) testDbContextManager(200000) end = time.time() res = end - start print("ExecutionTime: " + str(round(res, 2))+"s") input("Once again?") print() executeTest()  I tried several different approaches. With or without context manager. Different SQLAlchemy versions. Using python garbage collector. First flushing and finally committing to DB. I watch the ram consumption with windows task manager, but also used python memory-profiler...

Answer: Ok, after hours and hours of research and many different tries I finally found a solution for this problem. It was no problem with SQLAlchemy, this was Pythons behaviour in exception handling. When the exception occurs, it builds up a stack traceback and since the exception traceback is so large due to the large number of results, it consumes a lot of memory and it never clears this stack traceback. The solution was to simply add this to the except block to manually delete the traceback: e.__traceback__ = None  I implemented this solution after reading this blog post: https://cosmicpercolator.com/2016/01/13/exception-leaks-in-python-2-and-3/