Free preview

Cheat Sheet

Key takeaway

Replication gives you copies (availability); partitioning gives you capacity (scalability). They solve different problems, they are used together, and almost every database decision reduces to what the access pattern needs and what guarantee you are willing to give up.

Key terms

TermOne line
Relation / tuple / attributeTable / row / column
Impedance mismatchNested objects vs flat tables; needs a translation layer
NormalizationEach fact stored once, linked by foreign key
ReplicationMultiple copies of the same data
Partitioning / shardingDifferent data on different nodes
Replication lagDelay between primary and secondaries
HotspotOne partition taking disproportionate data or traffic
QuorumMinimum nodes that must respond: r + w > n
LWWLast-write-wins conflict resolution
Scatter-gatherQuery every partition, merge results
CDCChange data capture — stream row changes to another system

SQL vs NoSQL

Relational if...Non-relational if...
Data is structuredData is unstructured
ACID requiredNeed to serialize/deserialize
Fits on one nodeData is large

ACID: Atomicity (all or none) · Consistency (invariants hold) · Isolation (concurrent = sequential) · Durability (survives failure). Prevents dirty reads, lost updates, phantom reads. ACID's C is not CAP's C.

The four NoSQL families

FamilyModelUse forExamples
Key-valueHash tableSessions, carts — lookup by identityDynamoDB, Redis, Memcached
DocumentJSON/XML/BSON treesCatalogs, CMS — varied self-contained recordsMongoDB, Firestore
GraphNodes + edgesSocial graphs, fraud, recommendations — traversalNeo4j, OrientDB
ColumnarStored by columnAnalytics, warehousing — scans over few columnsRedshift, BigQuery

Columnar ≠ wide-column. Columnar = OLAP scans. Wide-column (Cassandra, HBase) = high-throughput writes via column families.

NoSQL drawbacks: no standard query language (hard to port) · weaker consistency and no foreign-key constraints — referential integrity becomes your code.

NewSQL (Spanner) = horizontal scale plus ACID, paid for in write-path coordination latency.

Replication

Synchronous   -> replicas current, higher latency, blocks on a slow replica
Asynchronous  -> fast writes, replicas lag, UNREPLICATED WRITES ARE LOST
Semi-sync     -> wait for ONE replica; bounded loss, fastest-peer latency

Leader-based replication defaults to async — durability is not guaranteed.

ModelWritesFailoverConflictsConsistency
Single-leaderOne node (bottleneck)Election + fencingNone — leader serializesStrong on leader
Multi-leaderSeveral nodesModerateYes — must resolveEventual
LeaderlessEvery nodeNone to loseYes — versioningTunable via r/w

Single-leader propagation methods

MethodShipsWeaknessUsed by
Statement-basedSQL statementsNOW() and other nondeterminism divergesOlder MySQL
WAL shippingLow-level bytesCoupled to engine internals; hard version upgradesPostgreSQL, Oracle
Logical (row-based)Row changesMore verbosePostgreSQL, MySQL — enables CDC

Replication lag causes: data loss on primary failure · inconsistent reads. Fix: read-your-writes — read own data from leader, or better, a version watermark any caught-up follower can satisfy.

Conflict resolution (multi-leader)

StrategyHowRisk
Conflict avoidancePin a record's writes to one leaderBreaks on failover/relocation
Last-write-winsHighest timestamp survivesSilent data loss from clock skew
Custom logicMerge, or prompt the userLow — nothing discarded blindly

Topologies: circular · star · all-to-all (most robust) — one node failure breaks the other two.

Quorums

r + w > n     guarantees read and write sets overlap
n/r/wLegal?Character
3/2/1✗ (2+1 not > 3)Read can miss the write
3/2/2Balanced default
3/1/3Fast reads, slow writes
3/3/1Fast writes, slow reads

Latency = slowest node in the quorum, not the average.

Partitioning

Vertical = move tables/columns (split blobs off) — manual, static. Horizontal = split rows into shards — automatable, dynamic.

StrategyAdvantageDisadvantage
Key-rangeRange queries easy; data sortedHotspots if keys skew
Hash-basedUniform distributionRange queries hit every partition
Consistent hashingScales with minimal data movementNon-uniform without virtual nodes
Number of shards = Database size / Size per shard
                 = 10 TB / 50 GB = 200 shards

Rebalancing

Never hash mod n — changing n remaps nearly every key.

StrategyPartition countUsed by
Fixed numberConstant; move whole partitionsElasticsearch, Riak
DynamicSplits/merges by sizeHBase, MongoDB
Proportional to nodesFixed count per nodeCassandra, Ketama

Throttle rebalancing — unthrottled moves under load cascade into outages.

Secondary indexes

By document (local)By term (global)
WriteCheap — one shardExpensive — several index nodes
ReadScatter-gather all shardsTargets specific nodes
Use forWrite-heavyRead-heavy

Request routing

Any node (forwards) · Routing tier · Client-aware (partition map). All three need a fresh mapZooKeeper or equivalent (HBase, Kafka, SolrCloud). Small, strongly consistent control plane separate from the data plane.

Centralized vs distributed

CentralizedDistributed
ProSimple maintenance, strong ACID, simple programming modelNearest-shard access, parallel subqueries
ConLatency at node limits, single point of failureCross-site latency, expensive joins, consistency complexity

Query optimization — move computation to the data

T = a + v / b        a = access delay, b = data rate, v = data volume

Move Product (100,000 tuples) to A     -> 0.1 + 0.4  = 0.5 s
Move Store + Sales (1,010,000) to B    -> 0.2 + 4.04 = 4.24 s
Filter Brand='Wolf' at B, move 10 rows -> 0.1 + ~0   = ~0.1 s   <- 42x faster

Push predicates down. When transfer dominates, cut volume; when access delay dominates, cut round trips.

Quick decision cues

  • Multi-record transactions needed → relational, and stay there
  • Lookup by single identifier at huge rate → key-value
  • Records with varying shapes → document
  • The relationships are the query → graph
  • Aggregate scans over few columns → columnar
  • Read-heavy → replicas + cache; write-heavy → shard
  • Acked write must never vanish → semi-sync at minimum
  • Data is derived and rebuildable → async replication is fine
  • Offline writes required → multi-leader
  • No leader to fail over → leaderless + quorums
  • Adding nodes often → consistent hashing / fixed partitions
  • Query by non-partition key, read-heavy → global index by term

Work the Interview Walkthrough for the full design and the Concept Drills for rapid-fire practice.

Enjoying the preview?

Create a free account to unlock the rest of this course, the in-browser judge, and live AI mock interviews.

Sign up free to continue