Custom API Caching Guide

TABLE OF CONTENTS


Overview

Caching improves API performance by storing the results of expensive operations, such as database queries or external service calls, in a temporary storage layer. Subsequent requests can retrieve data from the cache instead of repeating the original operation, reducing response times and minimizing system load.

The Znode Custom API SDK provides a unified caching abstraction through ICacheService, built on EasyCaching with support for both InMemory and Redis caching providers. Application code remains unchanged regardless of the selected caching backend. 

Purpose

This article explains how to implement caching in custom APIs built using the .NET 8-based Znode Custom API SDK. It covers cache architecture, backend configuration, cache key design, cache operations, invalidation strategies, error handling, and testing considerations.

Architecture

The caching framework uses a layered architecture. The application interacts only with ICacheService, while EasyCaching manages communication with the configured cache provider.

[Insert Architecture Diagram]

  • ICacheService – Cache abstraction consumed by application services.
  • EasyCaching – Provider abstraction layer.
  • InMemory Cache – Local application cache for development and single-instance deployments.
  • Redis Cache – Distributed cache for production and multi-instance deployments.

The cache provider is selected through configuration without requiring changes to business logic. 

Prerequisites

  • .NET 8 SDK installed.
  • Access to the Custom.Api.Core CacheManager implementation.
  • Redis Server or Azure Cache for Redis when Redis caching is used.
  • Secure storage for Redis credentials, such as environment variables or a key vault.
  • Defined cache expiration requirements for each cached resource.
  • Defined fallback strategy when cache services become unavailable.

Use Cases

Use Case 1: Cache Product and Category Data

Product catalogs and category information are requested frequently and change less often than transactional data. Caching these resources improves API response times and reduces database load. 

Use Case 2: Cache Store Configuration Data

Store settings and domain information change infrequently and are suitable candidates for longer cache durations. 

Use Case 3: Cache Inventory and Price Display Data

Inventory and pricing displayed on the Storefront can be cached for short periods. Inventory validation and pricing decisions at checkout must always retrieve live values from Znode. 

Caching Guidelines

Data TypeRecommendedSuggested Expiration
Domain ListsYesUp to 24 hours
Store SettingsYes6–24 hours
Product CatalogYes30–60 minutes
Category DataYes30–60 minutes
Display InventoryYes30–120 seconds
Display PricingYes1–5 minutes
Shopping Cart DataNoNot Recommended
Checkout PricingNoAlways Live
Checkout Inventory ValidationNoAlways Live

Configure Caching

Configure InMemory Caching

  1. Open the appsettings.json file.
  2. Locate the Caching section.
  3. Configure the cache type as InMemory.
  4. Save the configuration file.
{
  "Caching": {
    "CacheType": "InMemory",
    "RedisCacheConnectionString": "",
    "CacheExpirationMinutes": 60
  }
}

InMemory cache stores data within the application process and automatically clears all entries when the application restarts. 

Configure Redis Caching

  1. Open the appsettings.json file.
  2. Locate the Caching section.
  3. Set the cache type to Redis.
  4. Specify a secure Redis connection string.
  5. Save the configuration file.
{
  "Caching": {
    "CacheType": "Redis",
    "RedisCacheConnectionString": "<environment variable or key vault value>",
    "CacheExpirationMinutes": 60
  }
}

Redis supports distributed caching across multiple application instances and retains cache entries after application restarts. 

Redis Best Practices

  • Store connection strings outside source control.
  • Use abortConnect=False.
  • Enable TLS for external Redis deployments.
  • Restrict Redis access through firewall rules.
  • Use separate credentials for each environment.

Inject ICacheService

  1. Open the service implementation.
  2. Add ICacheService as a constructor parameter.
  3. Assign the dependency to a private field.
public class MyProductService : IMyProductService
{
    private readonly ICacheService _cacheService;

    public MyProductService(ICacheService cacheService)
    {
        _cacheService = cacheService;
    }
}

The dependency injection framework automatically supplies the cache service because it is registered during application startup. 

Read Data from Cache

  1. Generate a cache key.
  2. Call GetCacheData<T>().
  3. Validate whether the result exists.
  4. Retrieve data from the source when the cache key is not found.
var products = _cacheService.GetCacheData<List<ProductModel>>(key);

if (products != null)
{
    return products;
}

Handle Cache Misses

var count = _cacheService.GetCacheData<int?>(key);

if (count == null)
{
    // cache miss
}

Use nullable value types when determining whether a cache entry exists. 

Store Data in Cache

  1. Retrieve data from the primary source.
  2. Validate the response.
  3. Call SetCacheData().
  4. Specify an expiration period.
