Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Storage and Data

Databases from Serverless

Connect serverless functions to Postgres and other databases: connection pooling, HTTP drivers, region placement, marketplace integrations, migrations and avoiding connection exhaustion.

Neither Vercel nor Netlify runs a database of its own design that you must use: you pick a provider, usually through an integration, and connect from your functions. Postgres (often Neon or Supabase), MySQL (PlanetScale-style services), MongoDB Atlas, SQLite-in-the-cloud services like Turso, and Redis are all common. The tricky part is not choosing one; it is connecting to it from a platform where code runs in many short-lived instances.

The platforms and database services cannot run here. SQL and driver snippets are read-only sketches; check each provider's docs for current package names. The runnable code is a JavaScript stand-in that models connection limits, which is the main trap.

Why serverless changes database use

A traditional server opens a handful of connections and reuses them for months. Serverless scales out: a traffic spike can start hundreds of function instances at once, each opening its own connection. A Postgres server typically allows only a few hundred connections in total, and each one costs memory. Result: "too many connections" errors at exactly the moment you are popular.

Three techniques fix this:

  1. A connection pooler (such as PgBouncer, built into providers like Neon and Supabase as a pooled connection string). Many function instances share a small set of real connections. Use the pooled URL from the provider for serverless code, and the direct URL for migrations.
  2. HTTP or WebSocket drivers (for example Neon's serverless driver or Turso's client). They send each query over HTTPS, so no long-lived TCP connection is needed, and they also work in edge runtimes where raw TCP is unavailable.
  3. Reuse connections within an instance. Create the client outside the handler function so warm invocations reuse it:
JavaScript
import { neon } from "@neondatabase/serverless";   // read-only sketch
const sql = neon(process.env.DATABASE_URL);          // created once per instance

export default async function handler(req) {
  const rows = await sql`SELECT id, title FROM posts ORDER BY id DESC LIMIT 10`;
  return Response.json(rows);
}

Always use parameterized queries (the tagged template above parameterizes interpolated values) and never build SQL by concatenating user input.

Region matters

Your function runs in a region, and so does your database. If the function is in the US and the database in Frankfurt, every query pays an ocean-sized round trip, and a page making five queries pays five. Put the function region (a project setting on both platforms) next to the database region, or use a database with read replicas. Fewer, bigger queries beat many small ones.

Getting a database

  • On Vercel: add a storage integration from the Marketplace (Neon for Postgres, Upstash for Redis and others). It creates the database and injects the connection strings as environment variables for each environment.
  • On Netlify: add an extension or integration (for example Neon through Netlify's database offering) or set the connection string yourself as an environment variable. See Build Settings and Environments for how variables are scoped: keep production and preview databases separate so previews cannot damage real data.
  • Anywhere: any database reachable over the internet works if you set its URL as a secret.

Serverless and databases

Many instances Each may open a connection.
Pool Share a few real connections.
HTTP driver No long-lived TCP needed.
Same region Keep function and data close.

Use the pooled URL in functions.

1 / 2

Connection exhaustion, simulated

The stand-in compares two strategies under a burst of 200 simultaneous requests against a database with a limit of 100 connections: one connection per instance, versus a pooler that queues work onto 20 shared connections. Numbers are invented to show the effect.

JS Connection pool stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Migrations and schema

Schema changes are code too. Keep migrations in the repository (Drizzle, Prisma, Knex, or plain SQL files) and apply them in a controlled step, not on every function start. A typical flow is a build command or CI job that runs migrate against the target database before the new version receives traffic. For compatibility with rolling deploys and instant rollbacks (see Rollbacks and Promotions) make changes in two steps: add the new column first, deploy code that uses it, and remove the old one in a later release.

A tiny data-access layer

Wrapping queries in small functions keeps SQL in one place and makes handlers easy to test. This stand-in uses an in-memory array instead of a database and shows pagination, which every list endpoint needs.

JS Repository stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Cursor pagination (WHERE id > ?) stays fast on big tables, while OFFSET gets slower the deeper you page.

Checklist

  • Pooled connection string for functions, direct string for migrations.
  • Client created outside the handler.
  • Function region matches database region.
  • Separate databases (or branches) for production and previews.
  • Parameterized queries only; secrets in environment variables.
  • Timeouts shorter than the function's own limit, so you can return a clean error.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a traffic spike cause 'too many connections' on serverless?

    Scale-out multiplies connections, and a database has a fixed ceiling. A pooler or HTTP driver avoids exhausting it.
  2. 2. Where should you create the database client in a function file?

    Module-level clients survive across invocations in the same warm instance.
  3. 3. What is the main cost of a function and database in different regions?

    Each query pays the round trip, so pages with several queries get noticeably slower.
  4. 4. Which connection URL is right for running migrations?

    Migrations often need session-level features that transaction poolers do not allow, so providers recommend the direct connection.

Summary

  • Serverless scale-out can exhaust database connections.
  • Use pooled URLs or HTTP drivers and create clients once per instance.
  • Keep functions and databases in the same region.
  • Separate production and preview data, and run migrations as a deliberate step.
  • Parameterize queries and keep secrets in environment variables.

Next: Forms and Submissions