Database — Relational (RDBMS)¶
A relational database (SQL) organizes data in tables.
ACID properties¶
ACID describes relational database transactions:
| Property | Meaning |
|---|---|
| Atomicity | Each transaction is all-or-nothing. |
| Consistency | A transaction moves the DB from one valid state to another. |
| Isolation | Concurrent transactions have the same result as if run serially. |
| Durability | Once committed, a transaction stays committed. |
Techniques to scale a relational database¶
- Master-slave replication
- Master-master replication
- Federation (functional partitioning)
- Sharding (data partitioning)
- Denormalization
- SQL tuning
Master-Slave Replication¶
-
The master serves reads and writes, replicating writes to one or more slaves.
-
Slaves serve reads only, and can replicate to additional slaves (tree-like).
- If the master fails, the system can run in read-only mode until a slave is promoted to master (or a new master is provisioned).
Disadvantages¶
- Extra logic is needed to promote a slave to master.
- See "Disadvantages: replication" below (applies to both master-slave and master-master).
Master-Master Replication¶
- Both masters serve reads and writes, coordinating with each other on writes.
- If either goes down, the system continues with both reads and writes.
Disadvantages¶
- Needs a load balancer or app-logic changes to decide where to write.
-
Most master-master systems are either loosely consistent (violate ACID) or have increased write latency due to synchronization.
-
Conflict resolution grows as more write nodes and higher latency are added.
Disadvantages of replication (both kinds)¶
- Potential data loss if the master fails before replicating new writes.
- Writes are replayed to read replicas; heavy writes can bog them down.
- More read slaves → more replication → greater replication lag.
- Some systems write in parallel on the master but only sequentially on replicas.
- Replication adds hardware and complexity.
Federation (Functional Partitioning)¶
Splits databases by function. Instead of one monolith, you might have separate databases for forums, users, and products.
Benefits:
- Less read/write traffic to each DB → less replication lag.
- Smaller DBs → more data fits in memory → more cache hits (better locality).
- No single central master serializing writes → parallel writes, higher throughput.
Disadvantages¶
- Not effective if your schema needs huge functions/tables.
- App logic must know which DB to read/write.
- Joining data across two DBs is more complex.
- More hardware and complexity.
Sharding (Data Partitioning)¶
Distributes data across databases so each manages only a subset of the data. Example: as users grow, add more shards to a users database.
Benefits (similar to federation):
- Less read/write traffic and replication per shard.
- More cache hits; smaller index sizes → faster queries.
-
One shard failing doesn't take down the others (add replication to avoid data loss).
-
Parallel writes → higher throughput.
Common sharding keys: user's last-name initial or geographic location.
Disadvantages¶
- App logic must route to the right shard (complex SQL possible).
- Data distribution can become lopsided (e.g., power users on one shard).
- Rebalancing adds complexity; consistent hashing reduces data moved.
- Joining across shards is complex.
- More hardware and complexity.
Denormalization¶
Improves read performance at the cost of write performance by storing redundant copies of data in multiple tables to avoid expensive joins.
-
Some RDBMS (PostgreSQL, Oracle) support materialized views to maintain these redundant copies.
-
Once data is distributed (federation/sharding), cross-data-center joins get harder — denormalization may avoid them.
-
Reads often outnumber writes 100:1 or 1000:1, so optimizing reads pays off.
Disadvantages¶
- Data is duplicated.
- Constraints to keep copies in sync increase design complexity.
- Under heavy write load, a denormalized DB may perform worse than normalized.
SQL Tuning¶
A broad topic. The key workflow: benchmark and profile first.
- Benchmark — simulate high load (e.g.,
ab). - Profile — use tools like the slow query log to find bottlenecks.
Tighten the schema¶
- MySQL dumps to disk in contiguous blocks for fast access.
- Use
CHARoverVARCHARfor fixed-length fields (fast, random access). - Use
TEXTfor large blocks of text (e.g., blog posts); supports boolean search. - Use
INTfor numbers up to 2^32 (≈4 billion). - Use
DECIMALfor currency (avoid float rounding errors). - Avoid storing large
BLOBs — store the location of the object instead. VARCHAR(255)maximizes a byte in some RDBMS.- Set
NOT NULLwhere applicable to improve search performance.
Use good indices¶
- Index columns you query on (
SELECT,GROUP BY,ORDER BY,JOIN). -
Indices are usually B-trees: sorted data with logarithmic-time search, insertion, and deletion.
-
Trade-off: indices use memory and slow writes (index must update too).
- For bulk loads: disable indices, load, then rebuild.
Avoid expensive joins¶
- Denormalize where performance demands it.
Partition tables¶
- Move "hot spots" into a separate table to help keep it in memory.
Tune the query cache¶
- In some cases the query cache can cause performance issues.
Common Interview Questions¶
Design a URL shortener (Pastebin/Bitly)
Why it's asked here: schema design + read-heavy SQL scaling.
Key points to discuss:
- Schema:
short_code(PK),long_url,created_at,expires_at,user_id. - Hash generation (MD5/Base62) and collision handling.
- Read-heavy (100:1) → master-slave replication for reads.
- When to shard (by
short_code) and denormalize.
flowchart LR
U[User] --> A[App server]
A -->|POST /shorten| H[Hash generator]
H --> DB[(URLs table)]
U -->|GET /code| C[(Cache)]
C -->|miss| DB
Design the Twitter timeline / news feed
Why it's asked here: the classic sharding + denormalization problem.
Key points to discuss:
- Fan-out on write vs fan-out on read trade-off.
- Sharding the tweets table and the timeline cache.
- Denormalization to avoid expensive joins when rendering a feed.
- Master-slave for reads, with replication-lag implications.
flowchart LR
P[Post tweet] --> F[Fan-out service]
F --> T[(Timeline cache)]
F --> D[(Sharded tweets)]
U[User] --> T
T -->|miss| D
Design Amazon's sales ranking by category
Why it's asked here: heavy aggregation reads → SQL tuning territory.
Key points to discuss:
- Indices on (category, sales_count, timestamp).
- Denormalized/materialized ranking tables to avoid expensive joins.
- Partition hot categories to keep them in memory.
- Benchmark + profile (slow query log) before optimizing.
flowchart LR
S[Sales event] --> O[(Orders DB)]
O -->|aggregate| V[Materialized view]
V -->|index category + count| R[Ranking query]
Further reading¶
- Scalability, availability, stability, patterns
- Multi-master replication
- Scaling up to your first 10 million users
- The coming of the shard
- Consistent hashing
- Denormalization
Twitter Timeline / News Feed Full Design¶
To design a Twitter-like timeline, first define the workload and requirements. Assume 200 million daily active users, 500 million new tweets per day, and a peak of about 10,000 tweets per second. Timeline reads are far more frequent than writes, often 100:1 or more. The functional requirements are to let users post tweets, follow other users, and view a home timeline containing recent tweets from all accounts they follow. The non-functional requirements are low-latency timeline reads, horizontal scalability, high availability, and durability for accepted tweets. Timeline freshness can be eventually consistent because a short delay before a tweet appears for some followers is usually acceptable.
The high-level architecture separates the tweet write path from the timeline read path. Clients send requests through DNS and a load balancer to stateless application services. A tweet service validates and stores the new tweet in a sharded tweet store. After the tweet is durable, a fanout service asynchronously pushes the tweet ID into precomputed timeline caches for the author's followers. When a user opens the app, the timeline service reads the user's timeline from a Redis-style cache and returns the latest tweet IDs, then hydrates the actual tweet content from the tweet store or a content cache. This architecture keeps reads fast because the timeline is already assembled, while writes can fan out asynchronously without blocking the posting user.
The data model uses different stores for different access patterns. Users, follows, and account metadata are relatively small and relational, so they can live in a SQL database with strong consistency and indexed lookups. Tweets themselves are high-volume and append-heavy, so they are sharded by tweet ID across a distributed database or NoSQL store. The user timeline is stored in Redis as a sorted set or list keyed by user ID, with tweet IDs ordered by timestamp. Redis is used because timeline reads are extremely hot and need low-latency access. The social graph can be stored in SQL as a follows table or in a graph store such as FlockDB or Neo4j when traversal depth and relationship queries grow. Raw media such as images and videos is kept in object storage and served through a CDN, not through the database tier.
The core mechanism is hybrid fanout. For ordinary users, the system uses fanout on write. When a user posts a tweet, the fanout service looks up the follower list and inserts the tweet ID into each follower's timeline cache. This makes timeline reads a simple Redis lookup. The follower list is large, so the service paginates through it using an async queue and worker pool. To prevent one celebrity's tweet from creating millions of expensive cache writes, accounts with very large follower counts use fanout on read. The celebrity tweet is stored normally, but it is not eagerly pushed to all followers. Instead, when a follower views their home timeline, the timeline service reads the user's precomputed timeline from cache and then merges in recent tweets from high-profile accounts the user follows. This hybrid approach limits write amplification while preserving fast reads for most users.
Scaling and availability are achieved by sharding and replication at every layer. The application tier is stateless and scales horizontally behind load balancers. The tweet store is sharded by tweet ID to spread write load, and each shard is replicated for durability and failover. The timeline cache is sharded by user ID and partitioned across many Redis nodes so no single node holds all hot timelines. Redis replicas and failover protect the timeline cache from node loss. The fanout worker pool can be scaled independently and uses an asynchronous message queue to smooth bursts. If a user has not logged in for a long time, the system can rebuild a missing timeline by reading the user's followed accounts and fetching their most recent tweets from the sharded tweet store. This avoids storing every inactive timeline forever.
The most important trade-off is write fanout versus read fanout. Fanout on write makes timeline reads very fast but creates massive write amplification and can be extremely expensive for popular accounts. Fanout on read removes that write amplification but increases read latency and requires merging from multiple sources. The design therefore uses a hybrid approach. Another trade-off is consistency versus availability. Timeline caches are eventually consistent: after a tweet is posted, different followers may see it at slightly different times because fanout is asynchronous. Tweets themselves, however, should be durable and strongly visible to the author immediately. Denormalizing by storing the same tweet ID in many timeline caches improves read performance at the cost of storage and cache maintenance. Sharding improves throughput but makes cross-shard joins such as computing a feed for a brand-new user more complex. These trade-offs are the core of the Twitter timeline design.
flowchart LR
U[Client] --> LB[Load Balancer]
LB --> TW[Tweet Service]
LB --> TS[Timeline Service]
TW --> D[(Sharded Tweet Store)]
TW --> Q[Fanout Queue]
Q --> FW[Fanout Worker Pool]
FW --> G[(User Graph / Follower Store)]
FW --> C[(Sharded Timeline Cache)]
TS --> C
TS --> D
FW --> D
U --> CDN[CDN / Object Storage for media]
Design Amazon's Sales Ranking by Category¶
This design must produce a per-category list of best-selling products and update those rankings as sales and other engagement signals arrive. For a planning estimate, assume Amazon has 500 million catalog items, roughly 1,000 product categories, 5 million transactions per hour at peak, and more than 100 times more reads than writes for ranking pages. The main functional requirement is to return the top N products in any category quickly, for example top 20 or top 100. Non-functional requirements include low-latency ranking reads, freshness of rankings within seconds or minutes, high availability during peak shopping events, and the ability to absorb occasional burst writes without blocking reads.
The high-level architecture has a write and aggregation path and a read and serving path. Sales events and inventory changes are published from order, payment, and return systems to a durable event log such as Kafka. Stream processors consume these events, aggregate sales per product and category into time-bucketed counters, and update a set of ranking stores. A ranking query service reads from this store on ranking page requests. Because the page load is read-heavy, the ranking data for hot categories is cached at the application tier and, for very hot categories, at the CDN or page edge. A batch pipeline also reconciles counts from the relational order history to correct drift and handle late-arriving events.
The data model separates raw transactions, aggregated sales state, and materialized rankings. Raw sales events in the order database are transactional rows such as order_id, product_id, category_id, quantity, price, and timestamp. Aggregates are stored in a columnar analytical store or a key-value or wide-column store keyed by product_id and time bucket, with fields such as units_sold, revenue, returns, and rating. Materialized rankings are stored per category as a sorted set or table keyed by category_id, with product_id and rank score. A relational database may store category metadata and product metadata, but the hot ranking path should avoid expensive joins by reading precomputed rankings.
The core mechanism is pre-aggregation and materialized ranking. Raw sales are not joined and sorted on every page view. Instead, a stream processor such as Flink or Spark Streaming consumes sales events, updates per-product aggregates in partitioned storage, and periodically recomputes top-N lists per category. The ranking score is a weighted function of recent sales, long-run sales, ratings, returns, and potentially margin or availability. Only the top several hundred products per category are retained, keeping the ranking store small. Reads query a single partition by category, so latency stays low even under heavy traffic.
For scaling and availability, the system partitions work by product and category. The event log is replicated and enables replay after failures. Stream processors run in parallel, with state partitioned by category or product ID and backed up to a changelog. Ranking stores are sharded by category so hot categories, such as books or electronics, can be isolated and scaled independently. A cache layer absorbs read spikes, and edge caching may serve anonymous ranking pages with TTLs. The relational order system remains the source of truth and is replicated with read replicas for reconciliation. Failures in streaming are handled by retries, checkpointing, and idempotent writes, so a failed aggregator can rebuild its state without producing duplicate sales.
The main trade-off is freshness versus cost and complexity. Precomputed rankings give fast reads but can lag raw sales by several seconds or more, depending on aggregation windows. Longer windows produce more stable rankings and lower write load but are less responsive to a sudden best-seller. Exact counts require more expensive coordination and are usually unnecessary, so the design accepts approximate or eventually consistent rankings. Another trade-off is cacheability versus personalization: fully anonymous category best-seller pages can be cached at the edge, while personalized rankings must be assembled dynamically and therefore cannot be cached as aggressively.
flowchart LR
O[Order/Payment/Return systems] --> K[Kafka event log]
K --> S1[Stream aggregator 1]
K --> S2[Stream aggregator 2]
S1 --> A[(Product/category aggregate store)]
S2 --> A
A --> R[Materialized top-N ranking store sharded by category]
R --> Q[Ranking query service]
Q --> C[(Redis cache)]
C --> CDN[CDN/edge cache]
U[User] --> CDN
U --> Q
DB[(Transactional order DB)] --> B[Batch reconciliation]
B --> A
Requirements and Scale for a Twitter Timeline¶
To size a Twitter or news feed system correctly, begin with explicit workload numbers. Assume 200 million daily active users, 500 million new tweets per day, and a peak write rate around 10,000 tweets per second. Timeline reads are much hotter than writes, often 100:1 or more, so peak read traffic may be on the order of 1 million timeline reads per second. If an average tweet record, including metadata and indexes, is about 200 bytes, then 500 million tweets per day produce roughly 100 GB of raw tweet data per day, about 3 TB per month, and about 36.5 TB per year. The timeline cache is also large: 200 million active users each storing several hundred tweet IDs in a Redis sorted set or list can require a multi-terabyte cache tier, which is why the timeline cache must be sharded by user ID across many nodes rather than kept on one machine. These estimates drive the need for a sharded tweet store, a Redis timeline cache, asynchronous fan-out workers, and read-heavy scaling instead of a single database.
flowchart LR
U[Client] --> LB[Load Balancer]
LB --> TW[Tweet Service]
LB --> TS[Timeline Service]
TW --> D[(Sharded Tweet Store)]
TW --> Q[Fanout Queue]
Q --> FW[Fanout Workers]
FW --> G[(User Graph / Follower Store)]
FW --> C[(Sharded Timeline Cache)]
TS --> C
TS --> D
FW --> D