Understanding Database Transactions

1. Understanding Transaction Lifecycle

BEGIN ──► ACTIVE ──statements──► PARTIALLY COMMITTED ──fsync──► COMMITTED
   │                  │
   │                  ▼
   │              FAILED ──► ABORTED ──► TERMINATED
   └──ROLLBACK──────────────┘
        
StateMeaning
ActiveExecuting statements
Partially CommittedLast stmt done, awaiting durable commit
CommittedChanges durable; locks released
FailedError occurred; awaiting rollback
AbortedRolled back; DB at pre-tx state

2. Understanding Atomicity

MechanismDetail
Undo logReverse operations on rollback
Shadow pagingWrite to copy; swap pointer atomically
MVCCNew row version invisible until commit
Crash recoveryUncommitted txs rolled back at startup

3. Understanding Consistency

Enforced ByExample
ConstraintsPK, FK, CHECK, NOT NULL
TriggersCustom invariants
Application logicBusiness rules outside schema
IsolationConcurrent writes don't break invariants

4. Understanding Isolation

TechniqueDetail
Two-Phase Locking (2PL)Acquire locks, then release; strict 2PL holds until commit
MVCCEach tx sees a snapshot; writes create new versions
SSI (PG)Detects unsafe read-write dependencies; aborts one
Timestamp orderingOrder operations by tx start time

5. Understanding Durability

MechanismDetail
Write-Ahead Log (WAL)Log first, then apply
fsync on commitForce log to disk before ack
Group commitBatch fsyncs for throughput
ReplicationSync replica before ack (synchronous_commit)
CheckpointsFlush dirty pages, advance log

6. Understanding Transaction Logs

ComponentPurpose
WAL / Redo LogSequential record of changes
Undo LogPre-images for rollback / MVCC
LSNLog sequence number (monotonic position)
ArchiveOld WAL files retained for PITR
Replication streamWAL shipped to replicas

7. Handling Long-Running Transactions

ProblemMitigation
Bloat (PG)Vacuum can't reclaim dead tuples → split into batches
Lock holdingAvoid SELECT FOR UPDATE in long txs
Replication lagLong tx delays replay → use chunked work
Monitoringpg_stat_activity WHERE xact_start < now() - interval '5min'

8. Using Distributed Transactions

ProtocolDetail
Two-Phase Commit (2PC)Prepare → Commit; blocking on coordinator failure
XAOpen standard for 2PC across resource managers
Three-Phase Commit (3PC)Non-blocking variant (rarely deployed)
Paxos / RaftConsensus protocols (CockroachDB, Spanner, etcd)
SagasSequence of local txs + compensations

9. Implementing Compensating Transactions

AspectDetail
Saga patternSeries of local txs; each has an inverse
OrchestratedCentral coordinator (e.g., Temporal, Camunda)
ChoreographedEvent-driven, each service reacts
IdempotencyCompensations must be idempotent & retryable

10. Optimizing Transaction Performance

TechniqueDetail
Keep txs shortLess lock contention, less WAL
Batch writesOne tx for many rows vs N txs
Right isolationREAD COMMITTED unless need higher
Async commitTrade durability window for latency
Group commitServer-side coalesces fsyncs