ASP.NET Core  

Real-Time Cache Monitoring and Alerting with NCache in .NET

Introduction

In modern distributed applications, in-memory distributed caching plays a vital role in ensuring high performance, scalability, and fault tolerance. One of the most widely used .NET caching solutions is NCache, a 100% native .NET distributed caching platform.

While caching improves application speed and reduces database load, managing the health and performance of the cache in real time is equally important. If your cache nodes go down, memory consumption spikes, or throughput drops, your application may face bottlenecks. That’s where real-time cache monitoring and alerting comes in.

In this article, we’ll explore:

  • Why real-time cache monitoring is critical.

  • How NCache provides monitoring and alerting features.

  • Practical examples of configuring alerts.

  • A C# example of subscribing to cache events for custom monitoring.

By the end, you will be able to integrate monitoring and alerting into your projects using NCache.

Why Real-Time Monitoring and Alerting?

Imagine you are running an e-commerce application. Your shopping cart and session data are stored in NCache. If a cache node suddenly crashes or memory utilization spikes:

  • Customers might lose their sessions.

  • Database traffic will suddenly increase.

  • End-user experience will be negatively impacted.

Proactive monitoring and alerting helps you:

  • Detect failures instantly.

  • Trigger automated recovery actions.

  • Optimize cache configurations based on load.

  • Ensure high availability and performance.

Monitoring in NCache

NCache provides several built-in tools and APIs for monitoring cache clusters:

  1. NCache Manager (GUI): Visual dashboard to monitor cluster health, client connections, throughput, memory usage, etc.

  2. PerfMon Counters: Integration with Windows Performance Monitor for detailed metrics.

  3. Command-Line Tools: NCache PowerShell and CLI utilities for scripting.

  4. NCache Alerts & Notifications: Subscribe to cache events (node join/leave, cache start/stop, item eviction, etc.).

Practical Scenario: Real-Time Alerts

Let’s say you want to be notified if:

  • A cache node leaves the cluster.

  • A cache goes down.

  • Cache size exceeds a threshold (memory pressure).

We’ll use NC ache's event notification system to implement this.

Step 1. Enable Notifications in NCache

The very first step in building a real-time monitoring and alerting system with NCache is to enable event notifications at the cache level. By default, NCache allows you to configure whether a cache should broadcast certain events (like when nodes join or leave, cache stops, or items are added/removed). This setting can be controlled through NCache Manager, which is the GUI tool that comes with NCache. To enable it, simply open NCache Manager, right-click on the cache you want to monitor, and select Properties. Within the properties window, navigate to the Advanced Options or Notifications section (depending on your version of NCache). There, you’ll find options to enable event notifications. Once enabled, any client connected to this cache will be able to subscribe to those events programmatically. This step is crucial because if notifications are not enabled at the cache configuration level, your application will never receive real-time alerts, regardless of how much code you write. Think of this as turning on the “push notifications” switch for your distributed cache cluster.

  • Right-click on the cache → Properties → Enable event notifications.

Step 2. Subscribe to Cache Events in C#

After enabling notifications, the next step is writing C# code that subscribes to those cache events. This is where the Alachisoft.NCache.Client library comes into play. Using the CacheManager.GetCache() method, you establish a connection between your application and the distributed cache. Once connected, you can hook into various event handlers like CacheCleared, CacheStopped, ItemAdded, ItemRemoved, MemberJoined, and MemberLeft. Each of these events corresponds to real-world scenarios: for example, CacheStopped might indicate that the cache cluster is unavailable (critical alert), while MemberLeft could mean a server node unexpectedly went down. Subscribing to these events is as simple as attaching a method to them, much like how you’d subscribe to button click events in a WinForms or WPF application. This step transforms your application into a real-time monitoring agent because it will immediately know when important changes occur in the cache cluster. Developers often log these events to the console while testing, but in production, you would redirect them to log files, dashboards, or alerting systems.

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

namespace NCacheMonitoringDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Connect to the cache
            string cacheName = "demoClusteredCache";
            var cache = CacheManager.GetCache(cacheName);

            Console.WriteLine("Connected to cache: " + cacheName);

            // Subscribe to cache-level events
            cache.CacheCleared += OnCacheCleared;
            cache.ItemAdded += OnItemAdded;
            cache.ItemRemoved += OnItemRemoved;

            // Subscribe to cluster-level events
            cache.CacheStopped += OnCacheStopped;
            cache.MemberJoined += OnMemberJoined;
            cache.MemberLeft += OnMemberLeft;

            Console.WriteLine("Listening for real-time cache alerts...");
            Console.ReadLine(); // Keep running
        }

        private static void OnCacheCleared(object sender, EventArgs e)
        {
            Console.WriteLine("[ALERT] Cache cleared at: " + DateTime.Now);
        }

        private static void OnItemAdded(object sender, CacheItemEventArgs e)
        {
            Console.WriteLine($"[INFO] Item added: {e.Key}");
        }

        private static void OnItemRemoved(object sender, CacheItemRemovedEventArgs e)
        {
            Console.WriteLine($"[INFO] Item removed: {e.Key}, Reason: {e.Reason}");
        }

        private static void OnCacheStopped(object sender, EventArgs e)
        {
            Console.WriteLine("[CRITICAL ALERT] Cache has stopped!");
            // Here you can send email/SMS/Teams alert
        }

        private static void OnMemberJoined(object sender, NodeJoinedEventArgs e)
        {
            Console.WriteLine($"[INFO] Node joined: {e.NodeName}");
        }

        private static void OnMemberLeft(object sender, NodeLeftEventArgs e)
        {
            Console.WriteLine($"[ALERT] Node left: {e.NodeName}");
        }
    }
}

