A field guide to multi-version concurrency control, write-ahead logging, B-trees vs. LSM-trees, distributed consensus, two-phase commit, optimistic locking, consistent hashing, & more

By The Coding Gopher

Published: 2026-10-08

URL: https://thecodinggopher.substack.com/p/mvcc-wal-raft-and-7-more-database


The basics — ACID, indexes, joins, replication — get you through most day-to-day work. But there’s a second layer of ideas underneath all of that: the actual machinery databases use to deliver those guarantees while still being fast, and the harder problems that show up once a single machine isn’t enough anymore.

This is the stuff that explains why a query that should be instant sometimes isn’t, why your database occasionally pauses to “vacuum,” and why building a distributed system is so much harder than it sounds on a whiteboard. Consider this the sequel.

Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.

1. MVCC — how databases let you read without blocking writes

If a database simply locked a row every time someone read it, every read would block every write, and vice versa. Most modern databases solve this with Multi-Version Concurrency Control (MVCC): instead of overwriting a row in place, an update creates a new version of it, tagged with the transaction that created it. Readers see a consistent snapshot of the data as it existed when their transaction started, while writers create new versions without blocking those readers at all.What is Multi-Version Concurrency Control (MVCC) in DBMS? - GeeksforGeeksMultiversion Concurrency Control (MVCC) is a database technique that allows multiple transactions to read and write data simultaneously without blocking each other. Instead of overwriting existing records, the database creates a new version of the data, ensuring each user views a consistent snapshot from when their transaction began.

This is why a long-running read query doesn’t grind your whole database to a halt — it’s reading a snapshot, not fighting writers for a lock. The trade-off is that old row versions pile up and need to be cleaned out eventually. In Postgres, that cleanup process is called vacuum, and a database that isn’t vacuumed regularly slowly fills up with dead row versions, bloating tables and degrading performance — a very common, very avoidable production issue.PostgreSQL - Autovacuum - GeeksforGeeksPostgreSQL VACUUM is a crucial maintenance operation that reclaims storage space occupied by dead rows (dead tuples) created during UPDATE and DELETE operations. It prevents table bloat, updates query planner statistics, and protects against transaction ID wraparound.

Note: Transaction ID (XID) wraparound is an issue—most commonly associated with PostgreSQL—where a database's transaction counter hits its maximum 32-bit limit (approx. 2.1 billion writeable transactions) and overflows. To protect data from severe corruption, the database forces a shutdown or becomes read-only.

Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.

2. Write-ahead logging — durability without waiting on disk

Durability — the “D” in ACID — sounds like it should mean “write straight to disk before confirming.” In practice, that would make every transaction painfully slow, since random writes scattered across a data file are expensive.Write Ahead Logs : But Why ??. Write-Ahead Logging (WAL) is a… | by Abhinav  Vinci | MediumWrite-Ahead Logging (WAL) is a foundational technique used in databases and storage systems to ensure data integrity and durability. The core rule is simple: before any changes are applied to the actual data files, the changes are first appended to a persistent, sequential log. This ensures that even if a crash occurs, the system can be recovered by replaying the log.

Instead, databases use a write-ahead log (WAL): every change is first appended, sequentially, to a log file. Sequential writes are fast. Once the change is safely in the log, the transaction can be confirmed — the actual data file gets updated later, in the background. If the database crashes before that background update happens, it replays the log on restart and reconstructs exactly what should have happened.

This single idea is also what powers replication in most systems: a replica is often just a server that’s continuously replaying the primary’s WAL.

Note: Writing to data files involves scattered, random Input/Output (I/O). WAL allows the system to gather multiple changes, write them sequentially in one batch to an append-only log, and acknowledge the transaction to the client quickly, deferring the actual data updates to later.

Build Redis, Git, Docker & Claude Code From Scratch

Want to become a better software engineer?

Trusted by engineers at Google, NVIDIA, and Anthropic, CodeCrafters helps you rebuild technologies like Redis, Git, Docker, and Claude Code from scratch so you can deeply understand how real systems work.

