Tuesday, 21 October 2025

ASP.NET Core Web API Real-Time Cache Monitoring and Alerting Using NCache

Leave a Comment

Caching is essential for enhancing responsiveness and scalability in high-performance enterprise applications. Dispersed caching relieves database strain and increases throughput while handling heavy transaction loads or frequent data access. However, real-time monitoring and alerts become essential for stability and performance visibility when your cache expands and supports more APIs or microservices.



NCache, a potent open-source distributed cache for.NET, can help with it. In addition to speeding up your apps, it offers dashboards, real-time monitoring, and performance and cache health notifications.

We will create an ASP.NET Core Web API that is integrated with NCache and set up real-time cache monitoring and alerting in this post.

What is NCache?

NCache is a 100% native .NET distributed caching solution by Alachisoft. It provides:

  • High availability through replication and partitioning

  • In-memory data storage for low latency

  • Real-time monitoring and management

  • Built-in notifications and alerts

It’s widely used in .NET Core microservices, Web APIs, SignalR, and Azure/AWS deployments.

Why Monitor Cache in Real-Time?

Real-time cache monitoring helps you:

  • Detect cache node failures or disconnections immediately

  • Track hit/miss ratios to optimize caching logic

  • Identify memory pressure or expired items

  • Receive alerts before performance degradation impacts users

Setting Up the ASP.NET Core Web API

Let’s create a new ASP.NET Core project and integrate NCache.

Step 1. Create the Project
dotnet new webapi -n NCacheMonitoringDemo
cd NCacheMonitoringDemo
Step 2. Add Required Packages

Install the following NuGet packages:

dotnet add package Alachisoft.NCache.SDK
dotnet add package Alachisoft.NCache.SessionState
dotnet add package Alachisoft.NCache.Runtime
Step 3. Configure NCache in Program.cs

Here’s how you configure NCache in your .NET 8 Web API:

using Alachisoft.NCache.Client;
using Alachisoft.NCache.Runtime.Caching;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();

// Configure NCache
builder.Services.AddSingleton<ICache>(provider =>
{
    string cacheName = "demoClusteredCache";
    var cache = CacheManager.GetCache(cacheName);
    return cache;
});

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

This connects your API to a clustered cache named demoClusteredCache running on your NCache server(s).

Step 4. Using the Cache in Your Controller

Let’s create a simple way ProductController to interact with NCache.

using Microsoft.AspNetCore.Mvc;
using Alachisoft.NCache.Client;
using Alachisoft.NCache.Runtime.Caching;

namespace NCacheMonitoringDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly ICache _cache;

        public ProductController(ICache cache)
        {
            _cache = cache;
        }

        [HttpPost]
        public IActionResult AddProduct([FromBody] Product product)
        {
            _cache.Insert(product.Id.ToString(), product);
            return Ok("Product cached successfully!");
        }

        [HttpGet("{id}")]
        public IActionResult GetProduct(string id)
        {
            var product = _cache.Get<Product>(id);
            if (product == null)
                return NotFound("Product not found in cache!");

            return Ok(product);
        }
    }

    public record Product(string Id, string Name, decimal Price);
}

Now, whenever you call POST /api/product, your data gets cached in NCache, and can be retrieved with GET /api/product/{id}.

Step 5. Enabling Real-Time Cache Monitoring

NCache provides a web-based monitoring dashboard called NCache Web Manager, as well as a PowerShell-based monitoring tool.

Option 1: Use NCache Web Manager

  • Launch NCache Web Manager (usually at http://localhost:8251).

  • Navigate to Monitoring > Clustered Cache.

  • Select your cache (e.g., demoClusteredCache).

  • You’ll see live graphs for:

    • Cache Size

    • Requests per second

    • Cache Hits vs Misses

    • Client Connections

    • Server Health

Step 6. Configure Alerts and Notifications

You can configure email, SMS, or webhook-based alerts for cache events such as:

  • Server node down

  • Cache full or eviction started

  • High CPU/Memory usage

  • Client disconnection

Example PowerShell command to add an alert:

Add-Alert -CacheName demoClusteredCache `
  -EventType "NodeStopped" `
  -Action "Email" `
  -Recipients "[email protected]"
PowerShell

Or configure it through NCache Manager UI → Alerts → Add New Alert.

Step 7. Programmatic Event Notifications

NCache also supports runtime event subscriptions from your .NET code.

Example: Receive notification when a cache item is removed or updated.

_cache.MessagingService.RegisterCacheNotification("product-101",
    (key, eventType) =>
    {
        Console.WriteLine($"Cache key '{key}' was {eventType}");
    },
    EventType.ItemRemoved | EventType.ItemUpdated);

This is especially useful for synchronizing distributed APIs or invalidating dependent data in real-time.

Step 8. Visualizing Metrics in Grafana or Prometheus (Optional)

In order to integrate with observability technologies such as Prometheus, Grafana, or Azure Monitor, NCache provides a metrics API.  To see trends in cache health, simply connect your monitoring platform and enable metrics in your NCache setup.

 

Best Practices for Cache Monitoring
AreaRecommendation
Cache SizeAlways monitor memory growth and eviction count
Hit RatioMaintain 85–90% hit rate for efficiency
AlertsSet threshold-based alerts for CPU, memory, and node status
FailoverAlways run at least two cache servers for high availability
SecurityRestrict monitoring access using NCache roles

Conclusion
You can get enterprise-grade monitoring and alerting in addition to a high-performance caching layer by integrating NCache with your ASP.NET Core Web API. Improved user experience, seamless scaling, and preemptive problem identification are all made possible by real-time cache health awareness.

With minimal configuration, you can:

  1. Cache data in-memory for faster access

  2. Track live performance metrics

  3. Get alerts before downtime occurs

  4. Keep your distributed systems stable and predictable

ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFE guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

0 comments:

Post a Comment