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
| Item | Value |
|---|---|
| Protocol | Frontend/backend protocol 3.0. TCP (default port 5432) and Unix domain sockets |
| One connection | One backend process (Memory and process architecture) |
| Maximum connections | max_connections (100). superuser_reserved_connections (3), reserved_connections (0, from 16) |
| Authentication | Rules in pg_hba.conf. Default password method scram-sha-256. Time limit authentication_timeout (60 seconds) |
| Connection pooling | Not built into the server. Use an external pooler such as PgBouncer |
| Query modes | Simple query (statement text in one message), extended query (split into Parse, Bind, Execute) |
| Prepared statements | Separate per session. No count limit. Disappear when the connection ends |
| Execution plan cache | Backend local. Only for prepared statements and statements inside PL/pgSQL |
| Plan selection | plan_cache_mode (default auto): the first 5 executions use value-specific plans, then it compares costs and switches to a generic plan |
| Cursor | DECLARE … CURSOR. By default valid only within a transaction. With WITH HOLD, it persists after commit |
| Cursor direction | Forward by default. With SCROLL, it can also move backward |
| Cursor planning | cursor_tuple_fraction (0.1): assumes only 10% of the total will be read and picks a plan that returns the first rows quickly |
| Result cache | None |
| Catalog cache | Backend 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.
- The
postmasteraccepts the client's connection. Thepostmasterdoes not authenticate; it immediately does aforkof aBackend processand hands over the socket. So even a connection that fails authentication pays the cost of creating a process. - The backend process finds the first rule in
pg_hba.confthat matches the connection type, database, user, and address, and authenticates by that method. If it does not finish withinauthentication_timeout, it disconnects. - After authentication, it reports values such as the server encoding and time zone with
ParameterStatus, and gives the process ID and secret key withBackendKeyData. These two values are used to cancel a query. - When
ReadyForQueryarrives, 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
| Setting | Default | Target |
|---|---|---|
statement_timeout | 0 (none) | Execution time of a single statement |
idle_in_transaction_session_timeout | 0 | A session that idles with a transaction open. A long-open transaction blocks VACUUM |
transaction_timeout | 0 (from 17) | Total time of a transaction |
idle_session_timeout | 0 (from 14) | A session that idles outside a transaction |
tcp_keepalives_idle | 0 (operating system value) | TCP keepalive for detecting a dead peer |
client_connection_check_interval | 0 (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
Querymessage. It doesParse,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 andAnalyze/rewritein the backend as aPrepared statement.Bind(②) attaches the parameter values, decides thePlan, and creates aPortal.Execute(③) pulls rows from the portal. Repeating onlyBindandExecuteon the same prepared statement skips parsing and analysis. - A
Portalis an execution state that holds the plan and the position of its execution. IfExecuteis given a max row count, it returns only that many, stops, and continues at the nextExecute. 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.
- 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.
- 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.
- If the generic plan is clearly more expensive, it keeps using value-specific plans.
plan_cache_mode = force_custom_planalways uses a value-specific plan, andforce_generic_planalways 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;
| Kind | Declaration | Behavior |
|---|---|---|
| Default | DECLARE 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 c | Locks the rows read and updates the current row |
| PL/pgSQL | refcursor 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,
VACUUMcannot 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 sameSELECTmay 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, setSET 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
| Cache | Location | Content | Invalidation |
|---|---|---|---|
| Plan cache | Backend local | Analysis results and plans of prepared statements and PL/pgSQL statements | DDL on referenced objects, ANALYZE, search_path change |
| Catalog cache (catcache) | Backend local | System catalog rows (types, functions, operators, etc.) | Messages in the shared invalidation queue |
| Relation cache (relcache) | Backend local | Structure and file location of tables and indexes | Messages in the shared invalidation queue |
| Shared invalidation queue | Shared memory | Messages that tell other backends about one backend's DDL | |
shared_buffers | Shared memory | Data and index pages | |
pg_stat_statements | Shared memory (extension) | Execution statistics per normalized statement. Statistics, not a cache | Beyond 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
| PostgreSQL | MySQL | Oracle | SQL Server | KDBS | |
|---|---|---|---|---|---|
| Execution plan cache | Session local, prepared statements only | None | Shared pool (all sessions) | Plan cache (all sessions) | None. Keeps only the join order |
| Scope of a prepared statement | Session | Session | The session's cursor points to a shared cursor | The session handle points to a shared plan | Session, 64 |
| Server cursor | Portal, DECLARE | Inside stored programs, protocol cursor | Every statement is a cursor | API cursor, T-SQL cursor | Portal, 64 |
| Result cache | None | None (removed in 8.0) | Server result cache | None | None |
| Built-in server connection pool | None | Thread cache (thread pool in Enterprise) | Shared server, DRCP | None (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
- DBMS Architecture at a Glance
- PostgreSQL
- PostgreSQL Memory and Process Architecture
- PostgreSQL isolation levels and SSI
- PostgreSQL Lock Modes
- MySQL Connections, Cursors, and SQL Cache
- Oracle Connections, Cursors, and the SQL Cache
- SQL Server Connections, Cursors, and Plan Cache
- KDBS connections, portals, and statement cache