Skip to content

Week 3 — Databases, CAP Theorem & Scaling

SQL (Relational)NoSQL
StructureTables, fixed schemaFlexible (document, key-value, graph)
QueriesJOINs, complex filtersSimple key lookups or document scans
TransactionsACIDUsually eventual consistency
ScaleVertical first, then shardingHorizontal by design
Use whenBusiness data, financial records, complex relationsCache, session, logs, flexible schema

For ERP/accounting systems: SQL always. Transactional correctness beats schema flexibility.

TypeExamplesBest for
Key-valueRedis, DynamoDBCache, sessions
DocumentMongoDBFlexible schemas, nested data
Wide-columnCassandraTime-series, high write throughput
GraphNeo4jRelationships (social, fraud detection)
PropertyMeaning
AtomicityAll-or-nothing. Transaction succeeds completely or not at all
ConsistencyDB always moves from one valid state to another
IsolationConcurrent transactions don’t interfere
DurabilityCommitted data survives crashes (write-ahead log)

A distributed system can only guarantee two of three:

ConsistencyAvailabilityPartition Tolerance
CP
AP
CA✗ — not realistic

Network partitions always happen. So the real choice is: CP or AP?

  • CP systems (PostgreSQL, ZooKeeper): refuse requests during partitions rather than serve stale data
  • AP systems (Cassandra, DynamoDB): serve possibly stale data rather than go down

CAP consistency ≠ ACID consistency. CAP is about cross-node agreement. ACID is about transaction correctness within one node.

Buy a bigger machine. Simple, no code changes, but hits physical and cost limits.

Add more machines. Requires:

  • Stateless app servers — no local state, any server handles any request
  • Shared session storage — Redis or DB, not local memory
  • Load balancer — distributes traffic across instances
Tenant A → Database A (PostgreSQL instance 1)
Tenant B → Database B (PostgreSQL instance 1)
Tenant C → Database C (PostgreSQL instance 2)

Database-per-tenant sidesteps cross-shard joins entirely. Simple to reason about, easy to move a tenant to a new instance.

Design the data layer for a multi-company accounting system:

  • 500 companies sharing one application server
  • Financial data must never mix between companies
  • Some companies have 10x the transaction volume of others
  • Why is ACID consistency different from CAP consistency?
  • Your app needs to run in two data centres simultaneously. Which CAP trade-off applies?
  • What makes horizontal scaling hard for a stateful application?