How does serverless Postgres scale to zero work and how is it billed?

Scale to zero means the database's compute layer shuts down when nothing is using it, and it starts again when a client connects. Storage persists independently, so data survives the pause. Teams adopt it for workloads that sit idle most of the day, such as dev branches, preview environments, internal tools and low-traffic tenants, where paying for an always-on instance mostly buys idle CPU.

Billing is split along the same line as the architecture:

Cost component Aurora Serverless v2 Neon Drops to zero when idle?
Compute ACU-hours (capacity × time) Compute-unit hours Yes, if paused
Storage Billed per GB-month Billed per GB-month No
Other I/O, depending on cluster configuration Data transfer, history retention Varies

Only compute can reach zero. Your data has to live somewhere whether or not a query is running, so storage charges continue during a pause.

The autoscaler does not watch CPU alone. Postgres runs a separate backend process for every connection, and each process holds its own memory for buffers, sorts and catalog caches. A few hundred mostly idle connections can push memory pressure high enough to keep capacity elevated while CPU sits near zero. This is why connection count drives the bill: open connections hold compute awake and raise its floor.

Pause behavior, inactivity timeouts and minimum-capacity settings have changed over time on both platforms. Check each provider's current documentation before you base cost estimates on them.

 Clients (apps, preview envs, internal tools)
   |  each open connection = one Postgres backend process
   v
+-----------------------------------------------------------+
| COMPUTE LAYER  (billed: ACU-hours / compute-unit hours)   |
|                                                           |
|  +-----------+ +-----------+ +-----------+                |
|  | backend 1 | | backend 2 | | backend N |  ...           |
|  | own memory| | own memory| | own memory|                |
|  +-----------+ +-----------+ +-----------+                |
|        |             |             |                      |
|        +-------------+-------------+                      |
|                      |                                    |
|                      v                                    |
|  +-----------------------------------------------------+  |
|  | AUTOSCALER inputs: connection count, memory, CPU    |  |
|  | idle, no connections -> pause (compute = 0)         |  |
|  | open connections -> awake, higher floor             |  |
|  +-----------------------------------------------------+  |
+-----------------------------------------------------------+
                              |  reads / writes
                              v
+-----------------------------------------------------------+
| STORAGE LAYER  (billed: GB-month, never drops to zero)    |
| data persists while compute is paused                     |
+-----------------------------------------------------------+

Each client connection becomes a Postgres backend process with its own memory. The autoscaler sizes compute on connection count and memory pressure as well as CPU, so only the compute layer can pause to zero, while storage is billed continuously.

What keeps a serverless Postgres database from pausing?

Most databases that never pause aren't busy. Something holds a connection open, or opens a new one before the inactivity timer runs out. The provider counts any active session as activity, so ten idle connections can keep compute running as reliably as ten thousand queries. Connection behavior, not traffic volume, decides whether you ever reach zero.

Source Why it blocks pausing Typical fix
App pool minimum (min > 0) Idle sessions stay open indefinitely Set minimum to zero, add an idle timeout
Pooler holding server connections Client-side idleness never reaches Postgres Shorten the server idle timeout
Load balancer or Kubernetes probe running SELECT 1 Reconnects every few seconds Probe the process, not the database
Monitoring and metrics agents Scrape on a fixed interval Lengthen the interval or scrape only when awake
ORM migration check at boot Every restart or autoscale event wakes the database Run migrations as a deploy step
Cron jobs Scheduled wake-ups, often hourly Batch them into fewer windows
Developer GUI clients Left connected overnight Set idle_session_timeout on dev roles

To audit, query pg_stat_activity and group by application_name, client_addr, state and state_change. Exclude your own session and background workers. Look for sessions that sit in idle with an old state_change, and for short-lived sessions that keep coming back from the same address. Treat each one as a line item on the bill. Name the owner, state why the session needs to stay open, and work out what it costs in compute hours to keep it there. Sessions with an empty application_name are harder to trace, so require every client to set one.

