LESSON 12 OF 12

12. Performance Measurement, Observability, and a Production-Ready Cache Strategy

Learn how to measure cache performance, establish Redis and ASP.NET Core observability, and build a sustainable production caching strategy.

90 dk 81

Introduction

In this final lesson, we will make the cache service built in the previous lessons measurable and operationally useful. A cache strategy is not simply a matter of writing data to Redis or calling GetAsync. A production application must continuously answer questions such as: What is the cache hit ratio? How many database queries occur on a miss? How long do Redis commands take? How are p50, p95, and p99 request durations changing? Is memory usage or eviction increasing? What happens when Redis is unavailable?

We will answer these questions through three observability layers: application logs, application metrics, and dependency health checks. We will then compare no cache, in-memory cache, and Redis-based approaches with a controlled benchmark. Finally, we will create a practical cache decision matrix and a production-readiness checklist for the completed project.

1. Core indicators to measure

A single number cannot describe cache performance. At minimum, the following indicators should be observed together.

IndicatorDescriptionInterpretation
Hit ratioThe proportion of reads successfully served by the cacheA higher value is usually positive, but caching incorrect or unnecessary data is not a success.
Miss ratioThe proportion of reads not found or not usable in the cacheA high value may indicate problems with TTL, key design, invalidation, or the access flow.
LatencyThe duration of an HTTP request, cache operation, or Redis commandMeasure p95 and p99 in addition to the average.
ThroughputRequests, cache reads, or Redis commands per secondHelps determine system capacity under load.
SQL query countThe number of SQL commands executed during an HTTP requestA cache hit should normally avoid the expensive database query.
Memory usageApplication and Redis memory consumptionReveals oversized payloads, unbounded key creation, and eviction risk.

The basic hit-ratio formula is hits / (hits + misses). Dimensions such as endpoint, cache name, or tenant can be useful, but avoid unbounded labels such as user IDs or complete cache keys because they create high metric cardinality.

2. Adding logs and metrics to the cache service

The cache abstraction should not expose Redis details to the rest of the application, but every read and write still needs to be measurable. The .NET System.Diagnostics.Metrics API supports instruments such as Counters and Histograms.

using System.Diagnostics.Metrics;

public sealed class CacheMetrics
{
    public static readonly Meter Meter = new("Catalog.Cache", "1.0.0");

    public Counter<long> Hits { get; } =
        Meter.CreateCounter<long>("cache_hits_total");

    public Counter<long> Misses { get; } =
        Meter.CreateCounter<long>("cache_misses_total");

    public Histogram<double> OperationDuration { get; } =
        Meter.CreateHistogram<double>("cache_operation_duration_ms", "ms");

    public Counter<long> Failures { get; } =
        Meter.CreateCounter<long>("cache_failures_total");
}

Inside the cache service, start a stopwatch for each operation, increment the hit or miss counter, and record the duration in the histogram. A simplified read flow looks like this:

public async Task<ProductDto?> GetAsync(
    string key,
    CancellationToken cancellationToken = default)
{
    var stopwatch = Stopwatch.StartNew();

    try
    {
        var value = await _distributedCache.GetStringAsync(key, cancellationToken);

        if (value is null)
        {
            _metrics.Misses.Add(1, new KeyValuePair<string, object?>("cache", "products"));
            return null;
        }

        _metrics.Hits.Add(1, new KeyValuePair<string, object?>("cache", "products"));
        return JsonSerializer.Deserialize<ProductDto>(value);
    }
    catch (Exception exception)
    {
        _metrics.Failures.Add(1);
        _logger.LogWarning(exception, "Cache read failed for {CacheKey}", key);
        return null;
    }
    finally
    {
        _metrics.OperationDuration.Record(stopwatch.Elapsed.TotalMilliseconds);
    }
}

Writing complete cache keys to production logs is often a poor choice. A key can contain tenant identifiers, user information, or sensitive business data. Prefer the cache area, operation type, result status, and, if necessary, a safe hash of the key. Logging the entire payload on every request increases cost and may expose personal data.

3. Measuring HTTP and SQL behavior

To prove that caching helps, measure the complete HTTP request rather than only the cache layer. ASP.NET Core provides built-in HTTP metrics, while the application can expose business-specific measurements. For example, the catalog endpoint can track whether the result came from Redis or the database.

public sealed class CatalogMetrics
{
    private readonly Meter _meter = new("Catalog.Api", "1.0.0");

    public Counter<long> DatabaseFallbacks =>
        _meter.CreateCounter<long>("catalog_database_fallbacks_total");

    public Histogram<double> SqlQueryDuration =>
        _meter.CreateHistogram<double>("catalog_sql_duration_ms", "ms");
}

For tests and benchmarks, an EF Core command interceptor can count SQL commands. In production, logging every SQL statement in detail is usually too expensive. Prefer aggregate values such as query duration, endpoint, and query count. When a cache hit is served, the expected behavior is that the database command count falls to zero or to only the queries that are genuinely required.

4. Inspecting Redis outside the application

Redis's INFO command exposes sections for memory, clients, statistics, command counters, and latency percentiles. During development or controlled operations, use commands such as:

redis-cli INFO stats
redis-cli INFO memory
redis-cli INFO commandstats
redis-cli INFO latencystats
redis-cli SLOWLOG GET 20