_cacheService.SetCacheData(
    productKey,
    products,
    TimeSpan.FromMinutes(60));

Validate Data Before Caching

if (products != null && products.Count > 0)
{
    _cacheService.SetCacheData(
        productKey,
        products,
        TimeSpan.FromMinutes(60));
}

Avoid caching null objects and invalid results. 

Remove Cached Data

  1. Identify the affected cache key.
  2. Call DeleteCacheKey().
  3. Invalidate related cache entries when applicable.
_cacheService.DeleteCacheKey(
    keys.ProductById(1042));

_cacheService.DeleteCacheKey(
    keys.ProductList());

Cache invalidation should occur after create, update, and delete operations. 

Build Effective Cache Keys

Every cache key should uniquely identify a specific dataset and include all parameters that can change the response. 

{environment}:{store}:{locale}:{entity}:{scope}:{identifier}:{details}

Example

prod:portal5:en-us:product:id:1042

Pricing Example

prod:portal5:en-us:
price:sku:AB-100:
profile:12:
account:340:
currency:usd:
qty:5

Best Practices

  • Use lowercase values.
  • Include environment identifiers.
  • Include locale and store details.
  • Include all pricing and inventory variables.
  • Use internal IDs instead of personal information.
  • Never use email addresses in cache keys.

Handle Cache Failures

Caching is an optimization layer and should never become a dependency that prevents successful request processing. 

  1. Wrap cache operations in try/catch blocks.
  2. Log exceptions.
  3. Retrieve data from the primary source when cache operations fail.
  4. Return valid responses even when the cache provider is unavailable.
try
{
    var cached = _cacheService.GetCacheData<T>(key);

    if (cached != null)
        return cached;
}
catch(Exception ex)
{
    _znodeLogging.LogMessage(
        ex.Message,
        "CacheLog",
        TraceLevel.Warning);
}

Cache Invalidation Strategies

Expiration-Based Invalidation

Cache entries automatically expire after the configured TimeSpan period. This mechanism helps prevent stale data when updates occur outside custom APIs. 

Event-Based Invalidation

Invalidate cache entries immediately after successful create, update, or delete operations. 

TryDelete(keys.ProductById(productId));
TryDelete(keys.ProductList());

Generation-Based Invalidation (Recommended)

Generation-based cache keys provide a scalable mechanism for invalidating cache groups. 

int gen =
    _cacheService.GetCacheData<int?>(
        "prod:gen:product:portal5") ?? 1;

string key =
    $"prod:portal5:en-us:g{gen}:product:list";

To invalidate all entries within the group:

_cacheService.SetCacheData(
    "prod:gen:product:portal5",
    gen + 1,
    TimeSpan.FromDays(30));

Generation-based invalidation is recommended over Redis key pattern scanning because it is more efficient and consistent across deployments. 

Testing Cache Implementation

  1. Verify cache hit and miss behavior.
  2. Validate Redis keys and expiration values.
  3. Confirm cache invalidation after updates.
  4. Confirm generation-based invalidation.
  5. Verify expiration behavior.
  6. Verify restart behavior.
  7. Verify multi-instance synchronization.
  8. Validate behavior when data changes in Znode.
  9. Confirm checkout operations never use cached inventory or pricing.
  10. Verify fallback behavior during Redis outages.

Troubleshooting

IssueRecommendation
Cache Always MissesVerify identical key generation during read and write operations.
Redis Connection FailureVerify host, port, TLS configuration, credentials, and firewall access.
Requests Fail When Redis Is UnavailableVerify try/catch handling around cache operations.
Stale Data AppearsValidate invalidation and expiration strategies.
Different Data Across ServersUse Redis instead of InMemory caching.
Incorrect Customer PricingInclude all pricing variables in cache keys.

Best Practices

  • Use Redis in multi-instance environments.
  • Log cache hits, misses, and failures.
  • Use centralized cache key generation.
  • Define expiration periods explicitly.
  • Use generation-based invalidation for grouped cache entries.
  • Include environment identifiers in cache keys.
  • Never cache checkout inventory validation.
  • Never cache transactional pricing decisions.
  • Never store personal information in cache keys.
  • ICacheService
  • CacheService
  • RegisterStartupServices
  • CustomDependencyRegistration
  • EasyCaching
  • StackExchange.Redis

The Znode Custom API SDK provides a flexible caching framework that enables developers to improve performance while maintaining a consistent implementation model across InMemory and Redis deployments. 

Did you find it helpful? Yes No

Send feedback
Sorry we couldn't be helpful. Help us improve this article with your feedback.