We’ve partnered with CodeCrafters to give all readers an exclusive 40% lifetime discount.

💡 Engineers may expense platforms like this through their team’s learning budget.

Start Building & Unlock 40% Off

3. B-trees vs. LSM-trees — two philosophies for storing data

Most relational databases store data on disk in a B-tree — a balanced, sorted tree structure that keeps reads and writes both reasonably fast, with data updated in place. It’s a good general-purpose choice, which is why Postgres, MySQL, and SQL Server all lean on it.B-treeA B-tree is a self-balancing, sorted search tree data structure that allows for efficient searches, insertions, deletions, and sequential access. It is specifically designed to handle large amounts of data and is widely used in databases and file systems because it minimizes disk access.

Note: A self-balancing tree is a data structure that automatically adjusts its shape—keeping its height minimal—when data is inserted or deleted. This ensures search, insertion, and deletion times remain consistently fast at O(logN), preventing the tree from becoming a slow, linear list.

Databases built for very heavy write workloads (Cassandra, RocksDB, and many time-series databases) often use an LSM-tree (log-structured merge-tree) instead. New writes go into an in-memory buffer and get flushed to disk in batches as new, immutable sorted files; a background process periodically merges those files together and discards outdated versions. This turns random writes into sequential ones, which is dramatically faster for write-heavy workloads — at the cost of reads sometimes needing to check multiple files, and that background merging (”compaction”) competing for disk I/O.An LSM Tree (Log-Structured Merge-Tree) is a high-performance data structure designed for handling massive volumes of write operations by transforming random writes into fast sequential writes. It is the core engine behind many modern NoSQL databases like Apache Cassandra, RocksDB, and ScyllaDB.

Neither is “better” — it’s a direct trade-off between write throughput and read complexity, and it’s worth knowing which one your database uses, because it explains a lot about its performance personality.

4. Query optimizers — the part of the database that “thinks”

When you run a SQL query, you’re not telling the database how to get the answer — you’re describing what you want. The query optimizer is the component that figures out the actual execution plan: which indexes to use, what order to join tables in, whether to scan or seek.Query Optimization: How the Query Optimizer Works Using Relational Algebra  | by Ibrahim H. Al-Yazouri | Level Up CodingA query optimizer is a core component inside a database management system (DBMS) that determines the most efficient way to execute a given query. Because SQL is a declarative language, a user only defines what data they want, not how to get it. The query optimizer bridges this gap by evaluating multiple potential execution plans and selecting the one that minimizes hardware resources like CPU, memory, and disk I/O.

Note: The fundamental difference between a Scan and a Seek in SQL is how the database engine traverses data: a Scan reads through every row or page of a table or index from start to finish, whereas a Seek uses the B-tree structure of an index to navigate directly to specific rows. Think of a database like a textbook: a Scan is like reading the entire book page-by-page to find a keyword, while a Seek is like checking the index at the back of the book to jump straight to the exact page you need.

It does this largely by estimating cost using table statistics — row counts, value distributions, index selectivity — that the database keeps and periodically refreshes. This is why a query can suddenly get slow after a large data import: the statistics are stale, the optimizer’s cost estimates are wrong, and it picks a bad plan. Running ANALYZE (or the equivalent for your database) to refresh statistics is a surprisingly common fix for “this query used to be fast and now isn’t.”Explaining PostgreSQL EXPLAIN | Tiger DataIn database management (like PostgreSQL, MySQL, and DuckDB), EXPLAIN ANALYZE is a profiling tool that executes a SQL query to reveal exactly how the database engine processes it. It provides developers with the execution plan, actual row counts, and time spent on every step to help identify performance bottlenecks.

Reading an actual execution plan (via EXPLAIN ANALYZE) is one of the highest-leverage skills in working with databases — it turns “the database is slow” into “the database chose a sequential scan instead of using the index, and here’s probably why.”

Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.

5. Distributed consensus — getting multiple machines to agree