The INFO stats section shows the general Redis-level picture. Redis keyspace hits and misses are not identical to application cache hits and misses. The application may reject a value because of a serialization error, timeout, type mismatch, or fallback policy even though Redis successfully returned a key.

Redis latency monitoring may be disabled by default. Configure a threshold based on the application's service-level objective:

CONFIG SET latency-monitor-threshold 100
LATENCY LATEST
LATENCY DOCTOR

Do not run KEYS * in production to inspect large key spaces. Use SCAN instead. The KEYS command can block Redis's main thread on large datasets and increase latency for all clients. Large collections, oversized values, and unnecessary O(N) commands should also be investigated.

5. Monitoring dependency health

Health checks serve two different purposes. Liveness indicates that the process can continue running; readiness indicates that the application is prepared to receive traffic. If Redis is an optional cache, a Redis outage may be represented as degraded rather than making the entire application unhealthy. If Redis stores sessions or provides a required distributed lock, readiness may need to be stricter.

builder.Services.AddHealthChecks()
    .AddRedis(
        builder.Configuration.GetConnectionString("Redis")!,
        name: "redis",
        tags: new[] { "ready" });

var app = builder.Build();

app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = _ => false
});

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready")
});

Health endpoints are called frequently and can generate noisy informational logs. Separate liveness and readiness, filter health-check categories, and protect the endpoints through appropriate authentication, rate limiting, and network access controls. A successful health check does not prove that real user traffic is correct; it only provides a signal about selected dependencies.

6. Designing a benchmark

When comparing cache strategies, use the same dataset, payload size, and concurrency level. Prepare at least three scenarios:

  1. No cache: Every request reads directly from SQL.
  2. In-memory cache: Reads are served from the memory of one application instance.
  3. Redis cache: Multiple application instances share the cache.

Include a warm-up phase. Initial requests may be slower because of connection pools, JIT compilation, EF model creation, or Redis connection setup. After warm-up, generate a stable request rate for a fixed period. Record average, p50, p95, p99, error rate, throughput, and database query count.

A simple test plan might be:

Scenario: GET /api/products
Concurrency: 20, 50, 100
Duration: 60 seconds per run
Payload: 50 product records
Runs: 3 repetitions
Metrics: p50, p95, p99, requests/sec, SQL count, cache hit ratio

Do not treat a benchmark as an absolute truth. Redis on a developer laptop will not produce the same result as Redis reached through a production network. Network latency, TLS, serialization format, payload size, connection multiplexer configuration, and database indexes all affect the outcome.

7. A cache decision matrix

Instead of caching every object, make the decision based on data characteristics.

Data characteristicRecommended approachReason
Frequently read, rarely changed catalog dataRedis or, where appropriate, in-memory cacheHigh hit ratio and manageable invalidation cost are likely.
Short-lived user-specific dataRedis key scoped by tenant or userSharing across instances is required; keep the TTL short.
Financial data requiring immediate accuracyNo cache or only a very short-lived helper cacheStale data can create business risk.
Large, rarely accessed payloadExclude it or cache a smaller projectionMemory and serialization cost may exceed the benefit.
Local computation result on one serverIMemoryCacheLowest latency, but no sharing or restart durability.

Ask five questions before adding a cache: How frequently is the data read? How often does it change? Is stale data acceptable? How many application instances are running? Is there a safe fallback when the cache is unavailable? If the answers are unclear, measure the data-access path first instead of adding caching by assumption.

8. Common production failures

  • Treating hit ratio as the only success criterion: Returning incorrect data quickly is not a performance success.
  • Using Redis as the system of record: Keeping durable business data only in a cache can cause data loss.
  • Unbounded TTLs and key creation: Memory grows, eviction begins, and operational cost increases.
  • Disabling cache on every error: A short network issue can suddenly overload the database. Timeouts, retries, and fallbacks must be controlled.
  • Ignoring payload size: Many small keys and a few large payloads create very different memory and latency behavior.
  • Misreading health checks: A successful Redis ping does not prove that serialization, invalidation, or application logic works.
  • Logging complete keys and values: This creates privacy, cost, and log-cardinality problems.

9. Short practice exercise

Complete the following exercise for the final application's GET /api/products endpoint:

  1. Add counters for cache hits, misses, and failures.
  2. Create a histogram for cache operation duration.
  3. Measure endpoint p95 duration and database fallback count.
  4. Add a Redis readiness health check.
  5. Inspect INFO memory, INFO commandstats, and SLOWLOG GET 20.
  6. Run two tests with 20 concurrent clients: one with caching disabled and one with caching enabled.
  7. Record the results in a table and explain which strategy you selected and why.

The expected result is a reduction in SQL query count and average latency when the cache is enabled. However, if Redis is remote or the payload is unnecessarily large, p95 may be worse than expected. In that case, measure serialization, network latency, and key or payload design separately.

Conclusion

A production-ready cache strategy means choosing the correct cache type, applying consistent key and invalidation rules, providing a safe fallback, and measuring all of these behaviors. Hit ratio alone is not enough. Application latency, p95 and p99 values, Redis command duration, SQL query count, throughput, error rate, and memory usage must be evaluated together.

Throughout this course, we progressed from in-memory caching to distributed caching, Redis integration, cache-aside flows, expiration, invalidation, stale data, and cache stampede protection. When you finish with measurable objectives, meaningful alerts, controlled benchmarks, and an explicit decision matrix, caching stops being a randomly added optimization and becomes a sustainable part of the application's performance architecture.

Sources