TABLE OF CONTENTS
- Overview
- Purpose
- Architecture
- Prerequisites
- Use Cases
- Caching Guidelines
- Configure Caching
- Inject ICacheService
- Read Data from Cache
- Store Data in Cache
- Remove Cached Data
- Build Effective Cache Keys
- Handle Cache Failures
- Cache Invalidation Strategies
- Testing Cache Implementation
- Troubleshooting
- Best Practices
- Related Components
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 Type | Recommended | Suggested Expiration |
|---|---|---|
| Domain Lists | Yes | Up to 24 hours |
| Store Settings | Yes | 6–24 hours |
| Product Catalog | Yes | 30–60 minutes |
| Category Data | Yes | 30–60 minutes |
| Display Inventory | Yes | 30–120 seconds |
| Display Pricing | Yes | 1–5 minutes |
| Shopping Cart Data | No | Not Recommended |
| Checkout Pricing | No | Always Live |
| Checkout Inventory Validation | No | Always Live |
Configure Caching
Configure InMemory Caching
- Open the
appsettings.jsonfile. - Locate the
Cachingsection. - Configure the cache type as
InMemory. - 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
- Open the
appsettings.jsonfile. - Locate the
Cachingsection. - Set the cache type to
Redis. - Specify a secure Redis connection string.
- 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
- Open the service implementation.
- Add
ICacheServiceas a constructor parameter. - 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
- Generate a cache key.
- Call
GetCacheData<T>(). - Validate whether the result exists.
- 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
- Retrieve data from the primary source.
- Validate the response.
- Call
SetCacheData(). - 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
- Identify the affected cache key.
- Call
DeleteCacheKey(). - 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.
Recommended Format
{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.
- Wrap cache operations in try/catch blocks.
- Log exceptions.
- Retrieve data from the primary source when cache operations fail.
- 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
- Verify cache hit and miss behavior.
- Validate Redis keys and expiration values.
- Confirm cache invalidation after updates.
- Confirm generation-based invalidation.
- Verify expiration behavior.
- Verify restart behavior.
- Verify multi-instance synchronization.
- Validate behavior when data changes in Znode.
- Confirm checkout operations never use cached inventory or pricing.
- Verify fallback behavior during Redis outages.
Troubleshooting
| Issue | Recommendation |
|---|---|
| Cache Always Misses | Verify identical key generation during read and write operations. |
| Redis Connection Failure | Verify host, port, TLS configuration, credentials, and firewall access. |
| Requests Fail When Redis Is Unavailable | Verify try/catch handling around cache operations. |
| Stale Data Appears | Validate invalidation and expiration strategies. |
| Different Data Across Servers | Use Redis instead of InMemory caching. |
| Incorrect Customer Pricing | Include 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.
Related Components
- 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.