The moment you have more than one database node and need them to agree on something — who the current primary is, whether a write succeeded — you run into a hard problem: machines can crash, messages can be delayed or lost, and you still need the system to reach a single, correct answer.

Consensus algorithms like Raft and Paxos solve this. The intuition behind Raft, the more commonly implemented of the two: nodes elect a leader through a voting process, the leader handles all writes and replicates them to followers, and a write is only considered committed once a majority of nodes have acknowledged it. If the leader disappears, the remaining nodes hold a new election. This majority requirement is also why distributed systems are typically deployed in odd numbers (3, 5, 7) — it guarantees a clear majority can always be reached even if some nodes are down.Understanding Raft Consensus Algorithm: How it Works and Why it Matters |  by Mehar Chand | MediumRaft is a consensus algorithm designed to manage replicated logs across a cluster of nodes, ensuring all servers agree on the exact same sequence of commands. It achieves fault tolerance and strong consistency by electing a single leader and enforcing that the leader coordinates all data updates and log replication.

Note: Before Raft, the Paxos algorithm was the standard for distributed consensus, but it was notoriously difficult to understand and implement. Raft provides equivalent fault-tolerance and performance but offers a highly modular, easily understood design.

This is the mechanism underneath etcd, CockroachDB, and the leader-election logic in many distributed databases — it’s how a cluster avoids the nightmare scenario of two nodes both believing they’re the primary at once.

6. Two-phase commit — transactions across multiple databases

Consensus solves agreement within a cluster. Two-phase commit (2PC) solves a related but different problem: committing a single transaction that spans multiple, separate databases or services — for example, debiting an account in one database while creating an order in another.

It works in two steps. In the prepare phase, a coordinator asks every participant “can you commit this?” and each one locks its resources and replies yes or no. Only if everyone says yes does the coordinator move to the commit phase, telling everyone to actually finalize. If anyone said no, everyone rolls back instead.Distributed Transactions, 2PC and Saga Pattern | by Rohit S | Level Up  CodingTwo-Phase Commit (2PC) is a distributed algorithm that ensures all participant nodes in a distributed database system either commit or abort a transaction together. It guarantees atomicity (the “A” in ACID) across multiple physical locations or databases.

The catch is the coordinator itself is a single point of failure — if it crashes between the two phases, participants can be left holding locks indefinitely, waiting for an answer that never comes. This is one of the central reasons distributed transactions are so often avoided in favor of designs like message queues and eventual consistency, which sidestep the need for a single atomic moment across multiple systems entirely.

7. Optimistic vs. pessimistic concurrency control

When two transactions might touch the same data, there are two fundamentally different philosophies for handling it.

Pessimistic concurrency control assumes conflict is likely, so it locks the data up front — SELECT ... FOR UPDATE is the classic example. Other transactions trying to touch the same row simply wait. This is safe and predictable, but it means contention turns directly into transactions queuing up behind each other, and if you’re not careful about lock ordering, it opens the door to deadlocks — two transactions each waiting on a lock the other one holds. Most databases detect this automatically and kill one of the transactions to break the cycle.

Optimistic concurrency control assumes conflict is rare. Transactions proceed without locking, and at commit time the database checks whether anything changed underneath them — often via a version number on the row. If something changed, the transaction is rejected and has to retry. This scales much better under low contention, but it means your application needs to actually handle the retry case rather than assuming every write just succeeds.Optimistic vs. Pessimistic locking in RailsPessimistic concurrency control assumes data conflicts are highly likely, so it locks rows during a read to proactively block other users from making changes until the lock is released. In contrast, optimistic concurrency control assumes conflicts are rare, allows multiple users to read and edit data simultaneously without locks, and only verifies no other changes occurred at the moment of saving.

Which one fits depends entirely on how often you actually expect conflicts — pessimistic locking on a rarely-contended row is wasted overhead, and optimistic locking on a heavily-contended one just means constant retries.

Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.

8. Consistent hashing — sharding that doesn’t fall apart when you scale