Cutting Read Latency in a Normalized Relational Schema
System DesignModel answerLast updated
Speed up the hottest reads of a live service backed by a normalized database, and explain the write-path cost, freshness impact and rollout plan of each change.
A production service stores its data in a normalized relational database. Its most frequent read endpoints build each response by joining several related tables, and read latency on those endpoints is above what the team wants.
Your task: describe how you would change the database design and the read path to lower read latency.
In your answer, cover:
- How you would find out where the time goes before changing anything.
- Which schema, indexing and query changes you would make, and which read path each one targets.
- Whether and how you would add caching, including invalidation, a bound on staleness, and what happens when many entries expire together.
- What each change costs in write latency, storage, complexity and data freshness.
- How you would keep any derived or duplicated data correct over time.
- How you would roll the change out safely on a live system.
You have about 15 minutes, so lead with the changes that matter most and be prepared to go deeper on any of them. State any assumptions you make about the workload (read/write ratio, table sizes, freshness requirements, latency target).
Hints
Hint 1
Do not redesign first. Which queries are slow, and is the time spent in joins, aggregates computed at read time, missing indexes, many round trips per request, or lock contention with writes?
Hint 2
Order the fixes from cheapest and safest to most invasive: query and index fixes, then read replicas and caching, then precomputed or denormalized read models. For each, name the write cost and the staleness it introduces.
Hint 3
Derived data drifts. Decide how it is updated (same transaction, async events, or periodic rebuild), how you detect and repair mismatches, and how you migrate with dual writes, backfill, shadow reads and a fast rollback.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
I would state these up front and adjust once they are confirmed. The workload is read-heavy (roughly 50:1 or more), a few endpoints dominate traffic, and the tables are large enough that multi-table joins and read-time aggregates are visible in p95 latency. Most reads tolerate seconds of staleness, but a user must see their own writes immediately.
Step 1: Diagnose before redesigning
- Rank endpoints and queries by total time (frequency x latency) and by p95/p99, not only by average. Use the slow query log,
pg_stat_statementsor the equivalent, and request traces. - Run
EXPLAIN (ANALYZE, BUFFERS)on the top queries. Look for sequential scans, sorts spilling to disk, bad join order, large row estimates that are wrong, and N+1 patterns where one request issues dozens of queries. - Check for contention: long write transactions, lock waits, replication lag, and connection pool exhaustion.
This often removes a large share of the latency with no schema redesign, and it tells you which paths deserve a heavier change.
Step 2: Cheap, low-risk fixes first
- Indexes. Add composite indexes that match the filter and sort order of hot queries. Use covering indexes (included columns) so the query is answered from the index alone. Cost: slower writes and more storage per index, so remove unused indexes.
- Query shape. Eliminate N+1 by batching or joining, select only needed columns, replace offset pagination with keyset pagination, and avoid functions on indexed columns.
- Read replicas. Send read traffic to replicas. Cost: replication lag, so route read-your-writes traffic (a user just after they write) to the primary or pin the session to the primary for a short window.
Step 3: Precompute what is read far more often than it changes
Denormalized columns and counters. Store things like comment_count or avg_rating on the parent row instead of computing them on every read. Update them in the same transaction as the write for strict correctness (cost: write amplification and hot-row contention on popular parents), or asynchronously from an event stream or outbox (cost: seconds of staleness, but no contention). For hot counters, shard the counter or batch increments.
Read models / materialized views. For the hottest endpoint, build a table (or document) shaped exactly like the response, so the read is a single primary-key lookup with no joins. Options:
- Materialized view refreshed periodically or incrementally. Simple, but staleness equals the refresh interval and full refreshes get expensive.
- A separate read table maintained by an outbox plus a consumer. Near-real-time, but you now own an eventually consistent pipeline.
Trade-off summary: reads go from O(joins) to O(1), writes fan out to every read model that includes the changed entity, and you accept a defined staleness window. Keep the normalized tables as the source of truth so read models can always be rebuilt.
Partitioning and archiving. If queries mostly touch recent data, partition by time and archive cold rows, so indexes and working sets fit in memory.
Step 4: Caching
- Pattern: cache-aside for most reads. The app checks the cache, falls back to the database, then populates the cache.
- Keys and granularity: cache the assembled response or entity, keyed by ID and version, so invalidation maps cleanly to a write.
- Invalidation: on write, delete the key (preferred over updating it, which races). Add a TTL as a safety net to bound staleness, for example 30-300 seconds depending on freshness needs. For read-your-writes, bypass the cache or write through for the author.
- Stampede protection: when a hot key expires, many requests hit the database simultaneously. Use request coalescing (single-flight, one request rebuilds while the others wait), a short lock, jittered TTLs so keys do not expire together, and optionally stale-while-revalidate to serve the old value while refreshing in the background.
- Negative caching: cache "not found" briefly to avoid repeated misses on missing IDs.
- Cost: another system to run, a possibility of stale data, and cold-start load after cache failure. Size the database so it survives a cache outage, or at least degrades gracefully.
Step 5: Keeping derived data correct
- Prefer a single path for updates (transaction or outbox) so derived data cannot be forgotten by a code path.
- Make consumers idempotent (event IDs, version numbers) so retries and replays do not double count.
- Run a periodic reconciliation job that recomputes a sample (or all) of the derived values from the source of truth, alerts on drift beyond a threshold, and repairs it.
- Keep the ability to rebuild any read model from scratch.
Step 6: Safe rollout on a live system
- Create the new structure additively (new column, table or index built concurrently, for example
CREATE INDEX CONCURRENTLY). Never block writes. - Start dual writes to old and new structures behind a feature flag.
- Backfill existing data in throttled batches, then verify counts and checksums.
- Shadow reads: serve from the old path, compare against the new one, and log mismatches.
- Ramp traffic gradually (1%, 10%, 50%, 100%) while watching p50/p95/p99, error rate, replication lag and cache hit rate.
- Keep the old path and a fast rollback until the new one has been stable for a while, then remove it.
Prioritization for a 15-minute slot
Lead with: (1) measure and fix queries and indexes, (2) a single precomputed read model or counters for the hottest endpoint, (3) cache-aside with TTL and stampede protection, (4) rollout and reconciliation. Mention replicas, partitioning and sharding as later steps only if the numbers justify them.
Common mistakes
- Denormalizing everything up front instead of targeting measured hot paths.
- Adding a cache without an invalidation story or a staleness bound.
- Ignoring read-your-writes when moving reads to replicas or caches.
- Forgetting that every index and denormalized copy taxes the write path.
- Optimizing the average while the real complaint is p99.
- Migrating with a big-bang cutover and no rollback.