Cookie Consent by Free Privacy Policy Generator ASP.NET Core Cache - An Overview - NCache

ASP.NET Core Cache - An Overview

Modern web applications require fast performance and scalability. As applications grow, frequent database queries can slow things down, leading to performance bottlenecks and reduced responsiveness.

ASP.NET Core is a powerful framework for building scalable web applications, but it performs well when combined with a distributed caching solution like NCache. Caching frequently accessed data reduces database load, increases the response time, and improves scalability.

Let's discuss the benefits of distributed caching, its real-world use cases, and how to integrate NCache with ASP.NET Core applications.

 

What is Distributed Caching in ASP.NET Core?

Distributed caching stores frequently used data across multiple servers, making a scalable and reliable in-memory data store. This helps reduce latency, minimizes database queries, and improves application responsiveness. NCache delivers sub-millisecond response times and has been benchmarked to handle over 2 million requests per second in a clustered environment.

Feature Technical & Business Benefit
Improved Performance Achieves sub-millisecond response times by caching data in-memory, drastically reducing expensive database trips and network latency.
Linear Scalability Handles growing transaction loads by adding more server nodes to the cluster at runtime, ensuring consistent performance for any number of users.
High Availability Utilizes a self-healing, peer-to-peer dynamic cluster to ensure 100% uptime and no single point of failure, even during server maintenance or crashes.
Data Reliability Maintains data integrity via multi-node replication topologies and keeps the cache synchronized with the backend via Database Dependency.
 

Setting Up NCache for ASP.NET Core

Follow these steps to install and configure NCache for your ASP.NET Core application.

Step 1: Install NCache

Installing NCache Server

Install NCache Server on two servers from the official website.

Installing NCache Client SDK

To connect an ASP.NET Core application to the cache server, install the NCache Client SDK using NuGet:

Install-Package Alachisoft.NCache.SDK

Ensure your network and firewall settings allow communication between your application and the cache server.

Step 2: Creating a Clustered Cache

A clustered cache improves scalability and ensures high availability by distributing cached data across multiple servers.

  1. Verify Network Connectivity - Ensure cache nodes can communicate over the designated network ports.
  2. Configure NCache - Use NCache Management Center or PowerShell to create a clustered cache instance.
  3. Add Cache Nodes - Add multiple servers to improve performance and reliability.
  4. Monitor Cache Health - Track synchronization and node availability through NCache's monitoring tools.

Step 3: Installing & Configuring the .NET Client

After setting up NCache, configure your ASP.NET Core application to connect to the cache.

Program.cs (Modify)

using Alachisoft.NCache.Client;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ICache>(_ => CacheManager.GetCache("demoCache"));

var app = builder.Build();
app.Run();
 

Using NCache in ASP.NET Core

1. Retrieving Data from the Cache

This method retrieves multiple products from the cache using their product IDs in bulk, reducing the number of calls to the cache server.

public Dictionary<string, Product> RetrieveProducts(List<int> productIds)
{
    List<string> cacheKeys = productIds.Select(id => $"Product:{id}").ToList();
    Dictionary<string, Product> cachedProducts = _cache.GetBulk<Product>(cacheKeys);
    return cachedProducts;
}

2. Adding Data to the Cache

This method attempts to fetch a product from the cache; if it does not exist, it fetches it from the database and adds it to the cache with an expiration time.

public Product GetProduct(int productId)
{
    string cacheKey = $"Product:{productId}";
    Product product = _cache.Get<Product>(cacheKey);

    if (product == null)
    {
        product = FetchProductFromDB(productId);
        var cacheItem = new CacheItem(product)
        {
            Expiration = new Expiration(ExpirationType.Absolute, TimeSpan.FromMinutes(10))
        };
        _cache.Add(cacheKey, cacheItem);
    }
    
    return product;
}

3. Updating/Inserting Data in the Cache

This method updates the product in the database first and then inserts or updates the cached product with a specified expiration.

public void UpdateProduct(int productId, Product updatedProduct)
{
    // Update the database first
    UpdateProductInDB(productId, updatedProduct);
    
    // Update the cache after successful database update
    string cacheKey = $"Product:{productId}";
    var cacheItem = new CacheItem(updatedProduct)
    {
        Expiration = new Expiration(ExpirationType.Absolute, TimeSpan.FromMinutes(10))
    };
    _cache.Insert(cacheKey, cacheItem);
}

4. Removing Cached Data

This method removes multiple entries from the cache at once using their cache keys.

public void RemoveData(List<string> keys)
{
    _cache.RemoveBulk(keys);
}
 

What are the Advanced Features of NCache?

NCache offers additional enterprise-level caching features to enhance performance:

 

Get Started with NCache Today!

Optimize your ASP.NET Core applications with NCache! Reduce database load, enhance performance, and scale effortlessly.

Frequently Asked Questions (FAQ)

NCache improves performance by storing frequently accessed data in a distributed in-memory cache. This drastically reduces database load and network latency, allowing for sub-millisecond response times compared to traditional database retrieval.

Unlike InProc caching, which is limited to a single server, NCache provides a distributed architecture that shares data across the entire web farm. This eliminates the single point of failure and allows for linear scalability as application traffic grows.

Yes. NCache provides a high-performance Distributed Session State Provider for ASP.NET. It ensures that session data remains available and consistent across all server nodes, providing high availability even if a web server goes down.

NCache includes enterprise-level features such as SQL-like searching, Pub/Sub messaging for event coordination, and Database Dependency to ensure the cache is always synchronized with your back-end data source.

© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.