-- Audit who is holding the database awake.
-- One row per (application, client address, state) bucket.
SELECT
  COALESCE(NULLIF(application_name, ''), '<unset>') AS app,
  client_addr,                       -- NULL means a local Unix socket
  state,
  count(*)                           AS sessions,
  -- How long the longest-idle session in this bucket has been unchanged
  now() - min(state_change)          AS longest_in_state,
  -- Oldest connection: long-lived pool members show up here
  now() - min(backend_start)         AS oldest_connection,
  -- Newest connection: if this is seconds old on every run,
  -- something (probe, scraper, cron) keeps reconnecting
  now() - max(backend_start)         AS newest_connection
FROM pg_stat_activity
WHERE backend_type = 'client backend'  -- skip autovacuum, walwriter, etc.
  AND pid <> pg_backend_pid()          -- skip this audit session
GROUP BY 1, client_addr, state
ORDER BY longest_in_state DESC NULLS LAST;

-- Each row with state = 'idle' and a large longest_in_state is a cost
-- line item: record its owner and why it must stay open.

-- For developer roles, let Postgres close forgotten GUI sessions.
-- idle_session_timeout requires PostgreSQL 14 or later.
ALTER ROLE dev_readonly SET idle_session_timeout = '15min';

A pg_stat_activity audit that groups client sessions by application, address and state to expose long-idle pool connections and frequently reconnecting clients, plus an idle_session_timeout setting for developer roles.

How do you configure your stack so compute actually pauses?

Every service should set application_name in its connection string. With sessions identifiable, the next step is to make sure the application does not hold idle connections open itself.

Let the pool drain to zero

Most pools keep a warm floor of connections by default, and an open connection counts as activity, so the database never pauses. Set the floor to zero and close idle connections quickly. In node-postgres, use min: 0 with idleTimeoutMillis: 10000. In HikariCP, use minimumIdle=0 with a short idleTimeout. Once traffic stops, the pool empties and the provider's inactivity timer can start.

The cost is on the warm path. After a quiet period, the first request pays for a new TCP handshake, TLS negotiation and authentication. For low-traffic services that cost is usually small. For latency-sensitive endpoints, measure it.

Keep the database out of health checks

A liveness or readiness probe that runs SELECT 1 every few seconds keeps compute awake permanently. Point probes at an endpoint such as /healthz that confirms the process is serving requests without touching the database. This creates a gap: nothing now tests whether the database is up. Close it with a separate alert based on provider metrics, such as Aurora's CloudWatch metrics or Neon's console metrics, rather than polling from inside Postgres.

Batch scheduled work

Ten cron jobs spread across the hour can keep the database awake for the whole hour. Group them into one window so compute wakes once, does the work, and idles again.

With these defaults in place, dev and staging databases pause on their own, so nobody has to remember to stop them.

import express from "express";
import { Pool } from "pg";

// Pool configured so it can drain to zero and let the database pause.
const pool = new Pool({
  connectionString: process.env.DATABASE_URL, // e.g. postgres://app:***@db.example.internal/app
  application_name: "orders-api", // makes this service's sessions identifiable in pg_stat_activity
  min: 0,                          // no warm floor: idle connections are not kept open
  max: 10,                         // cap concurrent connections under load
  idleTimeoutMillis: 10_000,       // close connections idle for 10s so the pool empties after traffic stops
  connectionTimeoutMillis: 5_000,  // fail fast if a cold start takes too long
});

const app = express();

// Liveness/readiness probe: confirms the process is serving requests.
// It deliberately does NOT query the database, so probes never wake compute.
// Database availability is alerted on separately, from provider metrics.
app.get("/healthz", (_req, res) => {
  res.status(200).send("ok");
});

// Real traffic is the only thing that opens connections.
// After a quiet period, the first query pays for TCP, TLS and auth setup.
app.get("/orders/:id", async (req, res) => {
  const { rows } = await pool.query(
    "SELECT id, status FROM orders WHERE id = $1",
    [req.params.id]
  );
  res.json(rows[0] ?? null);
});

