Distributed systems · databases
Data in many places
A distributed database stores one logical database across many machines while letting applications query it as though it were one. It must decide how to split data, where each piece lives, how to answer a query whose data is scattered, and how to run transactions that touch several machines at once without losing the guarantees developers rely on.
What makes a database distributed
Two forces push data off a single server. Scale: the data or the request rate outgrows one machine. Geography: users on several continents want low latency, and some laws require data to stay in its country of origin. The goal is distribution transparency for the application:
- Fragmentation transparency: queries name the table, not its pieces.
- Location transparency: queries don't say which server holds the data.
- Replication transparency: the application doesn't manage copies.
- Transaction transparency: a transaction touching several servers behaves like one on a single server.
Full transparency is expensive. Many systems deliberately expose some distribution, for example by requiring a partition key in every query, so that applications can't accidentally write slow cross-server queries.
Shared memory, disk, or nothing
Shared nothing became the dominant design for large systems because adding a node adds CPU, memory, and disk together, with no shared component to saturate. Its price is that data must be partitioned and queries routed. Cloud databases have revived shared disk in a new form, separating compute from a distributed storage service, so compute nodes can be added or replaced in seconds.
Fragmentation
A table is split into fragments that can live on different sites. Horizontal fragmentation splits by rows, using a predicate or a function of a key. Vertical fragmentation splits by columns, keeping the primary key in every piece so rows can be rejoined. Hybrid fragmentation does both.
Fragments are then allocated to sites, often with replication. A good allocation puts each fragment near the users who query it most, keeps sites evenly loaded, and keeps related data together so common queries touch one site.
Partitioning schemes
Large systems usually fragment horizontally by a partition key (also called a shard key) chosen by the designer. How keys map to partitions decides how evenly load spreads.
| Scheme | How keys are placed | Strength | Weakness |
|---|---|---|---|
| Range | Contiguous key ranges per partition (A–F, G–M, …) | Efficient range scans and ordered reads | Hot spots when writes concentrate, e.g. on the newest timestamps |
| Hash | hash(key) mod N, or hash ranges | Spreads load evenly | Range queries must visit every partition |
| Consistent hashing | Keys and nodes on a ring | Adding a node moves only about 1/N of keys | Needs virtual nodes to balance well |
| Directory | A lookup table maps keys or ranges to partitions | Fully flexible placement and moves | The directory must be fast and highly available |
As data grows, partitions must split and move. Systems that split ranges automatically when they exceed a size, such as Bigtable, Spanner, and CockroachDB, avoid the pain of a fixed partition count. Moving a partition while it keeps serving traffic is one of the hardest operational problems in the field.
PaperChang et al., "Bigtable: A Distributed Storage System for Structured Data," ACM TOCS 26(2), 2008
DocsChoosing a shard key (MongoDB) · Vitess sharding for MySQL · Citus for PostgreSQL
Secondary indexes
Partitioning by one key makes lookups by any other column expensive. Two designs exist:
- Local indexes (partitioned by document): each partition indexes only its own rows. Writes stay on one partition, but a query on the indexed column must ask every partition and merge the results, a "scatter-gather" read.
- Global indexes (partitioned by term): the index is itself partitioned by the indexed value. Reads go to one index partition, but a single write may update index partitions on other machines, requiring a distributed transaction or an asynchronously updated index that may briefly lag.
Distributed queries
A query optimizer on one machine minimizes disk reads. A distributed optimizer must also minimize data moved over the network, often the dominant cost. The core techniques:
- Query shipping vs. data shipping: send the work to where the data lives instead of pulling data to the query.
- Push-down: apply filters and projections at each site before sending anything.
- Co-location: partition related tables on the same key so their joins happen locally.
- Semi-joins: send only the join keys first, so the other site returns only rows that will match.
Large analytic queries also run in parallel: every partition scans its share, intermediate results are repartitioned (shuffled) by join or group-by key so matching rows meet on the same node, and partial results are merged. The shuffle is usually the most expensive step.
PaperBernstein et al., "Query Processing in a System for Distributed Databases (SDD-1)," ACM TODS 6(4), 1981
TryReading query plans with EXPLAIN
Transactions and isolation
Transactions group operations so they are atomic (all or nothing), consistent (invariants hold), isolated (concurrent transactions don't see each other's partial work), and durable (committed data survives crashes). Isolation is a spectrum, and weaker levels permit specific anomalies:
| Isolation level | Dirty read | Lost update | Non-repeatable read | Write skew | Phantom |
|---|---|---|---|---|---|
| Read committed | prevented | possible | possible | possible | possible |
| Snapshot isolation | prevented | prevented | prevented | possible | prevented for reads |
| Serializable | prevented | prevented | prevented | prevented | prevented |
| Strict serializable | Serializable, and the order also respects real time (linearizable transactions) | ||||
Write skew is the classic snapshot-isolation anomaly. Two doctors are on call, and the rule is at least one must stay on call. Each transaction checks that the other is on call, then removes itself. Both succeed against their snapshots, and nobody is on call. The SQL standard's definitions of isolation levels missed anomalies like this one, which Berenson et al. later pointed out.
PapersEswaran et al., "The Notions of Consistency and Predicate Locks in a Database System," CACM 19(11), 1976 · Berenson et al., "A Critique of ANSI SQL Isolation Levels," SIGMOD 1995
TryHermitage (test what each database's isolation levels actually do)
Concurrency control
Concurrency control enforces isolation. The main families each extend to distributed settings:
- Two-phase locking (2PL)
- Acquire locks before access and release none until all are acquired; strict 2PL holds them until commit. Distributed deadlocks must be detected or prevented.
- Timestamp ordering
- Assign each transaction a timestamp and abort any operation that would violate timestamp order. No deadlocks, but more aborts.
- Optimistic (OCC)
- Run without locks, then validate at commit that nothing read was changed. Cheap when conflicts are rare.
- Multi-version (MVCC)
- Keep several timestamped versions of each row. Readers see a consistent snapshot and never block writers.
MVCC needs timestamps that every node agrees on. Systems obtain them from a central timestamp oracle (Percolator, TiDB), from tightly synchronized clocks with known error bounds (Spanner's TrueTime), or from hybrid logical clocks plus conflict checks (CockroachDB). Deterministic databases such as Calvin take a different route: they agree on a global order for transactions before executing them, so every replica runs them the same way without distributed commit.
PapersBernstein & Goodman, "Concurrency Control in Distributed Database Systems," ACM Computing Surveys 13(2), 1981 · Kung & Robinson, "On Optimistic Methods for Concurrency Control," ACM TODS 6(2), 1981 · Peng & Dabek, "Large-scale Incremental Processing Using Distributed Transactions and Notifications" (Percolator), OSDI 2010 · Thomson et al., "Calvin: Fast Distributed Transactions for Partitioned Database Systems," SIGMOD 2012 · Kulkarni et al., "Logical Physical Clocks," OPODIS 2014
Committing across shards
A transaction that writes to several partitions needs atomic commit: all partitions commit or none do. Two-phase commit provides this, but a coordinator crash can leave participants blocked while holding locks. Modern distributed SQL databases fix this by making every participant, and the coordinator's record, a replicated group.
Because every vote and decision is replicated, a single crash no longer blocks the transaction: another replica takes over and finishes it. The remaining cost is latency, at least one consensus round per phase. Designers reduce it by co-locating data that is updated together, so most transactions touch only one shard.
PaperGray & Lamport, "Consensus on Transaction Commit," ACM TODS 31(1), 2006
DocsCockroachDB transaction layer · Spanner: TrueTime and external consistency
System families
| Family | Examples | Data model | Transactions | Best fit |
|---|---|---|---|---|
| Sharded relational | Vitess, Citus | SQL tables split by a shard key | Full within a shard; limited across shards | Scaling an existing MySQL or PostgreSQL app |
| Distributed SQL (NewSQL) | Spanner, CockroachDB, TiDB, YugabyteDB | SQL over auto-split ranges | Serializable across shards | Global apps needing SQL and strong guarantees |
| Wide-column / key-value | Cassandra, DynamoDB, Bigtable | Rows by partition key, flexible columns | Single-row or limited; tunable consistency | Huge write volumes, predictable access paths |
| Document | MongoDB | JSON documents | Multi-document transactions, at higher cost | Flexible schemas, document-shaped data |
| Cloud-native shared storage | Aurora, AlloyDB | SQL on a distributed storage layer | Full ACID with a single writer | Relational apps that need fast failover and read scaling |
The dividing line between SQL and NoSQL has blurred. NoSQL stores added transactions and SQL-like queries, while distributed SQL systems adopted the partitioning and replication that NoSQL pioneered. The real questions are which consistency and transaction guarantees the application needs, and what latency it can afford for them.
In practice
Spanner
distributed SQLexternal consistency
Spanner partitions data into Paxos-replicated groups spread across datacenters and uses TrueTime to give globally ordered, strictly serializable transactions. A later paper describes how it grew from a key-value store into a full SQL system serving Google's ads and other core products.
Corbett et al., "Spanner," ACM TOCS 31(3), 2013 · Bacon et al., "Spanner: Becoming a SQL System," SIGMOD 2017
Amazon Aurora
compute–storage separation
Aurora's insight is that "the log is the database." Database nodes send only redo-log records to a storage service replicated six ways across three availability zones, and the storage layer rebuilds pages itself. Network traffic drops sharply, and crash recovery is nearly instant.
CockroachDB and TiDB
open-source distributed SQL
CockroachDB splits tables into Raft-replicated ranges, runs serializable transactions with hybrid logical clocks, and lets designers pin data to regions for latency and data-residency law. TiDB pairs a Raft-replicated row store with a columnar replica, so the same data serves both transactions and analytics.
Taft et al., "CockroachDB: The Resilient Geo-Distributed SQL Database," SIGMOD 2020 · Huang et al., "TiDB: A Raft-based HTAP Database," PVLDB 13(12), 2020
Tools and reading
Try it
- CockroachDBStart a three-node cluster locally, watch ranges split and rebalance, and kill a node mid-transaction.
- MongoDB shardingShard a collection by range and by hash and compare how data spreads.
- CitusDistribute PostgreSQL tables and read the distributed query plans.
- YugabyteDB and TiDBOther open-source distributed SQL systems to compare.
- HermitageReproduce isolation anomalies like write skew yourself.
- Jepsen analysesSee which databases kept their transaction promises under failure.
Read it
- Kleppmann, Designing Data-Intensive Applications, ch. 6 and 7Partitioning and transactions.
- van Steen & Tanenbaum, Distributed SystemsFree textbook.
- DeWitt & Gray, 1992Why shared-nothing parallel databases won.
- Berenson et al., 1995What isolation levels really mean.
- Thomson et al., 2012Deterministic distributed transactions.
- Taft et al., 2020A modern geo-distributed SQL design end to end.