System Design Part 4: Database & Storage
The database incident that haunted me for years started with a single query.
It was 2022, and our fintech platform was processing 50,000 transactions per minute. At 6:47 PM on a Friday (of course), our primary database locked up. Transactions failed. Account balances froze. Support tickets exploded.
The root cause? A developer ran without an index. On a table with 800 million rows. The query scanned the entire table, holding locks that blocked writes. For 23 minutes, our database was essentially offline.
SELECT * FROM transactions WHERE status = 'pending'That incident taught me more about database design than any course ever did. This guide captures those lessons—so you don't have to learn them the hard way.
The Anatomy of a Database Problem
Before diving into solutions, let's understand what makes databases fail at scale. Here's what happens when you grow from 1,000 to 1 billion transactions:
At 1,000 transactions:
- Any schema works
- Full table scans are fast
- Single server is fine
- Backups take seconds
At 1 million transactions:
- Missing indexes cause slowdowns
- Sequential IDs create contention
- Storage costs become noticeable
- Backup windows start mattering
At 1 billion transactions:
- Table scans are impossible
- Single server is insufficient
- Partitioning becomes mandatory
- Every query needs optimization
The patterns you need change dramatically at each scale. Let's build the right foundation.
Schema Design for Billions of Records
Let me show you the schema evolution we went through at our fintech company.
The Starter Schema (Works Until It Doesn't)
sqlCREATE TABLE transactions ( id BIGSERIAL PRIMARY KEY, account_id BIGINT NOT NULL, amount DECIMAL(18, 2) NOT NULL, type VARCHAR(20) NOT NULL, description TEXT, created_at TIMESTAMP NOT NULL DEFAULT NOW() ); CREATE INDEX idx_account ON transactions(account_id);
Why this breaks at scale:
-
BIGSERIAL creates a sequence bottleneck. Every insert needs to increment a counter. At 50K TPS, this becomes a lock contention point.
-
Single table grows indefinitely. After a year at 50K TPS, you have 1.5 trillion rows. Index operations take hours. Backups take days.
-
No partition pruning. Query for "last month's transactions" still scans the entire index.
-
VARCHAR wastes space. "DEBIT" repeated 750 billion times costs petabytes.

Why Naive Schema Fails
The Production Schema
Here's what actually works at scale:
sql-- Partition by date for lifecycle management CREATE TABLE transactions ( id UUID NOT NULL DEFAULT gen_random_uuid(), account_id BIGINT NOT NULL, transaction_date DATE NOT NULL, amount DECIMAL(18, 2) NOT NULL, transaction_type SMALLINT NOT NULL, reference_id VARCHAR(64) NOT NULL, metadata JSONB, PRIMARY KEY (transaction_date, id) ) PARTITION BY RANGE (transaction_date); -- Create partitions (automated via pg_partman in production) CREATE TABLE transactions_2024_01 PARTITION OF transactions FOR VALUES FROM ('2024-01-01') TO ('2024-02-01'); CREATE TABLE transactions_2024_02 PARTITION OF transactions FOR VALUES FROM ('2024-02-01') TO ('2024-03-01'); -- Indexes on the parent (automatically created on partitions) CREATE INDEX idx_transactions_account ON transactions(account_id, transaction_date);

Production Design
Why each choice matters:
| Decision | Reason |
|---|---|
| UUID primary key | Generated locally, no sequence contention, works distributed |
| Composite PK (date, id) | Enables partition key as part of PK (PostgreSQL requirement) |
| SMALLINT for type | 2 bytes vs 20+ for VARCHAR; use application enum mapping |
| Partition by month | Each partition ~4 billion rows max; easy archival |
| Account+date index | Covers 90% of queries: "show me my recent transactions" |
Partition Pruning in Action
When you query with the partition key:
sqlEXPLAIN ANALYZE SELECT * FROM transactions WHERE account_id = 12345 AND transaction_date BETWEEN '2024-01-01' AND '2024-01-31';
PostgreSQL only scans
transactions_2024_01. Other partitions aren't touched.Seq Scan on transactions_2024_01 (cost=0.00..1523.00 rows=50 width=128) Filter: (account_id = 12345 AND transaction_date >= '2024-01-01' AND ...)
Without partition key:
sqlEXPLAIN ANALYZE SELECT * FROM transactions WHERE reference_id = 'TXN-123456';
Scans ALL partitions:
Append (cost=0.00..15230000.00 rows=50 width=128) -> Seq Scan on transactions_2024_01 -> Seq Scan on transactions_2024_02 -> Seq Scan on transactions_2024_03 ... (ALL partitions)

Partitioning Benefit
Real Incident: The Hotspot That Melted Our Cluster
Six months after partitioning, we hit another wall. Our Redis cluster was handling 2 million operations per second, but one node was at 95% CPU while others sat at 15%.
The culprit: product view counters.
go// Every page view incremented the same key redis.Incr(ctx, fmt.Sprintf("views:product:%s", productID))
Our most popular product—a viral item featured on TV—was receiving 50,000 views per second. All hitting a single Redis key. On a single node.

Hotspot Problem
Solution: Sharded Counters
goconst numShards = 64 func incrementViews(ctx context.Context, productID string) error { // Randomly distribute across shards shard := rand.Intn(numShards) key := fmt.Sprintf("views:%s:shard:%d", productID, shard) return redis.Incr(ctx, key).Err() } func getViewCount(ctx context.Context, productID string) (int64, error) { // Aggregate shards (cache this result!) pipe := redis.Pipeline() cmds := make([]*redis.IntCmd, numShards) for i := 0; i < numShards; i++ { key := fmt.Sprintf("views:%s:shard:%d", productID, i) cmds[i] = pipe.Get(ctx, key) } _, err := pipe.Exec(ctx) if err != nil && err != redis.Nil { return 0, err } var total int64 for _, cmd := range cmds { val, _ := cmd.Int64() total += val } return total, nil }

Sharded Key
Results:
- Load distributed across ~16 nodes instead of 1
- Hottest node dropped from 95% to 40% CPU
- p99 latency dropped from 50ms to 2ms
Optimization: Local Buffering
For ultra-high throughput, buffer locally before hitting Redis:
gotype BufferedCounter struct { mu sync.Mutex buffer map[string]int64 redis *redis.Client maxSize int } func (bc *BufferedCounter) Increment(key string) { bc.mu.Lock() bc.buffer[key]++ if len(bc.buffer) >= bc.maxSize { bc.flushLocked() } bc.mu.Unlock() } func (bc *BufferedCounter) flushLocked() { if len(bc.buffer) == 0 { return } pipe := bc.redis.Pipeline() for key, count := range bc.buffer { pipe.IncrBy(context.Background(), key, count) } pipe.Exec(context.Background()) bc.buffer = make(map[string]int64) } // Periodic flush for stragglers func (bc *BufferedCounter) Start() { go func() { ticker := time.NewTicker(100 * time.Millisecond) for range ticker.C { bc.mu.Lock() bc.flushLocked() bc.mu.Unlock() } }() }

Local Buffering
This reduces Redis operations by 100x for bursty traffic.
SQL vs NoSQL: The Honest Decision Framework
After building systems with PostgreSQL, MongoDB, Cassandra, Redis, and DynamoDB, here's the framework I actually use:

SQL vs NoSQL Decision
When PostgreSQL Is the Right Choice
Use PostgreSQL when you need:
1. ACID transactions with complex operations
gofunc TransferMoney(ctx context.Context, from, to int64, amount decimal.Decimal) error { tx, err := db.BeginTx(ctx, &sql.TxOptions{ Isolation: sql.LevelSerializable, }) if err != nil { return err } defer tx.Rollback() // Lock both accounts in consistent order var fromBalance, toBalance decimal.Decimal err = tx.QueryRowContext(ctx, "SELECT balance FROM accounts WHERE id = $1 FOR UPDATE", min(from, to), ).Scan(&fromBalance) if err != nil { return err } err = tx.QueryRowContext(ctx, "SELECT balance FROM accounts WHERE id = $1 FOR UPDATE", max(from, to), ).Scan(&toBalance) if err != nil { return err } if fromBalance.LessThan(amount) { return ErrInsufficientFunds } _, err = tx.ExecContext(ctx, "UPDATE accounts SET balance = balance - $1 WHERE id = $2", amount, from) if err != nil { return err } _, err = tx.ExecContext(ctx, "UPDATE accounts SET balance = balance + $1 WHERE id = $2", amount, to) if err != nil { return err } return tx.Commit() }

PostgreSQL ACID
2. Complex queries across relationships
Joins, aggregations, window functions, CTEs—SQL is unmatched for analytical queries.
When MongoDB Is the Right Choice
Use MongoDB when:
1. Schema varies significantly per document
javascript// Electronics have different attributes than clothing db.products.insertMany([ { _id: "laptop-001", name: "MacBook Pro", category: "electronics", specs: { cpu: "M3 Max", ram: "64GB", storage: "2TB SSD", display: "16.2 inch Liquid Retina XDR" } }, { _id: "shirt-001", name: "Cotton T-Shirt", category: "clothing", specs: { size: ["S", "M", "L", "XL"], color: ["White", "Black", "Navy"], material: "100% Cotton", care: "Machine wash cold" } } ]);

MongoDB Product Catalog
2. Rapid prototyping with evolving requirements
Adding a field is instant—no migrations needed.
When Cassandra Is the Right Choice
Use Cassandra when:
1. Write throughput exceeds what any single node can handle
Cassandra writes are inherently distributed with tunable consistency.
2. Time-series data with known access patterns
cqlCREATE TABLE sensor_readings ( device_id uuid, reading_time timestamp, temperature float, humidity float, PRIMARY KEY ((device_id), reading_time) ) WITH CLUSTERING ORDER BY (reading_time DESC);
Partition key
device_id distributes data. Clustering key reading_time DESC sorts for efficient recent-first queries.
Cassandra IoT
When Redis Is the Right Choice
Use Redis when:
1. Latency is paramount (sub-millisecond required)
go// Session lookup in 0.1ms vs 10ms from database func GetSession(ctx context.Context, sessionID string) (*Session, error) { data, err := redis.Get(ctx, "session:"+sessionID).Bytes() if err == redis.Nil { return nil, ErrSessionNotFound } if err != nil { return nil, err } var session Session json.Unmarshal(data, &session) return &session, nil }

Redis Session Store
2. Data structures beyond key-value
Sorted sets for leaderboards, HyperLogLog for unique counts, streams for event logs.
Read Replica Lag: The Problem Nobody Talks About
Here's a scenario that broke our system:
- User updates their email
- Confirmation page loads immediately
- Page shows the OLD email (read from replica)
- User panics, updates again
- Support ticket filed
Replica lag was only 200ms, but that was enough to break the user experience.

Replica Lag Problem
Solution 1: Read-Your-Writes Consistency
Track recent writes and route accordingly:
gotype ConsistentDB struct { primary *sql.DB replica *sql.DB recentWrites sync.Map // user_id -> timestamp lagWindow time.Duration } func (db *ConsistentDB) Write(ctx context.Context, userID string, query string, args ...any) error { _, err := db.primary.ExecContext(ctx, query, args...) if err != nil { return err } // Remember this user wrote recently db.recentWrites.Store(userID, time.Now()) return nil } func (db *ConsistentDB) Read(ctx context.Context, userID string, query string, args ...any) (*sql.Rows, error) { if lastWrite, ok := db.recentWrites.Load(userID); ok { if time.Since(lastWrite.(time.Time)) < db.lagWindow { // User wrote recently, use primary return db.primary.QueryContext(ctx, query, args...) } } // Safe to use replica return db.replica.QueryContext(ctx, query, args...) }

Read Your Writes
Solution 2: LSN-Based Routing
For stronger guarantees, use the Write-Ahead Log position:
gotype LSNRouter struct { primary *sql.DB replica *sql.DB } func (r *LSNRouter) WriteAndGetLSN(ctx context.Context, query string, args ...any) (uint64, error) { var lsn uint64 tx, err := r.primary.BeginTx(ctx, nil) if err != nil { return 0, err } defer tx.Rollback() _, err = tx.ExecContext(ctx, query, args...) if err != nil { return 0, err } // Get current WAL position err = tx.QueryRowContext(ctx, "SELECT pg_current_wal_lsn()::text::pg_lsn::bigint", ).Scan(&lsn) if err != nil { return 0, err } return lsn, tx.Commit() } func (r *LSNRouter) ReadAfterLSN(ctx context.Context, minLSN uint64, query string, args ...any) (*sql.Rows, error) { var replicaLSN uint64 err := r.replica.QueryRowContext(ctx, "SELECT pg_last_wal_replay_lsn()::text::pg_lsn::bigint", ).Scan(&replicaLSN) if err != nil { return nil, err } if replicaLSN < minLSN { // Replica hasn't caught up, use primary return r.primary.QueryContext(ctx, query, args...) } return r.replica.QueryContext(ctx, query, args...) }

LSN Consistency
Store the LSN in the user's session. Subsequent reads check if replica has caught up.
Indexing: The Art of Knowing What to Index
After the incident I mentioned at the start, we implemented strict indexing reviews. Here's the framework:
The Golden Rules

Index Rules
-
Every query in production must use an index. No exceptions. Enable
log_min_duration_statementto catch slow queries. -
Index columns in WHERE, JOIN, and ORDER BY clauses. But not all of them—start with high-cardinality columns.
-
Composite indexes: Equality before Range.
sql-- Query: WHERE status = 'active' AND created_at > '2024-01-01' -- Good: Equality column first CREATE INDEX idx_status_date ON orders(status, created_at); -- Bad: Range column first (can't use status efficiently after range scan) CREATE INDEX idx_date_status ON orders(created_at, status);

Composite Index Order
Partial Indexes for Filtered Queries
If you only query certain rows, only index those rows:
sql-- Only 5% of orders are pending, but that's all we query CREATE INDEX idx_pending_orders ON orders(created_at) WHERE status = 'pending'; -- 20x smaller than full index, same performance for pending queries
Covering Indexes to Avoid Table Lookups
If you always select the same columns, include them in the index:
sql-- Frequent query SELECT account_id, balance, updated_at FROM accounts WHERE account_id = $1; -- Covering index (index-only scan) CREATE INDEX idx_accounts_covering ON accounts(account_id) INCLUDE (balance, updated_at);
PostgreSQL can satisfy the query from the index alone, without touching the table.
Security: Protecting Your Data Layer
Database security failures are among the most catastrophic in software. Here's what we've learned defending against them.
SQL Injection Prevention
Still the #1 database vulnerability. Every SQL query must use parameterized queries:
go// VULNERABLE - string concatenation query := fmt.Sprintf("SELECT * FROM users WHERE id = %s", userID) rows, err := db.Query(query) // SQL injection! // SAFE - parameterized query rows, err := db.Query("SELECT * FROM users WHERE id = $1", userID)
For dynamic queries, use a query builder:
go// Building dynamic WHERE clauses safely type QueryBuilder struct { conditions []string args []any } func (q *QueryBuilder) Where(column string, op string, value any) *QueryBuilder { argNum := len(q.args) + 1 q.conditions = append(q.conditions, fmt.Sprintf("%s %s $%d", column, op, argNum)) q.args = append(q.args, value) return q } func (q *QueryBuilder) Build() (string, []any) { query := "SELECT * FROM users" if len(q.conditions) > 0 { query += " WHERE " + strings.Join(q.conditions, " AND ") } return query, q.args }
Encryption at Rest and in Transit
In transit: Always use TLS for database connections.
goconfig := &tls.Config{ MinVersion: tls.VersionTLS12, ServerName: "db.example.com", } db, err := sql.Open("postgres", "host=db.example.com sslmode=verify-full sslrootcert=ca.crt")
At rest: Use transparent data encryption (TDE) for sensitive columns.
sql-- PostgreSQL pgcrypto extension CREATE EXTENSION IF NOT EXISTS pgcrypto; -- Encrypt PII on insert INSERT INTO users (email, ssn_encrypted) VALUES ( $1, pgp_sym_encrypt($2, $encryption_key) ); -- Decrypt on select SELECT email, pgp_sym_decrypt(ssn_encrypted, $encryption_key) as ssn FROM users WHERE id = $1;
Access Control
Principle of least privilege: Application user should only have necessary permissions.
sql-- Create application user with minimal permissions CREATE USER app_user WITH PASSWORD 'secure_password'; -- Grant only what's needed GRANT SELECT, INSERT, UPDATE ON transactions TO app_user; GRANT USAGE, SELECT ON SEQUENCE transactions_id_seq TO app_user; -- Explicitly deny dangerous operations REVOKE DELETE ON transactions FROM app_user; REVOKE ALL ON pg_catalog.pg_proc FROM app_user;
Audit Logging
For compliance, log all access to sensitive data:
sql-- Enable pgAudit extension CREATE EXTENSION pgaudit; -- Log all SELECT on sensitive tables ALTER TABLE users SET (pgaudit.log = 'read'); ALTER TABLE transactions SET (pgaudit.log = 'read, write');
Backup Security
Backups are often the weakest link:
bash# Encrypt backups pg_dump mydb | gpg --encrypt --recipient backup@company.com > backup.sql.gpg # Test restore regularly (unencrypted backup in secure environment) gpg --decrypt backup.sql.gpg | psql restore_test_db
Storage Engine Internals: B-Tree vs LSM-Tree
Understanding storage engines helps you choose the right database for your workload.
B-Tree (PostgreSQL, MySQL InnoDB)

Storage Engines
B-Trees maintain sorted data in a tree structure:
- Reads are fast: O(log n) to find any record
- Writes update the tree in place: Random I/O
- Best for: Read-heavy OLTP workloads
LSM-Tree (Cassandra, RocksDB, LevelDB)
LSM-Trees buffer writes in memory, then flush to sorted files:
- Writes are fast: Sequential I/O only
- Reads may check multiple files: Bloom filters help
- Best for: Write-heavy, time-series workloads
Write-Ahead Log (WAL)
Both use WAL for durability:

Write-Ahead Log
- Write to WAL (sequential, fast)
- Acknowledge to client
- Apply to data structures (async)
- If crash, replay WAL on startup
This is why disabling
fsync is dangerous—acknowledged writes can be lost.Interview Cheat Sheet
Schema Design Questions
-
"How would you design a schema for X?"
- Start with access patterns: How will data be queried?
- Choose partition key based on most frequent query
- Plan for data lifecycle: archival, deletion
- Consider read vs write ratio
-
"When would you denormalize?"
- When joins are too expensive (distributed systems)
- When read performance trumps write complexity
- Always: Accept data duplication, handle consistency
Scaling Questions
-
"How do you scale a database?"
- Vertical first: Bigger machine is simpler
- Read replicas for read scaling
- Partitioning for write scaling
- Sharding when single-machine is insufficient
-
"How do you handle hotspots?"
- Identify via monitoring (one node much hotter than others)
- Shard hot keys across multiple keys
- Buffer locally before writing
- Consider different data structure
Consistency Questions
-
"How do you handle replica lag?"
- Read-your-writes: Track recent writes per user
- LSN-based routing: Use WAL position
- Synchronous replication: For critical data (slower)
-
"ACID vs BASE?"
- ACID: Correctness over availability (financial systems)
- BASE: Availability over consistency (social feeds)
- Most systems need both in different parts
Key Takeaways

Database Design Mindmap
-
Schema design determines scale ceiling. Partition early, use appropriate keys, plan for billions from day one.
-
Hotspots are silent killers. Monitor node distribution, shard hot keys, buffer writes.
-
SQL vs NoSQL is about access patterns, not scale. Both can scale; they optimize for different queries.
-
Replica lag breaks user experience. Track writes, route intelligently, never assume instant replication.
-
Every query needs an index. No exceptions. Missing indexes cause outages.
The database is the foundation of every system. Get it wrong, and nothing else matters. Get it right, and everything else becomes easier.
What's Next?
In Part 5: Caching Strategies, we'll explore:
- Multi-level caching that actually works
- Cache invalidation strategies (yes, the hard problem)
- Preventing cache avalanche and thundering herd
- Security considerations for cached data
That 23-minute outage from a missing index cost us $180,000 in lost transactions. The index took 30 seconds to create. Know your data access patterns.