app.listen(3000);

A node-postgres pool with min 0 and a 10-second idle timeout, paired with a /healthz endpoint that never touches the database, so connections drain and compute can pause when traffic stops.

What does resuming from zero cost in latency and reliability?

The first connection after a pause waits on work the provider skipped while idle. The endpoint accepts the connection, then holds it while compute is scheduled and Postgres starts. Only after that does authentication complete. Even then, shared buffers and the OS page cache are empty, so early queries read from storage instead of memory. Expect higher I/O and slower queries until the working set is cached again.

Client settings have to account for this. A connect timeout tuned for an always-on database can expire before resume finishes, and the application then reports an outage when the database was only waking up. Measure your resume time, set the connect timeout above it, and retry failed connection attempts with exponential backoff and jitter so many clients do not reconnect at the same moment. For example, use a 10-second connect timeout and up to three attempts with backoff starting at 500 ms and doubling each time. Retry connection setup and idempotent statements only. Blindly retrying a write can apply it twice.

Illustrative estimate (assumed numbers, not a benchmark): first-request latency = resume time + cold-cache overhead + normal query time. With an assumed 3 s resume, 0.5 s cold-cache overhead, and 0.2 s normal query time, the first request takes 3 + 0.5 + 0.2 = 3.7 s.

For a low-traffic production API, roughly one request per idle period pays this cost. That pushes up tail latency while median latency stays unchanged. The trade can be acceptable for internal tools and batch endpoints. It is usually not acceptable when a user-facing latency target applies to every request.

import random
import time

import psycopg  # psycopg 3

# Placeholder DSN. Load real credentials from your secret store.
DSN = "postgresql://app_user:CHANGE_ME@db.example.internal:5432/appdb"

CONNECT_TIMEOUT_S = 10   # set above your measured resume time
MAX_ATTEMPTS = 3
BASE_DELAY_S = 0.5       # 0.5 s, then 1 s, before attempts 2 and 3


def connect_with_retry():
    """Retry only connection setup. Never re-run a write blindly."""
    delay = BASE_DELAY_S
    for attempt in range(1, MAX_ATTEMPTS + 1):
        try:
            # connect_timeout is the libpq parameter, in seconds.
            # It covers the time the endpoint holds the connection
            # while compute starts.
            return psycopg.connect(DSN, connect_timeout=CONNECT_TIMEOUT_S)
        except psycopg.OperationalError:
            if attempt == MAX_ATTEMPTS:
                raise  # surface the failure after the last attempt
            # Jitter spreads reconnects so clients that failed together
            # do not all retry at the same moment.
            time.sleep(delay * random.uniform(0.5, 1.5))
            delay *= 2


with connect_with_retry() as conn:
    # Read-only and idempotent, so it would be safe to retry.
    # The first query after a resume reads from storage and runs slower.
    row = conn.execute("SELECT 1").fetchone()
    print(row)

A psycopg 3 connection helper that uses a 10-second libpq connect_timeout and makes up to three connection attempts, with jittered exponential backoff starting at 500 ms, so a database resuming from zero is not reported as an outage.

How should you handle connection storms: provider pooler or application pooler?

Each serverless function instance and each autoscaled replica opens its own connections. A deploy or a traffic spike can open hundreds of them in seconds while query volume stays low. Every Postgres connection is a backend process with its own memory, so on platforms that scale compute partly on memory, the connection count alone can raise capacity. A connection leak has the same effect, only slower. Idle connections that are never closed hold memory, keep the instance from pausing, and eventually reach max_connections.

Option Where it runs Cost Helps serverless functions?
Neon pooled endpoint (PgBouncer, transaction mode) Provider side Included Yes. Many clients share a few backends
RDS Proxy in front of Aurora Provider side, separate resource Billed separately, on top of Aurora compute Yes
Application pooler (in-process or sidecar) Your process None beyond your compute Limited. Each instance keeps its own pool, so total connections = pool size × instances

