[Python] FastAPI + ECS: "SessionMiddleware must be installed to access request.session" even...

Discussão em 'Python' iniciado por Stack, Agosto 20, 2025.

  1. Stack

    Stack Membro Participativo

    I’m deploying a FastAPI app to AWS ECS (Fargate) behind an Application Load Balancer (ALB). When I update my ECS task definition, the new tasks fail ALB health checks and the deployment rolls back.

    Logs

    AssertionError: SessionMiddleware must be installed to access request.session
    File "/app/main.py", line 230, in dispatch
    logger.info(f"[{request.url.path}] Session before: {dict(request.session)}")
    File "/usr/local/lib/python3.10/site-packages/starlette/requests.py", line 160, in session
    assert "session" in self.scope, "SessionMiddleware must be installed to access request.session"


    Other requests sometimes return 200 OK, but the health check target is often marked as Unhealthy (500) by the ALB.

    Code In my main.py I am adding SessionMiddleware more than once:

    from starlette.middleware.sessions import SessionMiddleware

    # First one
    app.add_middleware(
    SessionMiddleware,
    secret_key="SECRET",
    session_cookie="session",
    )

    # Later in the file, again:
    app.add_middleware(
    SessionMiddleware,
    secret_key="SECRET" or "fallback",
    session_cookie="genlps_session",
    https_only=True,
    max_age=60 * 60 * 8,
    )

    class SomeCustomMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
    # This line raises AssertionError sometimes
    logger.info(f"[{request.url.path}] Session before: {dict(request.session)}")
    response = await call_next(request)
    logger.info(f"[{request.url.path}] Response status: {response.status_code}")
    return response



    In my middleware logic, I log the session like this:

    logger.info(f"[{request.url.path}] Session before: {dict(request.session)}")


    What I’ve observed

    • If SessionMiddleware isn’t configured properly, request.session raises AssertionError.
    • My ALB health check is currently hitting / (or /docs), which triggers that log line.
    • This seems to cause intermittent 500 responses → ECS marks task unhealthy → deploy rolls back.

    Question

    • Is adding SessionMiddleware twice the reason I’m seeing AssertionError?
    • What’s the correct way to configure sessions in FastAPI/Starlette so request.session is always available?
    • Should I change my ALB health check to hit a dedicated /health endpoint instead of /docs to avoid session-related logic?

    Continue reading...

Compartilhe esta Página