Prompt
How do I make a serverless function talk to a database?
Latest observation
Oct 25, 2026
OpenAI APIWeb search: off
To make a serverless function talk to a database, you generally do this:
1) Put the database somewhere reachable
Your function can connect to:
- a managed cloud database, like Postgres/MySQL on RDS, Cloud SQL, Azure Database
- a serverless-friendly database, like DynamoDB, Firestore, Supabase, PlanetScale, Neon
- a database exposed through a private network/VPC if your serverless platform supports it
2) Store credentials securely
Do not hardcode username/password in code.
Use:
- environment variables
- secrets managers
- platform secret storage
Example env vars:
DB_HOSTDB_PORTDB_USERDB_PASSWORDDB_NAME
3) Connect in code using a database driver
Example in Node.js for PostgreSQL:
import pg from "pg";
const { Pool } = pg;
const pool = new Pool({
host: process.env.DB_HOST,
port: process.env.DB_PORT || 5432,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
ssl: { rejectUnauthorized: false }
});
export default async function handler(req, res) {
const result = await pool.query("SELECT NOW()");
res.json({ time: result.rows[0].now });
}
4) Reuse connections carefully
Serverless functions scale by creating many short-lived instances. If you open a new DB connection on every request, you can overwhelm the database.
Best practice:
- create the connection pool outside the handler so warm invocations reuse it
- keep pool sizes small
- use a connection pooler if needed
5) Be aware of serverless-specific issues
Common problems:
- cold starts: first request may be slower
- connection limits: too many function instances can exhaust DB connections
- network access: your function may need VPC/private networking
- timeouts: function timeout must exceed query time
- SSL/TLS: some providers require secure connections
6) Consider a proxy/pooler if needed
For high scale, use:
- PgBouncer
- RDS Proxy
- Cloud SQL Auth Proxy
- vendor-managed connection pooling
This helps prevent too many direct DB connections from serverless instances.
7) If possible, use the database’s serverless/data API
Some services avoid direct TCP connections and are easier for serverless:
- DynamoDB
- Firestore
- Supabase client
- Neon serverless driver
- PlanetScale serverless driver
These often work better because they’re designed for ephemeral execution environments.
If you want, I can show you:
- a Node.js AWS Lambda + Postgres example,
- a Python serverless function + database example, or
- the best architecture for your specific cloud.