← tonia.ai

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 memoryShared diskShared nothing CPUCPUCPU memory disks CPUmemCPUmemCPUmem shared storage CPUmemdisk CPUmemdisk CPUmemdisk network one big machinelimited by its size nodes coordinate onshared pages (locks, cache) scales by adding nodes;data must be partitioned

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.

PaperDeWitt & Gray, "Parallel Database Systems: The Future of High Performance Database Systems," CACM 35(6), 1992

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.

customers idnameregionbal 1AnaWest40 2RajEast15 3MeiWest90 4LeoEast25 Horizontal (by region) site West 1 Ana West 403 Mei West 90 site East 2 Raj East 154 Leo East 25 Vertical profile service 1 Ana West2 Raj East3 Mei West4 Leo East billing 1 402 153 904 25 Correct fragmentation is complete (every row or column lands somewhere), reconstructible (a union or join rebuilds the table), and disjoint (no duplicates except the key in vertical splits). Choose fragments by access pattern: rows that are queried together should live together.

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.

SchemeHow keys are placedStrengthWeakness
RangeContiguous key ranges per partition (A–F, G–M, …)Efficient range scans and ordered readsHot spots when writes concentrate, e.g. on the newest timestamps
Hashhash(key) mod N, or hash rangesSpreads load evenlyRange queries must visit every partition
Consistent hashingKeys and nodes on a ringAdding a node moves only about 1/N of keysNeeds virtual nodes to balance well
DirectoryA lookup table maps keys or ranges to partitionsFully flexible placement and movesThe directory must be fast and highly available
Range on timestampHash on timestamp P1P2P3P4 P1P2P3P4 all new writes hit the latest range writes spread across partitions
Bar heights are illustrative. Even hashing can't fix a single extremely popular key (a celebrity's account, say); that needs splitting the key itself or caching.

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.
site 1: orders1,000,000 rows × 100 B site 2: customers200 in Arizona Ship the table all orders: 100 MB Semi-join 1. Arizona customer IDs: 200 × 8 B = 1.6 KB 2. matching orders only: 20,000 × 100 B = 2 MB about 50× less network traffic for the same answer
Assumes Arizona customers placed 2% of orders. Semi-joins pay off when the filter is selective; if most rows match, the extra round trip is wasted.

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 levelDirty readLost updateNon-repeatable readWrite skewPhantom
Read committedpreventedpossiblepossiblepossiblepossible
Snapshot isolationpreventedpreventedpreventedpossibleprevented for reads
Serializablepreventedpreventedpreventedpreventedprevented
Strict serializableSerializable, 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.
time → v1 @5 v2 @10 v3 @20 reader snapshot @15 sees latest version ≤ 15 written after the snapshot:invisible to this reader

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.

application gateway / coordinator prepare / commitprepare / commit shard A (accounts 1–5000) shard B (accounts 5001–9999) LL each shard: Raft leader (L) + followers; a prepared vote survives any single crash

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

FamilyExamplesData modelTransactionsBest fit
Sharded relationalVitess, CitusSQL tables split by a shard keyFull within a shard; limited across shardsScaling an existing MySQL or PostgreSQL app
Distributed SQL (NewSQL)Spanner, CockroachDB, TiDB, YugabyteDBSQL over auto-split rangesSerializable across shardsGlobal apps needing SQL and strong guarantees
Wide-column / key-valueCassandra, DynamoDB, BigtableRows by partition key, flexible columnsSingle-row or limited; tunable consistencyHuge write volumes, predictable access paths
DocumentMongoDBJSON documentsMulti-document transactions, at higher costFlexible schemas, document-shaped data
Cloud-native shared storageAurora, AlloyDBSQL on a distributed storage layerFull ACID with a single writerRelational 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.

Verbitski et al., "Amazon Aurora: Design Considerations for High Throughput Cloud-Native Relational Databases," SIGMOD 2017

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