Provider-side pooling usually runs in transaction mode, and that mode changes session semantics. A client gets a backend only for the length of one transaction. As a result:

  • Session-level prepared statements can land on a backend that never saw them. Support depends on the pooler and its settings.
  • Session advisory locks can be left held by the wrong backend.
  • Plain SET settings leak to other clients. Use SET LOCAL inside a transaction instead.
  • LISTEN/NOTIFY does not work. Route listeners to a direct connection.

Some ORMs and drivers need configuration changes to work this way, typically by disabling automatic prepared statements or enabling a pooler-compatibility option. Run your migrations and any listeners over a direct, unpooled connection.

How much does an always-awake database cost compared with one that idles? An illustrative estimate

Illustrative estimate (assumed numbers, not a benchmark). The inputs below are made up so the arithmetic is easy to follow. Replace them with your provider's published rates.

  • Price: $0.15 per compute-unit-hour (CU-hour)
  • Minimum capacity when awake: 0.5 CU
  • Active load: 2 CU for 6 hours a day
  • Remaining 18 hours: no real traffic
  • Month: 30 days
  • Storage: billed separately and identical in both scenarios, so it is excluded

The formula is:

Monthly compute = (active hours × active CU + idle hours × idle CU) × days × price

In scenario A, a load balancer health check opens a connection every 30 seconds. Most providers wait several minutes of inactivity before suspending, so a probe every 30 seconds resets that timer every time. The database never pauses and sits at its 0.5 CU floor through the quiet hours. In scenario B, the health check hits an application endpoint that does not touch the database, so compute drops to zero when idle.

Scenario Daily CU-hours Monthly CU-hours Monthly compute
A: never pauses (30 s DB health check) 6×2 + 18×0.5 = 21 630 $94.50
B: idles 18 h/day 6×2 + 18×0 = 12 360 $54.00

The health check alone accounts for 270 of the 630 CU-hours, about 43% of scenario A's compute bill, while serving no users.

Scale to zero only pays off when there are idle hours to recover. If the workload runs at 2 CU around the clock, it uses 1,440 CU-hours a month, which is $216 at the assumed rate. A provisioned instance of the same size, billed at a flat hourly rate, often costs less than that, because per-unit serverless rates usually include a premium for elasticity. Compare both prices before you assume serverless is the cheaper option.

When should you use scale to zero, and when should you avoid it?

Scale to zero pays off when a database spends most of its hours with no clients connected. It costs you when cold starts land on user-facing requests or when performance depends on a warm buffer cache, because a resumed compute starts with an empty cache and has to reload hot pages from storage.

Workload Scale to zero? Why
Preview branches per pull request Yes Idle most of their lifetime, and a slow first query is acceptable
Dev and staging Yes Idle overnight and on weekends, and nobody pages on a cold start
Per-tenant databases Usually Many small tenants are inactive at any given hour
Bursty internal tools Yes Short active windows separated by long idle gaps
Steady production traffic No Compute never pauses, so you pay the elasticity premium for nothing
Tight latency SLOs No Resume time and a cold cache land on real requests

For steady production, provisioned capacity or a serverless configuration with a nonzero minimum is usually cheaper and simpler. You keep a warm cache and get predictable latency.

These conclusions depend on the provider. Aurora Serverless v2, Neon and other offerings differ in minimum capacity floors, in whether and when compute can pause, and in how they meter usage. All of these change over time. Recheck the analysis when pricing or pause behavior changes, because a lower floor or a new billing unit can change which factor drives the bill.

Verify the savings

Don't assume a database is pausing. Check:

  • Usage trends. Track compute-hours or capacity-unit consumption in the provider's billing and metrics views, broken down by database or branch. A preview branch that should be idle will show up as flat daytime-and-overnight usage.
  • Idle alerts. Alert when a database that should be idle reports active compute for longer than a threshold you choose. The usual cause is a leftover connection, such as a monitoring agent, a pooler holding sessions open, or a forgotten cron job.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to serverless postgres scale to zero, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.