Performance & Reliability

Caching and Performance Optimization: Choosing Layers, Measuring Trade-offs

A Redis cache with a 95% hit rate can still leave an endpoint slow: the remaining misses may run an unindexed query, queue behind a saturated connection pool, or fan out to another service. Before adding a cache, measure where the request spends its time—especially at the tail of the latency distribution.

Published November 28, 2026

Begin with the slow request, not the cache product

A cache is useful only when it shortens the critical path for a meaningful share of requests without violating the system’s freshness requirements. The first step is therefore not selecting Redis, Memcached, a database replica, or a materialized view. It is tracing a representative request from ingress to response and separating execution time from waiting time.

Capture latency percentiles, not just averages. If an endpoint has a 25-millisecond median but a 900-millisecond p99, the average can make the service look healthier than it feels to users. Instrument database query duration, connection-pool acquisition time, cache lookup time, downstream calls, and serialization separately. A trace showing 18 milliseconds in SQL and 240 milliseconds waiting for a database connection points to a different intervention than one showing 200 milliseconds executing a full table scan.

Inspect query plans with the database’s native tooling—such as EXPLAIN ANALYZE in PostgreSQL—and check whether the query uses the intended index under realistic data volume. An index that exists but is ignored does not rescue a cache miss. Nor does a cache solve a pool that is too small for the concurrency profile or a slow dependency called on every request.

Establish a baseline before changing the request path. Record p50, p95, and p99 latency, database CPU, query count, pool wait time, cache hit rate, and error rate over a representative traffic window. Keep the workload and measurement interval comparable after deployment. Otherwise, a traffic lull can masquerade as an optimization.

What a hit rate conceals

A hit rate is a ratio of cache hits to lookups; it does not say how expensive misses are, whether hot keys dominate the result, or whether a hit serves the right version of the data. A 95% hit rate can coexist with poor p99 latency when the 5% of misses are disproportionately slow. It can also conceal a severe cold-start problem if the service restarts and every key must be repopulated.

Use hit rate alongside miss latency, origin load, eviction rate, key cardinality, and request latency. Break those measures down by endpoint and, where practical, by key family. A single global hit rate may be dominated by a popular catalog route while an account-settings route misses almost every time. The aggregate number is then accurate but operationally unhelpful.

Consider a service receiving 10,000 requests per second. At a 95% hit rate, 500 requests per second still reach the origin. If each miss executes a query taking 80 milliseconds and the database can safely sustain only 300 such queries per second, the cache has not removed the capacity problem. If those misses also wait in a connection queue, the resulting tail can be far worse than the query’s execution time suggests.

There is also a cost to every cache lookup: network hops, serialization, memory, operational ownership, and another failure mode. Caching a small, fast query can add more complexity than benefit. The right comparison is the full cost of the uncached path against the full cost of the cached path, including invalidation and recovery—not a database query measured in isolation.

Cache-aside: flexible reads, explicit invalidation

Cache-aside, also called lazy loading, is a common pattern for request-driven reads. The application checks the cache; on a miss, it reads the source of truth, stores the result, and returns it. The cache is not updated automatically by the database. That makes the pattern straightforward to introduce around selected queries, but it leaves freshness and concurrency behavior in application code.

Typical read path

GET key → cache miss → query database → populate key → return result

Cache-aside works well for data that is read frequently, changes less frequently, and can tolerate a defined period of staleness. A product catalog entry might be cached for 60 seconds if a short delay in reflecting a description change is acceptable. The same TTL is not automatically appropriate for inventory, account balances, authorization state, or any value whose stale presentation could cause a harmful decision.

Expiration is not a complete invalidation strategy. A write can update the database while an older read is in flight; that read may then repopulate the cache with stale data after the write has deleted the key. Under concurrency, this race is real even when application code appears to invalidate correctly. Options include versioned keys, carefully ordered updates, short TTLs, or a write-through or event-driven update path. Each adds complexity or latency, so select one according to the consequence of stale data.

Cache stampedes are another common failure mode. If a popular key expires and hundreds of requests miss simultaneously, they may all perform the same origin query. Use request coalescing or a per-key lock to let one request populate the value while others wait or receive a controlled fallback. A small amount of TTL jitter can also prevent many keys set together from expiring at the same instant. Locks require bounded waits and failure recovery: a lock that persists after its owner crashes can turn a stampede into an outage.

Negative caching can prevent repeated work for absent records, but its TTL should be conservative. If a client asks for a resource before it is created, caching “not found” for several minutes can hide the resource after creation. Cache the absence only when that behavior is acceptable and when the key space cannot be abused to fill memory with arbitrary misses.

Write-through: fresher reads, more work on writes

With write-through, an application or caching layer updates the cache as part of the write path, typically after or alongside a successful source-of-truth update. The goal is to avoid the gap in which a later read finds stale data or has to repopulate an empty key. This can be useful when the same records are read immediately after being changed and when the application can control both the write and cache update.

