Caching vs. Index Optimization for High-Traffic Services
System DesignModel answerLast updated
Evaluate when to add an in-memory cache versus tuning database indexes for a high-throughput service experiencing read latency spikes.
Context
You're working on a backend service that handles financial transaction records. The service stores transaction states in PostgreSQL and exposes APIs for querying transaction details, user balances, and activity summaries. During peak traffic periods, read query latencies increase substantially, impacting user experience.
A teammate proposes adding Redis to cache all transaction state queries. You need to evaluate this architectural decision, considering both when caching is appropriate and when database-level optimizations would be more effective.
What You Should Address
Provide a structured analysis covering:
Part 1: Evaluating the Caching Approach
- Under what workload characteristics does introducing an in-memory cache make sense? Consider read/write patterns, query cost, latency requirements, and scale.
- What are the operational challenges and consistency concerns when adding a cache layer? Discuss synchronization issues, invalidation approaches, and failure scenarios.
Part 2: Database Index Optimization
- Explain how multi-column indexes function and how column ordering affects query performance. Discuss equality versus range predicates.
- What are the downsides of adding indexes? Cover the impact on write operations, storage overhead, and maintenance requirements.
- How would you diagnose whether queries are I/O-bound, poorly planned, or affected by other database issues? Describe relevant tools and metrics.
Part 3: Decision Process
- Outline a systematic approach for choosing between database optimization and adding a cache layer for this specific scenario.
Hints
Hint 1
Consider the read-to-write ratio during peak traffic - transaction states change frequently
Hint 2
Multi-column indexes are only efficient when queries match the leftmost columns in order
Hint 3
Cache consistency is hardest when both the database write and cache invalidation must succeed together
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Caching vs. Index Optimization
Understanding the Problem
This question tests whether you can identify root causes before adding infrastructure. A cache seems like the obvious solution to slow reads, but it introduces complexity that may be unnecessary if the database itself can be optimized.
Part 1: When to Use In-Memory Caching
Caching is appropriate when:
-
High read-to-write ratio exists. If each piece of data is read 10+ times for every write, caching provides significant benefit. For transaction states that update with each status change, this ratio is likely much lower.
-
Computation cost is high. Aggregations like user balance summaries or activity rollups across thousands of records are expensive to compute repeatedly. Caching the computed result saves CPU and I/O. Simple key lookups of transaction state don't fit this pattern.
-
Bounded staleness is acceptable. Dashboards and analytics can tolerate slight delays. Transaction states used for authorization decisions or financial calculations cannot - serving stale data could enable duplicate charges or incorrect balances.
-
Hot key access patterns. When many clients repeatedly request the same data (like a viral post's metrics), caching prevents redundant database queries.
-
Scale exceeds what database replicas can handle. After exhausting vertical scaling and read replicas, a cache provides another defense layer.
Transaction state doesn't match these criteria well. During peak traffic, transactions are both written and read frequently, staleness is unacceptable for financial correctness, and access patterns are likely distributed across many different transactions rather than concentrated on hot keys.
Consistency challenges with caching:
-
Synchronization failures. The classic problem: your application writes to the database successfully, then crashes or encounters a network partition before invalidating the cache. The cache now serves outdated information indefinitely.
-
Race conditions. Even with write-through invalidation:
- Thread A reads from cache (miss), queries database, gets
status=PENDING - Thread B writes
status=COMPLETEDto database and deletes cache key - Thread A writes
status=PENDINGback to cache
The cache is now stale despite proper invalidation logic.
- Thread A reads from cache (miss), queries database, gets
-
Invalidation strategies:
- Time-to-live (TTL) guarantees staleness bounds but ensures some staleness always exists
- Event-driven invalidation via message queues or change-data-capture adds another distributed system to monitor and maintain
- Write-through patterns require every code path to remember invalidation
-
Cache failure modes. When cache instances restart or fail over, all traffic suddenly hits the database simultaneously - exactly when you need the cache most. This requires request coalescing and proactive cache warming.
Comparison to read replicas: Replication is native to the database, preserves ordering guarantees, has well-understood lag monitoring, and requires no application-level consistency logic.
Part 2: Index Optimization Strategy
How multi-column indexes work:
A composite index on (user_id, status, timestamp) stores entries sorted by user_id first, then status within each user, then timestamp within each user-status combination. The database can efficiently seek to any leading prefix of these columns.
-
Leftmost prefix matching. A query filtering on
statusalone cannot use this index for efficient seeking - the database would need to scan the entire index. However, filtering onuser_idor(user_id, status)can. -
Equality before range predicates. Place columns with equality comparisons first, then range comparisons. A query like
WHERE user_id = ? AND timestamp > ?benefits from(user_id, timestamp). Once a range predicate is applied, subsequent columns aren't useful for seeking (though they can still be used for filtering). -
Covering indexes. Including additional columns that appear in the SELECT clause allows the database to satisfy queries entirely from the index without accessing the table heap, eliminating I/O.
Index costs:
-
Write amplification. Every insert or update that modifies indexed columns must update all relevant indexes, generating additional disk writes and write-ahead log entries. For high-write workloads, each index materially slows down writes.
-
Storage and memory pressure. Indexes consume disk space and compete for buffer pool memory with table data. If indexes push frequently-accessed table pages out of memory, you've traded one I/O problem for another.
-
Update performance. When an indexed column changes, the database often cannot perform an in-place update and must insert a new row version and mark the old one dead. This generates index bloat over time.
-
Maintenance overhead. Indexes accumulate dead entries and require regular vacuuming. Monotonically increasing keys (like timestamps) can cause page splits and contention on the rightmost index pages.
Diagnosing query performance:
Use EXPLAIN (ANALYZE, BUFFERS) with track_io_timing enabled to understand where time is spent:
-
I/O-bound: High buffer read counts with high I/O timing indicates the working set exceeds available memory or the query accesses too many disk pages.
-
Poor query plan: High buffer hit rates but slow execution suggests the query plan touches far too many pages. Check for full table scans where indexes should be used, or examine whether index selectivity is poor.
-
Stale statistics: Large discrepancies between estimated and actual row counts mean the query planner is making decisions based on outdated information. Regular
ANALYZEruns are essential. -
Index bloat: Buffer counts far exceeding what the index size suggests indicates dead entries accumulating faster than vacuum can reclaim them.
-
Filtering inefficiency: Many "Rows Removed by Filter" means the index isn't selective enough for the query predicates.
Part 3: Systematic Decision Framework
-
Profile before acting. Use query performance monitoring to identify which specific queries cause latency spikes and their execution frequency. Determine whether the problem is a few expensive queries or overall load.
-
Examine execution plans. For the slowest queries, check whether they use appropriate indexes, whether table statistics are current, and whether the planner's estimates match reality.
-
Optimize the database first:
- Add or modify indexes to match query patterns, prioritizing equality predicates and leftmost prefix rules
- Use partial indexes to cover only relevant rows (e.g.,
WHERE status IN ('pending', 'processing')to exclude completed transactions) - Tune autovacuum settings if bloat is evident
- Add covering columns for frequently-accessed data
- Consider partitioning by time if the dataset is large and queries naturally filter by date ranges
-
Scale with read replicas for queries that can tolerate replication lag (typically tens of milliseconds).
-
Introduce caching selectively only for workloads that truly benefit: expensive aggregations, high read-to-write ratios, and scenarios where staleness is acceptable. Cache derived data and computed results rather than transactional state.
For this transaction service scenario, I would recommend focusing on database optimization first. Transaction state has tight consistency requirements, frequent updates, and relatively inexpensive lookups - characteristics that make caching risky and low-value. Adding Redis without fixing the underlying query inefficiencies simply adds operational complexity while leaving the root cause unresolved.
Common Mistakes
- Assuming a cache always improves performance without analyzing the workload characteristics
- Underestimating consistency challenges and assuming "just delete on write" is sufficient
- Adding indexes without considering write amplification costs
- Not measuring actual query performance before making architectural changes
- Caching highly mutable data where staleness creates correctness issues