Pcornel
Browse topics
Options
Recent
Favorites
Databases · Technical reference

Transactions, MVCC & Locking

Direct answer

Transactions group statements into all-or-nothing units; MVCC keeps row versions so readers don't block writers; locks protect concurrent changes.

When to use this

Use it when queries block each other, deadlock, or see unexpected data.

First 30 seconds

1. Open/long transactions: SELECT * FROM pg_stat_activity WHERE state <> 'idle' / SHOW ENGINE INNODB STATUS / sys.dm_tran_active_transactions.

2. Blocking chains.

3. Deadlocks in the log.

4. Isolation level of the session.

5. Fix app transaction scope.

Operational verification

BEGIN → reads (snapshot) and writes (locks) → COMMIT/ROLLBACK → versions cleaned

Evidence · next step

Common failures include idle transactions retaining old versions/locks, inconsistent object access order, oversized batches, assuming MVCC means no locking, and killing a blocker without understanding rollback cost or why it held the resource. Preserve the first divergent observation and repeat the same bounded verification after remediation.

Continue only after interpreting the current observation.
Context & applicabilityCommon mistakes · platform/version boundaries
Common mistakes
What not to infer

Databases owns transaction/lock semantics. Application logic determines transaction scope and retry behavior; host/storage Topics own resource problems below the engine.

Platform / version applicability
MariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformMariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts · Databases owns transaction/lock semantics. Application logic determines transaction scope and retry behavior; host/storage Topics own resource problems below the engine.
Scope / prerequisiteUse it when queries block each other, deadlock, or see unexpected data.
What next?3 suggested next steps
Child topics (this level)3
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

2 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Verification workflow Verify boundary

When diagnosing concurrency, identify transaction/session IDs, isolation level, locks/waits and statement age. Determine blocker versus waiter, capture the deadlock graph or engine report when available, and confirm that the application retries only errors that are safe to retry.

Step 2 Failure signatures and limits Narrow the fault

Common failures include idle transactions retaining old versions/locks, inconsistent object access order, oversized batches, assuming MVCC means no locking, and killing a blocker without understanding rollback cost or why it held the resource.

Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

test · 1
Drill down

Subtopics

Go one level deeper into this subject.

Key points

Keep transactions short. Long open transactions block cleanup (PG vacuum, MySQL purge) and hold locks. Choose the isolation level deliberately.

Key checks
  • SELECT * FROM pg_stat_activity WHERE state <> 'idle' — first check for this topic
  • psql -c "SELECT now(), version();" — PostgreSQL reachable and version
  • mysql -e "SELECT NOW(), VERSION();" — MariaDB/MySQL reachable and version
  • sqlcmd -S <server> -Q "SELECT @@VERSION" — SQL Server reachable and version
ReferenceWhat it is1 section · depth on demand

Operating model

Transactions, MVCC & Locking covers concurrency and consistency. A transaction groups work into a commit/rollback point; isolation controls what concurrent effects can be observed; MVCC keeps versions so readers/writers can coexist, while locks still protect resources and can block or deadlock depending on access order and engine behavior.

ReferenceHow it works1 section · depth on demand

In depth

Transactions group changes so they either all take effect or none do. Concurrency control lets many transactions run at once without corrupting data: PostgreSQL and InnoDB use MVCC (multi-version concurrency control), where readers see a consistent snapshot and do not block writers, while row locks serialise conflicting writes.

Isolation levelPrevents
Read committed (PostgreSQL, SQL Server default)Dirty reads
Repeatable read (InnoDB default)Non-repeatable reads
SerializableAll anomalies (may abort transactions to resolve conflicts)

Common operational problems:

ProblemCauseCheck
BlockingLong transactions holding lockspg_stat_activity, SHOW ENGINE INNODB STATUS, sys.dm_exec_requests
DeadlocksTransactions locking rows in different orderDeadlock logs; access rows in consistent order
Table bloat (PostgreSQL)Old row versions not vacuumed (long-open transactions)autovacuum activity, idle in transaction sessions

Keep transactions short and never leave sessions idle inside open transactions.

ReferenceImportant terms & boundaries1 section · depth on demand

Scope map

  • Transaction lifecycle
  • Isolation levels
  • MVCC
  • Row/table locks
  • Blocking
  • Deadlocks
  • Long-running transactions
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical examples

Configuration & expected output

Concrete examples are shown only when the stored reference contains an actual configuration or output shape for this Topic.

Configuration example

PostgreSQL PostgreSQL 14 or laterFind sessions waiting on locks and the session blocking them.

Assumptions: Read-only query; needs pg_monitor or superuser to see other users' queries.

SELECT pid, usename, state, wait_event_type, wait_event,
       pg_blocking_pids(pid) AS blocked_by,
       now() - xact_start AS xact_age, left(query, 60) AS query
  FROM pg_stat_activity
 WHERE datname = current_database()
 ORDER BY xact_age DESC NULLS LAST;

Expected output

PostgreSQL PostgreSQL 14 or laterSELECT pid, state, wait_event_type, pg_blocking_pids(pid) AS blocked_by FROM pg_stat_activity WHERE wait_event_type = 'Lock';

Expected state: In a healthy database this returns no rows, or only short-lived waits.

pid  | state  | wait_event_type | blocked_by
-------+--------+-----------------+------------
 41822 | active | Lock            | {41790}
(1 row)
Look at the blocker (here pid 41790): an idle in transaction session holding locks is the usual cause. Ending it rolls back its work. Illustrative authored output: field layout matches the tool, values will differ in your environment.
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-29 · otherMariaDB / PostgreSQL / Microsoft SQL Server concepts PostgreSQL current documentation

Documentation verification: confirms the upstream model used by the Topic. It does not assert local production behavior.

Basis: https://www.postgresql.org/docs/current/mvcc.html · confidence 92%
Technical changelog & impact

What changed and what may be affected

Recent technical edits are separated from ordinary page timestamps. Relationship impact is advisory: it identifies nearby canonical references to review, not automatic breakage.

Related reference impactReview these references after material technical changes when their shared boundary is affected.
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
transactions, mvcc & lockingdatabase transactionMVCCdatabase locks deadlock
Embedded reference data

Quick lookup tables

Transactions, MVCC & Locking verification boundary matrix

A compact lookup separating intent, owning component state, effective state and consumer-visible outcome for Transactions, MVCC & Locking.

BoundaryInspectHealthy interpretationDo not infer
IntentTransaction lifecycleIntended object/scope is explicit and versioned where relevantIntent is already effective
Owning runtime/control planeIsolation levels / MVCCOwner accepts and reports the expected object stateDownstream dependencies are healthy
Effective stateRow/table locksIndependent read-back matches the intended stateEvery client sees the same result
Consumer outcomeBlockingThe original bounded check succeeds in the same time windowProduction correctness outside this scope
Depth when you need it

Deep reference

Design & tradeoffs

Scope

Application logic determines transaction scope and retry behavior; host/storage Topics own resource problems below the engine.

Confirmation

Confirm action

Continue?