The trade-off is additional write latency and another operation that can fail. If the database commits but the cache update fails, the system must decide whether to fail the request, retry, or accept temporary inconsistency. Failing after the database commit is especially confusing: the caller receives an error even though the data changed. A transactional outbox can make cache-update events durable, but it introduces asynchronous propagation and does not make the cache and database one atomic system.

Write-through also does not necessarily suit every key. Updating a cached object may require invalidating several derived keys, lists, or search results. A change to a product, for example, could affect its detail record, category listing, and featured-products response. Broad fan-out can make writes expensive and create ordering problems. Keep cache ownership explicit: document which component writes each key, what event changes it, and how missed updates are repaired.

For many systems, a practical compromise is to update or invalidate a small set of well-defined keys synchronously and let a durable event process wider projections. The synchronous boundary should cover the consistency promise the API actually makes; the rest can converge asynchronously if clients can tolerate it.

Materialized views: cache the computation, not just the row

Some slow reads are expensive because they join, aggregate, or transform large amounts of data. A key-value cache can store the final response, but a materialized view stores a precomputed result in the database or a dedicated read model. This shifts work from query time to refresh time and can give operators a more inspectable, durable representation than an opaque collection of application-managed keys.

Materialized views fit reporting, dashboards, and complex read models where the source data changes more often than the output needs to be recomputed. In PostgreSQL, for example, a materialized view can be refreshed explicitly; a concurrent refresh can keep reads available, subject to the database’s requirements for a suitable unique index. Refresh schedules define a freshness window. If the view refreshes every five minutes, consumers should understand that the result may be nearly five minutes old, plus refresh duration.

For near-real-time systems, teams often maintain projections from a change stream or event log rather than periodically rebuilding them. That approach can reduce refresh spikes and support purpose-built queries, but it creates a distributed-consistency problem: consumers must know whether a projection has processed a given change. Track lag, make replays safe, and provide a rebuild procedure from authoritative data. A projection that cannot be reconstructed is a second source of truth, whether or not the architecture calls it a cache.

Materialized views are not free performance. They consume storage, need refresh capacity, and can move load from interactive reads to periodic writes. A nightly report that refreshes a large view at 09:00 may simply convert slow user queries into a sharp database workload at the start of business. Stagger refreshes, measure refresh duration, and consider incremental maintenance when full recomputation is too costly.

Read replicas: more read capacity, not a cache

A read replica serves database queries from a replicated copy rather than the primary. It can increase read capacity and isolate some analytical or read-heavy traffic, but it differs from a cache: a replica still executes the query and still consumes database resources. It is useful when query execution is reasonable and the primary is constrained by read load, not when a pathological query needs to be hidden behind more hardware.

Replication is commonly asynchronous. A write may commit on the primary before the replica has applied it, so an immediate read from the replica can return an older value. This read-after-write inconsistency can break workflows such as “create, then fetch” or “update, then confirm.” Route those reads to the primary, use a consistency token or replication position where supported, or keep a narrowly scoped cache of the newly written value. The choice should be part of the application’s consistency contract.

Replica lag is an operational signal, not a theoretical footnote. Monitor it and define what the service does when lag exceeds its acceptable threshold: route sensitive reads to the primary, reduce replica traffic, or return a clearly bounded stale result. Sending every read to a replica without a lag policy can make behavior unpredictable precisely when the database is under stress.

Replicas can also multiply the cost of inefficient queries. A full scan that is tolerable on one primary may become a recurring burden across several replicas, while replication itself must keep up with writes. Test representative query plans and write volume before treating replica count as a direct scaling lever.

Connection pooling: remove queues before adding layers

Applications often open far more database connections than the database can use efficiently. Connection pooling reuses a bounded set of established connections, avoiding repeated setup overhead and limiting concurrency at the database. But a pool is also a queue. When all connections are occupied, new requests wait; the pool’s acquisition time can dominate endpoint latency even while individual SQL statements remain fast.

Measure active connections, idle connections, waiters, acquisition latency, and time spent holding each connection. A 200-millisecond pool wait should not be misdiagnosed as a slow query. Investigate long transactions, queries that hold connections while making network calls, and application concurrency that exceeds the database’s useful parallelism. Increasing the pool size may reduce application-side waiting while overloading the database with more simultaneous work.

For example, suppose a service runs 40 application instances, each configured with a pool of 30 connections. The theoretical maximum is 1,200 connections before accounting for migrations, background jobs, or administrative access. If the database is comfortable with substantially fewer active sessions, that configuration can turn a traffic increase into contention rather than throughput. The arithmetic should include every process that connects, not just the web tier.

Pool sizing depends on database capacity, request concurrency, transaction duration, and deployment topology. A pooler such as PgBouncer can reduce the number of database server connections, but transaction pooling changes connection semantics: session-level state and features that assume a stable server connection may not behave as expected. Verify prepared statements, temporary tables, and session settings against the selected pooling mode. Pooling is an architectural boundary, not a transparent switch.

Put freshness into the design contract

