What state does a relational database server keep that is scoped to a single client session, and why does that state matter when connections are shared or reused?
answer
- Txn + isolation + locks; params; temp tables
- Prepared statements, cursors, advisory locks
- Session-scoped role = authorisation risk
- Reuse without reset = leakage across requests
- Rollback + discard on release
basics
~20 sA session holds its transaction, session parameters (timezone, isolation level, search path, autocommit), temporary tables, prepared statements and cursors, session-level locks, sequence state, and the authenticated identity. If a connection is reused without resetting that state, the next user of the connection inherits it and behaves unpredictably.
solid answer
~50 sSession-scoped state includes: - the **current transaction** and its isolation level, snapshot, and held locks; - **session parameters**: timezone, character encoding, autocommit, lock and statement timeouts, schema search path, role; - **temporary tables** and other temp objects, visible only to that session and dropped at disconnect; - **prepared statements**, open cursors, and their cached plans; - **session-level advisory locks** and, in some engines, subscriptions such as asynchronous notification channels; - per-session sequence values (last generated identity) and the authenticated identity itself. It matters because a connection is not fungible. If a request sets a timeout or a role and the connection returns to a pool without a reset, the next borrower silently runs with those settings. Worse, a connection returned mid-transaction holds locks and blocks other work. Correct reuse therefore requires an explicit reset on return - rollback any open transaction and discard temp objects, prepared statements, and modified parameters.
code
sql · 9 lines-- request A, on connection #7
SET SESSION statement_timeout = '60s';
CREATE TEMPORARY TABLE staging (id bigint);
SET ROLE reporting_user;
-- connection returned to the pool without a reset
-- request B, borrows connection #7
SELECT * FROM staging; -- unexpectedly resolves to A's temp table
INSERT INTO orders ...; -- runs as reporting_user, with a 60s timeoutgo deeper
List the main pieces - open transaction, session settings, temporary tables, prepared statements - and state that they belong to one connection only.
Explain how each piece leaks across reuse and name the reset discipline (rollback plus discard) that prevents it.
Add the operational and security angles: retained locks blocking cleanup, load-dependent bugs that only appear on shared connections, and role leakage as an authz defect.
Frame the tension between session-scoped optimisations (prepared statements, temp staging) and connection multiplexing, and set a fleet-wide convention for defaults and resets.
## What "session state" means When a client authenticates, the server creates an execution context that survives across statements. Anything remembered between two statements on the same connection, and not visible to other connections, is session state. It is the reason a database connection cannot be treated as an interchangeable pipe. ## The inventory **Transaction context.** Whether a transaction is open, its isolation level, its snapshot, its accumulated locks, and any savepoints. This is the most consequential piece: an open transaction pins resources and blocks other writers. **Session parameters.** Timezone, encoding, autocommit mode, default isolation level, statement and lock timeouts, the schema search path or default schema, the currently assumed role, and similar knobs. These change how identical SQL behaves. **Temporary objects.** Temporary tables (and in some engines temporary sequences or types) live in a session-private namespace and are dropped when the session ends. Two sessions can hold same-named temp tables with different contents. **Prepared statements and cursors.** A prepared statement is parsed - and often planned - once and referenced by name for the rest of the session. Open cursors hold a position in a result set, and in some engines an underlying snapshot. **Locks and subscriptions.** Session-level advisory locks are held until released or the session ends, regardless of transaction boundaries. Engines with asynchronous notification channels bind subscriptions to the session too. **Small conveniences.** The last generated identity value, session-scoped user variables, the current search of role privileges, and the authenticated identity. ## Why it matters The entire value of connection reuse rests on the assumption that a connection handed to new work behaves like a fresh one. Session state breaks that assumption in three ways. *Leakage.* Code that sets a timeout, changes the isolation level, switches role, or creates a temp table and then returns the connection leaves those changes behind. The next borrower inherits them, producing bugs that appear only under load, only sometimes, and never in a single-connection test. These are among the most miserable production bugs to reproduce, because the symptom depends on which request previously used the same connection. *Resource retention.* A connection returned with an open transaction keeps its locks and prevents cleanup of old row versions engine-wide. A connection with hundreds of accumulated prepared statements holds their memory. Neither is visible to the borrower that inherits the connection. *Security.* If an application uses a role switch to represent the end user, forgetting to reset it hands the next request the previous user's privileges. That is not a performance bug; it is an authorisation defect. ## Making reuse safe The discipline is simple to state: **the state a unit of work changes, it must undo before releasing the connection.** In practice: - always end the transaction explicitly - a rollback on release is the cheap safety net; - prefer statement-scoped settings over session-scoped ones where the engine offers them (for example, a setting applied only for the duration of the current transaction); - issue an explicit reset/discard command on return, which drops temp objects, deallocates prepared statements, releases session locks, and restores parameters to defaults; - release session-level advisory locks deliberately, since they do not follow transaction boundaries; - set defaults at the role or database level rather than per session, so the correct value is restored by a reset instead of being reapplied by application code. ## The trade-off to know Session state is also useful. Prepared statements amortise parse and plan cost across many executions, temporary tables give a place to stage intermediate results, and session settings let one workload run with different timeouts from another. The engineering tension is that every one of those benefits depends on statements landing on the *same* session - exactly what aggressive connection multiplexing removes. Recognising that tension, and naming the reset that resolves it, is what an interviewer is listening for.
- How do you make sure a connection is clean before it is used again?End the transaction explicitly - a rollback on release costs almost nothing and guarantees no locks are carried over - and then issue the engine's reset or discard command, which drops temporary objects, deallocates prepared statements, releases session-level locks, and restores parameters to their configured defaults. Setting defaults at role or database level rather than per session means the reset restores the right values automatically.
- Why are session-level advisory locks especially dangerous on a shared connection?Unlike row or table locks taken inside a transaction, session-level advisory locks are not released by commit or rollback; they persist until explicitly released or the session ends. On a pooled connection that can mean a lock is held indefinitely by a session that has moved on to unrelated work, blocking other processes with no obvious culprit in transaction monitoring.
saying these in an interview costs you the question
- Believing rollback or commit clears all session state
- Assuming temporary tables are global or shared between sessions
- Treating a returned connection as fresh without any reset
- Using a session-scoped role switch for per-user authorisation without resetting it