stac-utils / stac-utils/stac-fastapi

mangum does not cache database connection pools

Open
#493 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

documentation
Dominant language
Python
Stars
324
Forks
126
Avg merge
1d 22h
Merged PRs (30d)
10

Description

It appears that mangum runs ASGI lifecycle events (startup, shutdown etc.) on each lambda function invocation instead of run once and cached. This adds an extra ~200ms of runtime to each invocation and can exhaust available database connections unless lambda is calling through a proxy (ex. RDS Proxy) configured to aggressively drop idle connections.

This seems to fix the problem for pgstac:

# app.py

async def connect_to_database(settings: Settings):
    db = DB()
    logger.info("Connecting to database.")
    readpool = await db.create_pool(settings.reader_connection_string, settings)
    writepool = await db.create_pool(settings.writer_connection_string, settings)
    logger.info("Succesfully connected to database.")
    return readpool, writepool

# Define read/write pool in global scope, lambda will cache across invocations.
loop = asyncio.get_event_loop()
READPOOL, WRITEPOOL = loop.run_until_complete(connect_to_database(settings))

# Update startup event.
# Also need to delete the shutdown event.
@app.on_event("startup")
async def startup_event():
    """Connect to database on startup."""
    app.state.readpool = READPOOL
    app.state.writepool = WRITEPOOL

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start from the app.py lifecycle example and trace how FastAPI startup and shutdown events are invoked for each Lambda invocation. Reproduce or inspect the connection-pool behavior across invocations, then verify that pools persist when appropriate and lifecycle setup is not repeated unnecessarily.

Written by the indexing model from the issue text.

Assessment

Tech stack
aws, fastapi, python
Domain
api, backend, cloud, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.