“Eventually consistent” is too broad to guide an implementation. State an explicit freshness requirement for each read path: how stale may the result be, what happens after a write, and which operations require read-your-writes behavior? A 60-second TTL might be sound for a public catalog description and unacceptable for an account balance used to authorize a transfer.

Freshness has both a time dimension and a correctness dimension. A balance that is 200 milliseconds old may be unacceptable for a funds check even if the same delay is invisible in a profile page. Conversely, a daily aggregate may remain useful even if its source has changed several minutes earlier. The domain determines whether stale data is merely cosmetic, operationally disruptive, or financially and legally consequential.

Document the source of truth, cache key, write and invalidation path, maximum expected staleness, and fallback behavior. Include what happens when the cache is unavailable. Falling back to the database can preserve functionality, but only if the database can absorb the resulting traffic. Otherwise, use admission control, a degraded response, or a circuit breaker with deliberate behavior rather than allowing every request to overwhelm the origin.

Do not confuse a longer TTL with resilience. A longer TTL can reduce origin load, but it also increases the period during which an invalidation failure remains visible. A short TTL limits stale duration but can create more misses and synchronized expiration. The right value follows from measured change rates, origin capacity, and the freshness contract—not from a universal cache rule.

A measurement loop for choosing the next layer

Use a repeatable sequence rather than adding cache layers in response to one slow dashboard.

  1. Find the expensive segment. Use traces and database statistics to distinguish application work, network time, pool waiting, query execution, and downstream latency.
  2. Confirm the workload. Identify request volume, key distribution, data size, update frequency, and which calls are on the critical path. A highly skewed key distribution behaves differently from uniformly accessed data.
  3. Fix avoidable work first. Correct missing indexes, unnecessary queries, N+1 access patterns, oversized responses, and long-held connections before masking them with a cache.
  4. Choose the smallest suitable intervention. Use cache-aside for selective hot reads, write-through when immediate cache visibility matters, a materialized view for expensive derived data, a replica for read capacity, or pooling to control connection pressure.
  5. Test under realistic conditions. Include cold-cache behavior, concurrent misses, expiration, replica lag, and a cache outage. A warm-cache benchmark alone does not describe production performance.
  6. Compare before and after. Recheck p95 and p99 latency, origin load, pool waits, errors, hit and eviction rates, and freshness behavior. Keep the change only if the measured improvement outweighs the new operational burden.

Load tests should include the shape of traffic, not merely its peak rate. A steady 5,000 requests per second can be easier than a burst of 5,000 requests arriving at once after a cache restart. Test hot-key concentration, large-value serialization, and the moment many entries expire. If a cache outage sends all requests directly to a database that was sized assuming a 95% hit rate, the “fallback” may be a cascading failure.

Operational safeguards for a cache that matters

Cache key design affects correctness and capacity. Include every input that changes the result—such as tenant, locale, permissions, or schema version—without putting sensitive information into observable key names. Normalize equivalent inputs to avoid accidental duplicate entries. Set limits on value size and cardinality, and define an eviction policy based on the workload. A cache that admits unbounded user-generated keys can become a memory-exhaustion mechanism.

Track eviction rate and memory pressure alongside hit rate. A rising eviction rate may mean the working set no longer fits, a key-generation bug is creating too many entries, or a deployment changed the key format and made old entries useless. Cache memory is finite; an entry that displaces a more valuable hot item can reduce the overall hit rate even when it is accessed occasionally.

Plan for cache failures and deployment changes. Use timeouts short enough to prevent a cache call from consuming the request budget, but not so aggressive that routine network variation creates a storm of fallbacks. Consider circuit breaking and load shedding where appropriate. When changing key formats or serialized values, version keys or provide a controlled migration; old and new application versions may run concurrently during a rolling deployment.

Finally, treat observability as part of the implementation. Emit metrics for cache operation latency, errors, hit and miss counts by meaningful operation, and origin fallback volume. Avoid unbounded labels such as raw cache keys, which can overwhelm a metrics system and expose data. Logs and traces should make it possible to connect a slow request to its cache outcome without turning every key into a high-cardinality dimension.

Choose the mechanism that fits the bottleneck

Cache-aside is a strong default for hot reads with tolerable staleness, provided invalidation and stampede behavior are designed. Write-through suits paths where cache visibility after a write is important, at the cost of coupling writes to cache health. Materialized views are effective when computation dominates and refresh lag is acceptable. Read replicas add read capacity but preserve query cost and introduce replication lag. Connection pools manage scarce database connections, but an oversized pool can move the queue from the application into the database.

These mechanisms can coexist, but each should have a distinct job. A service might use a small cache-aside layer for popular product details, a materialized view for a seller dashboard, and a read replica for ordinary catalog queries, while keeping balance reads on the primary. The design is credible only if the team can explain the freshness contract, failure behavior, and measurements for each path.

The useful question is not “Which cache should we add?” It is “Which measured cost are we moving, how much latency or capacity will that save, and what new consistency or operational cost are we accepting?” Answer those questions with traces, query plans, pool statistics, and a workload that includes failure conditions. A cache is an engineering trade, not a performance guarantee.

Theme