Skip to main content

Lesson 8 of 8

Mini Project: Cached Product Catalog API

Build a high-performance Product Catalog API combining all performance patterns: Redis distributed caching with GetOrSetAsync, Serilog structured logging with correlation ID enrichment, Output Cache for public list endpoint, Prometheus metrics for request tracking, and Polly retry for an external pricing API.

40 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Quick Quiz - Logging, Caching & Performance

Complete Performance Stack

Complete Performance Stack
// ━━ CatalogService - layers all performance patterns ━━
public class CatalogService(
    IProductRepository repo,
    DistributedCacheHelper cache,
    ExternalPricingClient pricingClient,
    ILogger<CatalogService> logger)
{
    public async Task<CursorPage<ProductDto>> GetCatalogAsync(
        CatalogQuery query, CancellationToken ct)
    {
        var cacheKey = $"catalog:{query.Category}:{query.Cursor}:{query.Limit}";

        using var timer = CatalogMetrics.TrackCatalogQuery(query.Category ?? "all");

        return await cache.GetOrSetAsync(
            cacheKey,
            async token =>
            {
                logger.LogInformation(
                    "Cache miss for catalog {Category} page - loading from DB", query.Category);

                var products = await repo.GetPagedAsync(query, token);

                // Enrich with real-time pricing from external service
                var enrichedItems = await Task.WhenAll(
                    products.Items.Select(async p =>
                    {
                        try
                        {
                            var price = await pricingClient.GetCurrentPriceAsync(p.Id, token);
                            return p with { Price = price };
                        }
                        catch (Exception ex)
                        {
                            logger.LogWarning(ex, "Failed to get real-time price for {ProductId}", p.Id);
                            return p; // fallback to DB price
                        }
                    }));

                return new CursorPage<ProductDto>(enrichedItems.ToList(), products.NextCursor, products.HasNextPage, query.Limit);
            },
            expiry: TimeSpan.FromMinutes(2), // short expiry - prices change
            ct: ct);
    }
}

// Metrics for catalog
public static class CatalogMetrics
{
    private static readonly Histogram QueryDuration = Prometheus.Metrics
        .CreateHistogram("catalog_query_duration_seconds", "Catalog query duration",
            new Prometheus.HistogramConfiguration { LabelNames = ["category"] });

    public static IDisposable TrackCatalogQuery(string category) =>
        QueryDuration.WithLabels(category).NewTimer();
}

// External pricing client with Polly retry
public class ExternalPricingClient(HttpClient http)
{
    public async Task<decimal> GetCurrentPriceAsync(Guid productId, CancellationToken ct)
    {
        var response = await http.GetAsync($"/prices/{productId}", ct);
        if (!response.IsSuccessStatusCode) throw new HttpRequestException($"Price API: {response.StatusCode}");
        var result = await response.Content.ReadFromJsonAsync<PriceResponse>(cancellationToken: ct);
        return result!.CurrentPrice;
    }
}

record CatalogQuery(string? Category, string? Cursor, int Limit = 20);
record ProductDto(Guid Id, string Name, decimal Price)
{
    public ProductDto with(decimal Price) => new ProductDto(Id, Name, Price);
}
record CursorPage<T>(System.Collections.Generic.List<T> Items, string? NextCursor, bool HasNextPage, int Limit);
record PriceResponse(decimal CurrentPrice);
interface IProductRepository { Task<CursorPage<ProductDto>> GetPagedAsync(CatalogQuery q, CancellationToken ct); }

Tip

Tip

Practice Mini Project Cached Product Catalog API in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Cached Product Catalog API from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Mini Project Cached Product Catalog API is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done