Databases at scale
The database is usually the hardest part of a system to scale, because it holds state: you can't just start ten copies of it. This lesson covers choosing a database, making queries fast with indexes, spreading reads with replication, and the trade-offs that come with each.
SQL or NoSQL?
| Relational (PostgreSQL, MySQL) | Document (MongoDB, Firestore) | Key-value (Redis, DynamoDB) | Wide-column (Cassandra, ScyllaDB) | Graph (Neo4j) | |
|---|---|---|---|---|---|
| Data model | Tables, rows, joins | JSON-like documents | Key → value | Rows partitioned by key, many columns | Nodes and relationships |
| Strengths | Transactions, joins, constraints, ad-hoc queries | Flexible schema, nested data | Extreme speed and scale for simple lookups | Massive write throughput, multi-region | Traversing relationships |
| Watch out | Scaling writes needs sharding | Fewer cross-document guarantees | Only queries by key | Query patterns must be designed up front | Niche |
| Typical uses | Orders, payments, users, most apps | Catalogues, content, profiles | Sessions, caches, carts, counters | Messages, events, time series, IoT | Recommendations, fraud rings |
Default to a relational database (PostgreSQL is an excellent choice) unless you have a clear reason: it handles far more scale than most products ever reach, and transactions and constraints prevent whole categories of bugs. Large systems often use several stores, each for what it's best at (polyglot persistence).
Indexes: the first and cheapest fix
Without an index, finding rows means scanning the whole table. An index (usually a B-tree) finds them in O(log n). Here's SQLite showing its query plan before and after:
Index the columns you filter, join and sort by. But each index costs storage and slows down writes (it must be updated on every insert), so add them for real query patterns, not "just in case". Composite indexes ((customer_id, created_at)) serve queries that filter on the first column and sort by the second.
Replication
A primary database handles writes and streams its changes to replicas, which serve reads:
writes ──▶ primary ──replication──▶ replica 1 ◀── reads
app servers └────────────▶ replica 2 ◀── readsBenefits: more read capacity, failover (promote a replica if the primary dies), and replicas in other regions for local reads and disaster recovery.
Replication lag
Replication is usually asynchronous: replicas are a little behind, typically milliseconds, sometimes seconds under load. That produces a classic bug: a user saves their profile, the page reloads from a replica, and the change seems to have vanished:
Fixes, depending on how much consistency a feature needs:
- Read your own writes: after a user changes something, read their data from the primary for a short time.
- Route reads that must be fresh (balances, stock) to the primary; send everything else to replicas.
- Synchronous replication to at least one replica guarantees no data loss on failover, at the cost of slower writes.
Scaling writes
Replication scales reads. When the primary can't keep up with writes, or the data no longer fits one machine:
- Scale up the primary (more CPU, RAM, faster disks). Surprisingly effective.
- Reduce writes: batch them, move non-critical ones to a queue, store counters in Redis and flush periodically.
- Split by feature (vertical partitioning): orders in one database, user profiles in another.
- Shard (horizontal partitioning): split one table's rows across many databases by a key. That's the next lesson.
Connection pooling
Each database connection costs memory on the server (PostgreSQL uses a process per connection). A thousand app instances with 20 connections each would overwhelm it. Use connection pools in each app, and a pooler such as PgBouncer in front of PostgreSQL, so many clients share a few hundred real connections.
Backups and durability
Replicas are not backups: deleting a table replicates the deletion instantly. Keep point-in-time recovery (base backups plus write-ahead logs), test restores regularly, and store backups in another region. Define your RPO (how much data you can afford to lose) and RTO (how long recovery may take), then design to meet them.
Practice
- In the index example, add a query that filters by
statusand sorts bytotal. Which index helps? - Change the replication model so reads within 1 second of a user's own write go to the primary.
- Choose databases for: user accounts, a product catalogue with varied attributes, a real-time leaderboard, and billions of sensor readings.
1.What do read replicas help with?
2.A user updates their name and immediately sees the old one. What's the likely cause?
3.What is the downside of adding many indexes?