Skip to content

fix: ensure SQL storage initializes in Vercel serverless runtime#314

Open
FaiChou wants to merge 1 commit intochenyme:mainfrom
FaiChou:fix/vercel-serverless-db-init
Open

fix: ensure SQL storage initializes in Vercel serverless runtime#314
FaiChou wants to merge 1 commit intochenyme:mainfrom
FaiChou:fix/vercel-serverless-db-init

Conversation

@FaiChou
Copy link

@FaiChou FaiChou commented Mar 12, 2026

Summary

Fixes DB schema not initializing on Vercel serverless deployments even when SERVER_STORAGE_TYPE and SERVER_STORAGE_URL are set.

Root cause

Schema bootstrap depends on storage-backed config loading, which was only triggered in FastAPI lifespan startup. In serverless runtime, lifespan may not run reliably before requests.

Changes

  • Added config.ensure_loaded() with:
    • one-time _loaded flag
    • asyncio.Lock for concurrency-safe first load
  • Added HTTP middleware to call await config.ensure_loaded() before handling requests
  • Replaced lifespan await config.load() with await config.ensure_loaded()

Result

Initialization now works in both traditional and serverless runtimes, with minimal and backward-compatible changes.

Vercel serverless deployments could start serving requests without reliably executing FastAPI lifespan startup, so config.load() was not always called during cold start. Because SQL schema creation is triggered through storage-backed config/tokens access, PostgreSQL/MySQL tables (for example app_config and tokens) were never initialized even when SERVER_STORAGE_TYPE and SERVER_STORAGE_URL were configured.

Add a minimal lazy-init guard in Config with ensure_loaded(), protected by an asyncio lock and a success flag to keep initialization idempotent under concurrent first requests. Wire this guard into an HTTP middleware so initialization is guaranteed before handling requests, and reuse ensure_loaded() in lifespan to preserve existing startup behavior. This keeps the fix small, safe, and backward-compatible while restoring deterministic DB bootstrapping on Vercel.
@FaiChou
Copy link
Author

FaiChou commented Mar 12, 2026

this bug: #243 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant