Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions app/database.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import heapq
import os
import time

from peewee import DatabaseProxy, Model
from playhouse.pool import PooledPostgresqlDatabase
Expand All @@ -18,11 +20,32 @@ def init_db(app):
port=int(os.environ.get("DATABASE_PORT", 5432)),
user=os.environ.get("DATABASE_USER", "postgres"),
password=os.environ.get("DATABASE_PASSWORD", "postgres"),
max_connections=20,
max_connections=int(os.environ.get("DATABASE_MAX_CONNECTIONS", 20)),
stale_timeout=300,
timeout=10,
)
db.initialize(database)

# Pre-fill the connection pool so startup traffic doesn't thundering-herd PostgreSQL
min_connections = int(os.environ.get("DATABASE_MIN_CONNECTIONS", 10))
warm_conns = []
for _ in range(min_connections):
try:
conn = super(PooledPostgresqlDatabase, database)._connect()
ts = time.time()
database._heap_counter += 1
heapq.heappush(database._connections, (ts, database._heap_counter, conn))
warm_conns.append(conn)
except Exception:
break

pid = os.getpid()
app.logger.info(
"Connection pool pre-filled: %d/%d connections ready (worker pid=%d, max=%d)",
len(warm_conns), min_connections, pid,
int(os.environ.get("DATABASE_MAX_CONNECTIONS", 20)),
)

@app.before_request
def _db_connect():
from flask import request
Expand All @@ -31,7 +54,7 @@ def _db_connect():
return
db.connect(reuse_if_open=True)

@app.teardown_appcontext
@app.teardown_request
def _db_close(exc):
if not db.is_closed():
db.close()
7 changes: 4 additions & 3 deletions compose.dev.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
services:
db:
image: postgres:18-alpine
image: postgres:18
environment:
POSTGRES_DB: hackathon_db
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
command: ["postgres", "-c", "max_connections=200"]
volumes:
- pgdata_dev:/var/lib/postgresql/data
- pgdata_dev:/var/lib/postgresql
ports:
- "5432:5432"
healthcheck:
Expand All @@ -16,7 +17,7 @@ services:
retries: 5

valkey:
image: valkey/valkey:8-alpine
image: valkey/valkey:8
ports:
- "6379:6379"
healthcheck:
Expand Down
Loading