PostgreSQL connections, cursors, and SQL cache

In PostgreSQL, one connection is one backend process, and all session state (prepared statements, open cursors, temporary tables, SET values) lives in that process's local memory. Unlike Oracle or SQL Server, there is no shared cache of parsed SQL and execution plans that all sessions use together. If another connection sends the same statement, that backend parses and plans it again from the start. To reuse a plan, you must use a prepared statement within the same connection.

Key specs

ItemValue
ProtocolFrontend/backend protocol 3.0. TCP (default port 5432) and Unix domain sockets
One connectionOne backend process (Memory and process architecture)
Maximum connectionsmax_connections (100). superuser_reserved_connections (3), reserved_connections (0, from 16)
AuthenticationRules in pg_hba.conf. Default password method scram-sha-256. Time limit authentication_timeout (60 seconds)
Connection poolingNot built into the server. Use an external pooler such as PgBouncer
Query modesSimple query (statement text in one message), extended query (split into Parse, Bind, Execute)
Prepared statementsSeparate per session. No count limit. Disappear when the connection ends
Execution plan cacheBackend local. Only for prepared statements and statements inside PL/pgSQL
Plan selectionplan_cache_mode (default auto): the first 5 executions use value-specific plans, then it compares costs and switches to a generic plan
CursorDECLARE … CURSOR. By default valid only within a transaction. With WITH HOLD, it persists after commit
Cursor directionForward by default. With SCROLL, it can also move backward
Cursor planningcursor_tuple_fraction (0.1): assumes only 10% of the total will be read and picks a plan that returns the first rows quickly
Result cacheNone
Catalog cacheBackend local (catcache, relcache). Refreshed through the shared invalidation queue

Connections

Figure. From connecting to the first query

sequenceDiagram
  participant C as Client
  participant P as postmaster
  participant B as Backend process
  C->>P: TCP connection, SSL request (optional)
  C->>P: StartupMessage (user, database)
  P->>B: fork, hand over the socket
  B->>C: Authentication request (SCRAM etc., per pg_hba.conf rule)
  C->>B: Authentication response
  B->>C: AuthenticationOk, ParameterStatus
  B->>C: BackendKeyData (process ID, secret key for cancel)
  B->>C: ReadyForQuery
  C->>B: Query, or Parse, Bind, Execute
  B->>C: RowDescription, DataRow, CommandComplete, ReadyForQuery

Diagram explanation: Time flows from top to bottom.

  1. The postmaster accepts the client's connection. The postmaster does not authenticate; it immediately does a fork of a Backend process and hands over the socket. So even a connection that fails authentication pays the cost of creating a process.
  2. The backend process finds the first rule in pg_hba.conf that matches the connection type, database, user, and address, and authenticates by that method. If it does not finish within authentication_timeout, it disconnects.
  3. After authentication, it reports values such as the server encoding and time zone with ParameterStatus, and gives the process ID and secret key with BackendKeyData. These two values are used to cancel a query.
  4. When ReadyForQuery arrives, queries can be sent. This message carries the transaction state (idle, in a transaction, failed transaction).

Query cancel. A cancel cannot be sent over the connection that is running, so the client opens a new connection and sends a CancelRequest with the process ID and secret key. The postmaster checks the key and signals the matching backend.

Connection count and pooling. Because a connection is a process, an idle connection also holds memory, and each new connection refills the catalog cache from scratch. PgBouncer's transaction pooling hands a server connection to another client each time a transaction ends, so you must not use state tied to the session (SQL PREPARE, session-level SET, WITH HOLD cursors, temporary tables, advisory locks).

Time limits that drop a connection

SettingDefaultTarget
statement_timeout0 (none)Execution time of a single statement
idle_in_transaction_session_timeout0A session that idles with a transaction open. A long-open transaction blocks VACUUM
transaction_timeout0 (from 17)Total time of a transaction
idle_session_timeout0 (from 14)A session that idles outside a transaction
tcp_keepalives_idle0 (operating system value)TCP keepalive for detecting a dead peer
client_connection_check_interval0 (from 14)Checks whether the client disconnected while a long query runs

Query processing and the plan cache

Figure. Stages that simple and extended queries pass through

