HomeBlog

Connecting FastAPI to a Serverless Database with pool_pre_ping

4 min read
FastAPI connecting to a resilient serverless database in the cloud, with automatic reconnection

Serverless databases like Neon can scale down to zero when not in use. That’s great for saving money, but it means your app might hit a sleeping database and get a broken connection. If you’re running FastAPI on a serverless platform like Google Cloud Run, this is even more likely. You need a way to make sure your app reconnects automatically.

That’s where pool_pre_ping=True comes in. It tells SQLAlchemy to test the database connection before using it. If the connection is dead, SQLAlchemy will reconnect for you. You can read more about SQLAlchemy connection pooling in the official documentation.

Why pool_pre_ping Matters

Serverless databases can drop connections when they scale down. If your app tries to use a stale connection, you’ll get errors. With pool_pre_ping=True, SQLAlchemy checks the connection before each use. If it’s broken, it reconnects. This keeps your app running smoothly, even if the database was asleep.

Example: Setting Up the Engine

Here’s how you can set up your FastAPI app to use a serverless Postgres database (like Neon) with SQLModel and SQLAlchemy.

from sqlmodel import Session, create_engine
from app.config.main import get_settings

settings = get_settings()

# Check for required environment variables
required_vars = [
    settings.POSTGRES_USER,
    settings.POSTGRES_PASSWORD,
    settings.POSTGRES_HOST,
    settings.POSTGRES_PORT,
    settings.POSTGRES_DATABASE_NAME,
]
if not all(required_vars) or not str(settings.POSTGRES_PORT).isdigit():
    raise ValueError("Database environment variables are missing or invalid. Please check your .env file.")

# Example for Neon (add channel_binding if needed)
SQLALCHEMY_DATABASE_URL = (
    f"postgresql+psycopg2://{settings.POSTGRES_USER}:{settings.POSTGRES_PASSWORD}"
    f"@{settings.POSTGRES_HOST}:{settings.POSTGRES_PORT}/{settings.POSTGRES_DATABASE_NAME}"
    "?sslmode=require&channel_binding=require"
)

engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    pool_pre_ping=True,
)

def get_session():
    """Yields a SQLModel Session instance."""
    with Session(engine) as session:
        yield session

.env File Example

You’ll need a .env file with your database settings. Here’s what it might look like:

POSTGRES_USER=your_user
POSTGRES_PASSWORD=your_password
POSTGRES_HOST=your_host
POSTGRES_PORT=your_port
POSTGRES_DATABASE_NAME=your_database

Want to learn more about organizing your FastAPI settings and using .env files? Read our article on Centralizing Your FastAPI Configuration Settings with Pydantic v2 and .env Files.

Make sure these values match your database provider’s settings. If you’re using NeNeonon, or another cloud Postgres, check their dashboard for the right connection info.

If you need a guide on connecting FastAPI to a SQL database and building CRUD APIs, see: Connecting FastAPI to a Database with SQLModel

Final Thoughts

Using pool_pre_ping=True is a simple way to avoid broken connections with serverless databases. It’s not magic, but it solves a real problem. If you’re running FastAPI on Cloud Run, or using a database that can sleep, add this to your setup. Your app will be more reliable, and you’ll spend less time chasing down connection errors.

About the Author

David Muraya is a Solutions Architect specializing in Python, FastAPI, and Cloud Infrastructure. He is passionate about building scalable, production-ready applications and sharing his knowledge with the developer community. You can connect with him on LinkedIn.

Related Blog Posts

Enjoyed this blog post? Check out these related posts!

How to Set Up a Custom Domain for Your Google Cloud Run service
Building a Flexible Memcached Client for FastAPI

Building a Flexible Memcached Client for FastAPI

Flexible, Safe, and Efficient Caching for FastAPI with Memcached and aiomcache

Read More..

Adding Google Authentication to Your FastAPI Application

Adding Google Authentication to Your FastAPI Application

A guide to adding Google Authentication to your FastAPI app.

Read More..

Managing Background Tasks in FastAPI: BackgroundTasks vs ARQ + Redis

Managing Background Tasks in FastAPI: BackgroundTasks vs ARQ + Redis

A practical guide to background processing in FastAPI, comparing built-in BackgroundTasks with ARQ and Redis for scalable async job queues.

Read More..

Contact Me

Have a project in mind? Send me an email at hello@davidmuraya.com and let's bring your ideas to life. I am always available for exciting discussions.

© 2025 David Muraya. All rights reserved.