What’s happening here?

  • CacheCleared → Alerts you if cache data is completely cleared.

  • ItemAdded / ItemRemoved → Monitors object-level activity.

  • CacheStopped → Triggers a critical alert if cache is stopped.

  • MemberJoined / MemberLeft → Monitors cluster health in real time.

Step 3. Adding Custom Alerting (Email / Logging / Dashboard)

Subscribing to cache events is useful, but in a real production environment, you need a way to alert the right people when something goes wrong. That’s why the third step is adding custom alerting mechanisms. For example, if your OnCacheStopped event fires, it’s not enough to simply log a message to the console. You want your DevOps team or system administrator to know about it instantly. This can be done by sending an email using SMTP, firing a webhook to Slack or Microsoft Teams, or pushing the data to monitoring tools like Azure Application Insights, Prometheus, or ELK (Elasticsearch-Logstash-Kibana). In practice, you would implement a helper function (such as SendEmailAlert) that takes the subject and body of the alert and dispatches it via SMTP. You can then call this function inside your event handlers, ensuring that every time an event like CacheStopped or MemberLeft is triggered, someone on the operations team is immediately notified. This step essentially transforms passive monitoring into active alerting, which is a huge leap in preventing downtime.

  • Email Notifications (using SMTP).

  • Slack / Microsoft Teams Webhooks.

  • Centralized Logging (e.g., ELK, Serilog).

  • Application Insights / Prometheus metrics.

Example: Sending Email on Cache Down

private static void SendEmailAlert(string subject, string body)
{
    using (var client = new System.Net.Mail.SmtpClient("smtp.yourserver.com"))
    {
        var mail = new System.Net.Mail.MailMessage("[email protected]", "[email protected]");
        mail.Subject = subject;
        mail.Body = body;
        client.Send(mail);
    }
}

private static void OnCacheStopped(object sender, EventArgs e)
{
    string alertMessage = "[CRITICAL] Cache has stopped!";
    Console.WriteLine(alertMessage);
    SendEmailAlert("NCache Alert", alertMessage);
}

Step 4. Using NCache Manager for Visual Monitoring

While code-based monitoring and alerting are important for developers, system administrators often prefer visual dashboards to keep an eye on cache performance. This is where the NCache Manager dashboard comes in handy. Once you connect to your cache cluster through NCache Manager, you can monitor throughput (requests per second), cache hit ratios, memory usage, client connections, and even replication traffic across cluster nodes. The dashboard updates in real time and allows you to quickly spot performance bottlenecks. For example, you might notice that memory consumption is nearing the cache limit, which could cause evictions, or that one node is handling significantly more requests than others, which might indicate load-balancing issues. You can also set up threshold-based alerts in the GUI, so that the dashboard highlights problem areas when certain values cross defined limits. This step complements your programmatic monitoring by giving operations staff a bird’s-eye view of cache health, ensuring everyone—from developers to sysadmins—has the tools they need to respond quickly.

Apart from programmatic monitoring, you can use NCache Manager Dashboard:

  • Monitor throughput (requests/sec).

  • Track CPU/memory usage per node.

  • View client connections.

  • Get graphical alerts for thresholds.

This is helpful for operations teams who want a GUI-based experience.

Step 5. Performance Counters Integration

The final step to build a comprehensive monitoring system is to integrate NCache with performance monitoring tools via PerfMon counters. NCache exposes a rich set of counters to Windows Performance Monitor (PerfMon), allowing you to track metrics like cache requests per second, average response time, cache hit ratio, memory usage, client connections, and cluster node availability. By adding these counters into PerfMon, you can create live graphs, log data over time, and even export it to third-party tools like Grafana or Prometheus. For example, imagine you’re monitoring an API-driven SaaS product where traffic spikes during certain hours of the day. By tracking counters like “Requests/sec” and “Cache Hit Ratio,” you can visually confirm whether your cache is absorbing the load or whether database calls are increasing. Integrating these counters into your DevOps pipeline also enables long-term trend analysis, capacity planning, and predictive scaling. This step ensures that your cache monitoring is not only real time but also historically trackable, giving you both short-term alerts and long-term insights.

If you are using Windows Performance Monitor, NCache exposes several counters:

  • Requests per second

  • Cache hit ratio

  • Memory used / free

  • Number of connected clients

  • Number of cache servers running

You can integrate these counters into Grafana / Prometheus / Azure Monitor for advanced dashboards.

Best Practices for Cache Monitoring

  1. Always subscribe to cluster events in mission-critical apps.

  2. Define thresholds for memory, item count, and eviction policies.

  3. Integrate alerts with your DevOps monitoring stack.

  4. Use async logging to avoid blocking cache operations.

  5. Monitor cache hit ratio to measure caching effectiveness.

Conclusion

Real-time monitoring and alerting in NCache is not just a nice-to-have—it’s a must-have for enterprise applications. With NCache’s event notifications, performance counters, and management tools, you can:

  • Detect problems instantly.

  • Automate recovery.

  • Ensure high performance and reliability of your .NET applications.

Whether you’re building e-commerce platforms, financial systems, or SaaS products, integrating NCache monitoring and alerting will help you maintain 99.99% uptime and provide a seamless user experience.