flowchart LR
  SQ["Simple query<br/>Query message"] --> PA["Parse"]
  PM["Extended query ① Parse<br/>names the statement"] --> PA
  PA --> AN["Analyze, rewrite<br/>check tables and types, expand views"]
  AN --> ST["Prepared statement<br/>backend local memory"]
  BD["Extended query ② Bind<br/>parameter values"] --> PL
  ST --> PL["Plan<br/>value-specific plan or generic plan"]
  AN -->|"a simple query goes straight on"| PL
  PL --> PO["Portal<br/>execution state"]
  EX["Extended query ③ Execute<br/>max rows"] --> PO
  PO --> RS["Result rows"]

Diagram explanation: A statement is processed from left to right.

  • A simple query sends the SQL text in a single Query message. It does Parse, Analyze/rewrite, Plan, and execution from scratch every time. It leaves nothing behind.
  • An extended query is split into three messages. Parse (①) stores the result of parsing and Analyze/rewrite in the backend as a Prepared statement. Bind (②) attaches the parameter values, decides the Plan, and creates a Portal. Execute (③) pulls rows from the portal. Repeating only Bind and Execute on the same prepared statement skips parsing and analysis.
  • A Portal is an execution state that holds the plan and the position of its execution. If Execute is given a max row count, it returns only that many, stops, and continues at the next Execute. An SQL cursor is the same portal.

You can do the same in SQL.

PREPARE ord_by_cust (int) AS SELECT * FROM orders WHERE cust_id = $1;
EXECUTE ord_by_cust(101);
DEALLOCATE ord_by_cust;

Value-specific plans and generic plans

A prepared statement's plan comes in two kinds. A value-specific plan (custom plan) is built fresh at every Bind with the actual parameter values. A generic plan is built once without knowing the values and reused from then on.

Figure. Plan selection for a prepared statement

flowchart TB
  A["Bind: n-th execution"] --> B{"Is n 5 or less"}
  B -->|"Yes"| C["Build and run a value-specific plan<br/>add its cost to the average"]
  B -->|"No"| D{"Is the generic plan's cost<br/>sufficiently cheaper than the average cost<br/>of value-specific plans"}
  D -->|"Yes"| E["Cache the generic plan and keep using it<br/>skip the planning stage"]
  D -->|"No"| C

Diagram explanation: This is the selection when plan_cache_mode = auto.

  1. The first five executions always build a value-specific plan. This gives good plans even on columns whose selectivity differs greatly by value, but it pays the planning cost every time.
  2. From the sixth execution, it builds a generic plan and compares its estimated cost with the average cost of the value-specific plans so far (including planning time). If the generic plan is not more expensive, it caches the generic plan, and later executions skip the planning stage.
  3. If the generic plan is clearly more expensive, it keeps using value-specific plans.
  • plan_cache_mode = force_custom_plan always uses a value-specific plan, and force_generic_plan always uses a generic plan. Use the former for statements whose value distribution is skewed so that the generic plan is bad, and the latter for short statements where the planning cost exceeds the execution cost.
  • A cached plan is invalidated when a table the statement references changes (ALTER TABLE, index creation or drop) or when statistics are refreshed (ANALYZE), and it is rebuilt at the next execution.
  • SQL statements inside a PL/pgSQL function are cached per session in the same way.
  • The conditions for using prepared statements differ by driver. The JDBC driver switches to a server-side prepared statement after the same statement has been executed prepareThreshold (default 5) times.

What having no shared SQL cache means. Sending many statements with literal values embedded does not overflow a cache the way Oracle's shared pool can. Instead, if 100 connections use the same statement, 100 backends each prepare it and each cache their own plan. In a service that runs very short statements very often, parsing and planning can take a large share of CPU, and prepared statements help in that case.

Cursors

A cursor is a feature that names a query's portal, keeps it open, and reads it in chunks with FETCH.

