diff --git a/backend/main.py b/backend/main.py
index 59b18a41999816ad154eb244e9a02c8ea0a82c70..3500fb8303598d917f4929bab3ca6c5ac1223873 100644
--- a/backend/main.py
+++ b/backend/main.py
@@ -1,11 +1,11 @@
 import os
 import json
 import tomllib
+from contextlib import asynccontextmanager
 from pathlib import Path
 from fastapi import FastAPI
 from fastapi.middleware.cors import CORSMiddleware
 from fastapi.staticfiles import StaticFiles
-from uvicorn import lifespan
 
 from app import ssl_heidi
 from app.routers import (
@@ -73,15 +73,6 @@ def run_server():
 
 # Get project metadata from pyproject.toml
 project_name, project_version = get_project_metadata()
-app = FastAPI(
-    lifespan=lifespan,
-    title=project_name,
-    description="Backend for next-gen sample management system",
-    version=project_version,
-    servers=[
-        {"url": "https://mx-aare-test.psi.ch:1492", "description": "Default server"}
-    ],
-)
 
 # Determine environment and configuration file path
 environment = os.getenv("ENVIRONMENT", "dev")
@@ -121,18 +112,9 @@ if environment == "dev":
     if not Path(cert_path).exists() or not Path(key_path).exists():
         ssl_heidi.generate_self_signed_cert(cert_path, key_path)
 
-# Apply CORS middleware
-app.add_middleware(
-    CORSMiddleware,
-    allow_origins=["*"],
-    allow_credentials=True,
-    allow_methods=["*"],
-    allow_headers=["*"],
-)
 
-
-@app.on_event("startup")
-def on_startup():
+@asynccontextmanager
+async def lifespan(app: FastAPI):
     print("[INFO] Running application startup tasks...")
     db = SessionLocal()
     try:
@@ -180,10 +162,30 @@ def on_startup():
                 from app.database import load_slots_data
 
                 load_slots_data(db)
+
+        yield
     finally:
         db.close()
 
 
+app = FastAPI(
+    lifespan=lifespan,
+    title=project_name,
+    description="Backend for next-gen sample management system",
+    version=project_version,
+    servers=[
+        {"url": "https://mx-aare-test.psi.ch:1492", "description": "Default server"}
+    ],
+)
+# Apply CORS middleware
+app.add_middleware(
+    CORSMiddleware,
+    allow_origins=["*"],
+    allow_credentials=True,
+    allow_methods=["*"],
+    allow_headers=["*"],
+)
+
 # Include routers with correct configuration
 app.include_router(protected_router, prefix="/protected")
 app.include_router(auth.router, prefix="/auth", tags=["auth"])