Connect to Amazon RDS for PostgreSQL from Python with psycopg 3: a connection pool sized for RDS limits, verified TLS with the RDS CA bundle, passwords from Secrets Manager or IAM tokens, and the network setup that causes most timeouts.

Amazon RDS for PostgreSQL gives a Python backend a managed Postgres, and connecting is the same psycopg call as for any server. The surprises come from AWS, in security groups that turn a typo into a timeout, TLS required by default, connection limits tied to instance size and IAM tokens that expire after 15 minutes.
This guide uses psycopg 3 and psycopg_pool, the current versions of the most common Postgres driver for Python.
A web app should open a small pool per process and borrow from it, because a Postgres connection is a backend process on the server and opening one per request costs a TLS handshake and authentication each time. The module below uses IAM authentication, and the password section later shows the Secrets Manager variant:
import os
import boto3
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
HOST = os.environ["DB_HOST"] # orders.abc123.eu-west-1.rds.amazonaws.com
rds = boto3.client("rds", region_name="eu-west-1")
def connect_kwargs() -> dict:
# Called for every new connection, so each one gets a fresh 15-minute IAM token.
token = rds.generate_db_auth_token(DBHostname=HOST, Port=5432, DBUsername="app_user")
return {"password": token}
pool = ConnectionPool(
conninfo=(
f"host={HOST} port=5432 dbname=orders user=app_user "
"sslmode=verify-full sslrootcert=/etc/ssl/rds/global-bundle.pem"
),
kwargs=connect_kwargs,
min_size=1,
max_size=10, # per process: multiply by workers and tasks
open=False, # call pool.open() in the app's startup hook
)
def recent_orders(customer_id: int) -> list[dict]:
with pool.connection() as conn:
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"SELECT id, total_cents, created_at FROM orders"
" WHERE customer_id = %s ORDER BY id DESC LIMIT 20",
(customer_id,),
)
return cur.fetchall()
psycopg_pool 3.3 accepts a function for kwargs and calls it for each new connection, which is what makes IAM tokens work in a long-running pool. With FastAPI or another async framework, the same options apply to AsyncConnectionPool, opened in the lifespan handler.
RDS for PostgreSQL 15 and later sets rds.force_ssl to 1 in the default parameter group, so unencrypted connections are refused. sslmode=require encrypts but accepts any certificate, while verify-full also checks that the server certificate is signed by the RDS CA and matches the hostname. Download the global certificate bundle into the image at build time:
The common setup keeps the master password or an app user's password in Secrets Manager, read once at startup and passed as password in kwargs. RDS can manage the master password in Secrets Manager and rotate it, which means the app has to fetch it again after an authentication failure.
IAM database authentication replaces the password with a token signed by the app's role. Enable it on the instance, run GRANT rds_iam TO app_user;, and give the role rds-db:connect on arn:aws:rds-db:<region>:<account>:dbuser:<DbiResourceId>/app_user. Tokens are valid for 15 minutes but only at connection time, so open connections stay up after the token expires. AWS recommends staying under about 200 new IAM-authenticated connections per second, which a pool handles easily and a connection-per-request app does not.
A timeout means packets are dropped, which is a network problem and never a password problem. The RDS instance usually sits in private subnets with a security group, and that group needs an inbound rule for TCP 5432 from the security group of the ECS service, Lambda function or EC2 instance running the app. From a laptop, a private instance is unreachable by design, and the way in is a bastion or SSM port forwarding rather than making the database public.
RDS sets max_connections from the instance memory with the formula LEAST({DBInstanceClassMemory/9531392}, 5000), which leaves the smallest instance classes with around a hundred connections, a few of them reserved for administrators. Ten pooled connections across eight Gunicorn workers on four tasks is already 320, so compute the total before scaling out, and use RDS Proxy when many short-lived processes, such as Lambda functions, share one database.
Encore works alongside your Python framework, here FastAPI, as an SDK that declares infrastructure in code, and a Postgres database is a module-level declaration with a migrations directory. Encore for Python is in private beta, and you can request an invite. The host, TLS settings, credentials and pool from the sections above are not in the code at all.

# orders/main.py
import encore
from encore.storage import postgres
from fastapi import FastAPI
# RDS Postgres on AWS, Cloud SQL on GCP, a local Postgres under `encore run`.
db = postgres.Database("orders", migrations="./migrations")
app = FastAPI()
@app.get("/customers/{customer_id}/orders")
async def recent_orders(customer_id: int) -> list[dict]:
return await db.query(
"SELECT id, total_cents, created_at FROM orders"
" WHERE customer_id = $1 ORDER BY id DESC LIMIT 20",
customer_id,
).all()
@app.post("/orders/{order_id}/ship")
async def ship(order_id: int) -> dict:
result = await db.exec("UPDATE orders SET status = 'shipped' WHERE id = $1", order_id)
return {"updated": result.rows_affected == 1}
if __name__ == "__main__":
encore.run(app)
encore run starts Postgres locally and applies the files in ./migrations, such as 1_create_orders.up.sql, before the service starts. The service is registered with an encore.service.json file, and the SDK needs Python 3.9 or later.
On deploy to your own AWS account, the database lands on an RDS for PostgreSQL instance by default, or Aurora if you choose it for the environment, encrypted at rest, in private subnets, and with its own database role for each service, as the AWS infrastructure docs describe. Encore provisions an IAM role for the service, and the security groups between the containers and the storage subnet are part of the same setup, so the timeout section above does not apply.
A coding agent that needs a new table writes the migration and the query in one change and runs them against the local Postgres, where a wrong column fails in seconds instead of in a deploy log.
Request a private-beta invite to try this setup:
Install psycopg[binary] and psycopg_pool, then create a ConnectionPool with the RDS endpoint, database name, user and password, plus sslmode=verify-full and sslrootcert pointing at the RDS global CA bundle. Open the pool at startup and borrow connections with pool.connection() in each request.
A timeout, as opposed to an authentication error, almost always means the network path is closed. Check that the instance's security group allows port 5432 from the app's security group, that the app runs in the same VPC or a peered one, and that you are not trying to reach a private instance from your laptop.
Yes. Enable IAM database authentication on the instance, GRANT rds_iam to the database user, give the app's role rds-db:connect, and pass a token from boto3's generate_db_auth_token as the password. Tokens last 15 minutes, so generate one per new connection rather than once at startup.
The default max_connections is derived from the instance's memory, so small instances allow only a few dozen to a few hundred. Multiply your pool's max_size by the number of processes and tasks to get the actual total, and put RDS Proxy or a smaller pool in front when that total gets close. Encore apps on AWS get the database from the code, with the connection limits set per environment in the dashboard. Encore for Python is in private beta (sign up at /py).
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.