BEGIN;
DECLARE c CURSOR FOR SELECT * FROM orders WHERE ord_dt >= '2025-01-01' ORDER BY ord_dt;
FETCH 100 FROM c;      -- 100 rows
FETCH 100 FROM c;      -- the next 100 rows
CLOSE c;
COMMIT;
KindDeclarationBehavior
DefaultDECLARE c CURSOR FOR …Valid only within a transaction. Closed at commit or rollback. Continues the execution at each FETCH
Hold cursor… CURSOR WITH HOLD FOR …At commit, runs the rest of the result to the end and stores it (in memory up to work_mem, in a temporary file beyond that). Kept until the session ends or CLOSE
Scroll… SCROLL CURSOR FOR …FETCH BACKWARD and FETCH ABSOLUTE n are possible. Depending on the plan, a stage that stores the result is added
For update… FOR UPDATE + UPDATE … WHERE CURRENT OF cLocks the rows read and updates the current row
PL/pgSQLrefcursor variable, FOR rec IN SELECT …Can be opened inside a function and passed to the caller
  • A cursor reads with the snapshot from the moment it was opened. Changes other transactions make after it was opened are not visible (Isolation levels).
  • An open default cursor keeps a transaction open, so if left for long, VACUUM cannot reclaim dead rows.
  • The optimizer plans a cursor query on the assumption that only cursor_tuple_fraction (10%) of the total will be read. So even the same SELECT may get a plan that returns first rows quickly, such as an index scan instead of a sort, when opened as a cursor. For a cursor that will be read to the end, set SET cursor_tuple_fraction = 1.0.

Reading results on the client. Without a cursor, a libpq-based driver by default returns the result only after receiving the whole result into client memory. To receive a large result a little at a time, use one of: a server cursor (DECLARE/FETCH), the extended protocol's row limit (JDBC's setFetchSize, which works only with autocommit off), or libpq's single-row mode.

Cache summary

CacheLocationContentInvalidation
Plan cacheBackend localAnalysis results and plans of prepared statements and PL/pgSQL statementsDDL on referenced objects, ANALYZE, search_path change
Catalog cache (catcache)Backend localSystem catalog rows (types, functions, operators, etc.)Messages in the shared invalidation queue
Relation cache (relcache)Backend localStructure and file location of tables and indexesMessages in the shared invalidation queue
Shared invalidation queueShared memoryMessages that tell other backends about one backend's DDL
shared_buffersShared memoryData and index pages
pg_stat_statementsShared memory (extension)Execution statistics per normalized statement. Statistics, not a cacheBeyond pg_stat_statements.max (5,000), less-used entries are removed

There is no result cache that stores query results and returns them later. To reduce repeated computation, create and refresh a materialized view (MATERIALIZED VIEW) yourself.

Settings and checks

-- Connections and state
SELECT pid, usename, application_name, client_addr, state, backend_start, xact_start, state_change, query
FROM pg_stat_activity WHERE backend_type = 'client backend';

-- Sessions idling with a transaction open
SELECT pid, now() - xact_start AS xact_age, query
FROM pg_stat_activity WHERE state = 'idle in transaction' ORDER BY xact_start;

-- This session's prepared statements and execution counts by plan kind (from 14)
SELECT name, statement, generic_plans, custom_plans FROM pg_prepared_statements;

-- This session's open cursors
SELECT name, statement, is_holdable, is_scrollable, creation_time FROM pg_cursors;

-- The plan a prepared statement is using now
EXPLAIN EXECUTE ord_by_cust(101);     -- if the condition shows $1, it is a generic plan; if it shows 101, a value-specific plan

-- Session cleanup
DEALLOCATE ALL;  CLOSE ALL;  DISCARD ALL;

pg_prepared_statements and pg_cursors show only your own session's entries. You cannot see what other sessions have prepared.

The sandbox on this site opens a read-only transaction for each request, runs the statement, and rolls back. It uses the defaults: plan_cache_mode = auto, cursor_tuple_fraction = 0.1, password_encryption = scram-sha-256, and pg_stat_statements is not loaded.

Comparison with other DBMSs

PostgreSQLMySQLOracleSQL ServerKDBS
Execution plan cacheSession local, prepared statements onlyNoneShared pool (all sessions)Plan cache (all sessions)None. Keeps only the join order
Scope of a prepared statementSessionSessionThe session's cursor points to a shared cursorThe session handle points to a shared planSession, 64
Server cursorPortal, DECLAREInside stored programs, protocol cursorEvery statement is a cursorAPI cursor, T-SQL cursorPortal, 64
Result cacheNoneNone (removed in 8.0)Server result cacheNoneNone
Built-in server connection poolNoneThread cache (thread pool in Enterprise)Shared server, DRCPNone (sessions are lightweight)None (connections are lightweight)

The full comparison is in DBMS architecture at a glance.

NOTE Defaults are based on PostgreSQL 17 and can vary by version. For the behavior of poolers and drivers, check each product's version.

Related pages