[Python] How to persist resources across API calls in AWS Lambda with FastAPI and Mangum?

Discussão em 'Python' iniciado por Stack, Maio 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am running a FastAPI application on AWS Lambda using the Mangum adapter. The application is triggered via an Application Load Balancer (ALB). I am facing an issue where certain resources (e.g., files or data) need to be loaded every time the API is called, which causes inefficiency and delays.

    For example:


    • The first API call works fine because the required resources (e.g., information-data.zip) are loaded.


    • However, subsequent calls either fail or reload the same resources unnecessarily, even though the Lambda container is reused.

    Here is my current main.py:

    from fastapi import FastAPI
    from fastapi.responses import RedirectResponse
    from mangum import Mangum
    from src.routers import downloader
    from src.logger import logger

    app = FastAPI()

    @app.get("/", include_in_schema=False)
    async def docs_redirect():
    logger.info("Redirecting to /docs")
    return RedirectResponse(url="/docs")

    app.include_router(downloader.router, prefix="/downloader")

    handler = Mangum(app, lifespan="off")


    And here is my Dockerfile:

    FROM python:3.11.9-slim-bullseye

    WORKDIR /app

    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt

    ENV AB_CONFIG_PATH=/app/src/config/

    COPY . .

    EXPOSE 8000

    CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]


    Questions:


    1. Does disabling the lifespan in Mangum (lifespan="off") help in avoiding resource reloading for every API call? Are there any side effects of doing this?


    2. What is the best way to persist resources (e.g., files or data) across multiple API calls within the same Lambda container lifecycle?


    3. Are there any best practices for managing resource initialization in FastAPI when deployed on AWS Lambda with Mangum?

    I want to ensure that resources are loaded only once per Lambda container lifecycle and reused across multiple API calls to improve efficiency.

    Continue reading...

Compartilhe esta Página