Skip to content

Commit

Permalink
Ensure only 1 connection during lambda execution
Browse files Browse the repository at this point in the history
  • Loading branch information
alukach committed Sep 18, 2024
1 parent 267ee40 commit 56c8094
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
29 changes: 15 additions & 14 deletions space2stats_api/src/space2stats/api/db.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Database connection handling."""

from typing import TYPE_CHECKING, Any, Dict, Optional
from typing import TYPE_CHECKING

from fastapi import FastAPI
from psycopg_pool import ConnectionPool
Expand All @@ -11,7 +11,7 @@

async def connect_to_db(
app: FastAPI,
pool_kwargs: Optional[Dict[str, Any]] = None,
**overrides,
) -> None:
"""Connect to Database."""
settings: "Settings" = app.extra.get("settings")
Expand All @@ -20,18 +20,19 @@ async def connect_to_db(
"Settings not found in app.extra. FastAPI app must be initialized with "
"settings provided as a keyword argument."
)
pool_kwargs = pool_kwargs or {}

app.state.pool = ConnectionPool(
conninfo=settings.DB_CONNECTION_STRING,
min_size=settings.DB_MIN_CONN_SIZE,
max_size=settings.DB_MAX_CONN_SIZE,
max_waiting=settings.DB_MAX_QUERIES,
max_idle=settings.DB_MAX_IDLE,
num_workers=settings.DB_NUM_WORKERS,
kwargs=pool_kwargs,
open=True,
)

pool_kwargs = {
"conninfo": settings.DB_CONNECTION_STRING,
"min_size": settings.DB_MIN_CONN_SIZE,
"max_size": settings.DB_MAX_CONN_SIZE,
"max_waiting": settings.DB_MAX_QUERIES,
"max_idle": settings.DB_MAX_IDLE,
"num_workers": settings.DB_NUM_WORKERS,
"open": True,
**overrides,
}

app.state.pool = ConnectionPool(**pool_kwargs)

# Make sure the pool is ready
# ref: https://www.psycopg.org/psycopg3/docs/advanced/pool.html#pool-startup-check
Expand Down
2 changes: 1 addition & 1 deletion space2stats_api/src/space2stats/api/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
@app.on_event("startup")
async def startup_event() -> None:
"""Connect to database on startup."""
await connect_to_db(app)
await connect_to_db(app, max_size=1)


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

0 comments on commit 56c8094

Please sign in to comment.