Boost App Performance with Advanced Redis

In a previous blog post, I showed how you can speed up .NET APIs using Redis to cache frequently-accessed and infrequently-changing data. If you haven’t checked it out yet, it provides a solid foundation on how Redis can dramatically improve API performance.

In this post, I want to take things a step further by showcasing additional Redis capabilities that can enhance your software—from real-time messaging and dynamic data structures to efficient session storage and robust rate limiting. Whether you’re a software engineer or a technical leader, these advanced use cases will help you build faster, more scalable, and resilient systems.

Message Broker (Pub/Sub)

Real-time messaging is a cornerstone of modern distributed applications. Redis’s publish/subscribe (Pub/Sub) model provides a lightweight and efficient mechanism to broadcast messages across various parts of your system—making it ideal for notifications, chat systems, or any scenario requiring immediate data propagation.

Example: Implementing Pub/Sub in C#

Below is a simple C# example using the StackExchange.Redis library to illustrate how you can subscribe to a channel and publish messages:

using StackExchange.Redis;
using System;
using System.Threading.Tasks;

public class RedisPubSubExample
{
    public static async Task RunExample()
    {
        // Connect to the local Redis server
        var redis = ConnectionMultiplexer.Connect("localhost");
        var sub = redis.GetSubscriber();

        // Subscribe to the "notifications" channel
        await sub.SubscribeAsync("notifications", (channel, message) =>
        {
            Console.WriteLine($"Received: {message}");
        });

        // Publish a message to the "notifications" channel
        await sub.PublishAsync("notifications", "Hello from .NET!");

        Console.WriteLine("Message published. Press any key to exit...");
        Console.ReadKey();
    }
}

This example demonstrates the simplicity of setting up a real-time messaging system in your .NET applications, ensuring prompt communication between services.

Redis Data Structures for Advanced Use Cases

Redis supports a variety of data structures including lists, sets, and sorted sets, enabling you to solve common programming challenges effectively. One popular example is implementing a leaderboard—where a sorted set allows you to easily rank users or players by score.

Example: Creating a Leaderboard with Sorted Sets

The following C# snippet shows how to add players with scores to a leaderboard and then retrieve the ranking in descending order:

using StackExchange.Redis;
using System;

public class RedisLeaderboardExample
{
    public static void RunExample()
    {
        // Connect to the local Redis server
        var redis = ConnectionMultiplexer.Connect("localhost");
        var db = redis.GetDatabase();

        // Add players with their respective scores to the sorted set
        db.SortedSetAdd("game:leaderboard", "Player1", 1500);
        db.SortedSetAdd("game:leaderboard", "Player2", 2000);
        db.SortedSetAdd("game:leaderboard", "Player3", 1800);

        // Retrieve and display the leaderboard (highest score first)
        var topPlayers = db.SortedSetRangeByScore("game:leaderboard", order: Order.Descending);
        Console.WriteLine("Leaderboard:");
        foreach (var player in topPlayers)
        {
            Console.WriteLine(player);
        }
    }
}

This approach not only simplifies the implementation of dynamic rankings but also ensures your leaderboard updates in real time with minimal overhead.

Session Storage and Authentication

Managing sessions effectively is a critical aspect of any scalable web application. Traditional in-process session storage can limit scalability, especially in distributed systems. Redis offers a robust solution by storing session data in memory, enabling fast retrieval and seamless scaling across multiple servers.

Example: Storing Session Data in Redis

Here’s how you can use Redis to store and manage session data securely using JSON serialization:

using StackExchange.Redis;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;

public class RedisSessionExample
{
    public static async Task RunExample()
    {
        // Connect to the local Redis server
        var redis = ConnectionMultiplexer.Connect("localhost");
        var db = redis.GetDatabase();

        string sessionKey = "session:user123";
        var sessionData = new { UserId = "user123", Name = "John Doe", Role = "Admin" };

        // Serialize session data to JSON
        string jsonData = JsonConvert.SerializeObject(sessionData);

        // Store session data with a 30-minute expiration
        await db.StringSetAsync(sessionKey, jsonData, TimeSpan.FromMinutes(30));

        Console.WriteLine("Session data stored.");
    }
}

By centralizing session storage in Redis, your application can achieve high availability and performance even as traffic scales.

Rate Limiting and Throttling

APIs need robust mechanisms to prevent abuse and ensure service stability. Rate limiting is a crucial feature for this purpose, and Redis provides an effective platform to implement it using strategies like the token bucket or sliding window algorithms.

Example: Implementing a Basic Rate Limiter

This C# example demonstrates a very simple rate limiter that restricts a specific user to five requests per minute:

using StackExchange.Redis;
using System;
using System.Threading.Tasks;

public class RedisRateLimiterExample
{
    public static async Task<bool> IsAllowed(string userId)
    {
        // Connect to the local Redis server
        var redis = ConnectionMultiplexer.Connect("localhost");
        var db = redis.GetDatabase();

        string rateLimitKey = $"rate_limit:{userId}";
        // Increment the request counter
        int currentCount = (int)await db.StringIncrementAsync(rateLimitKey);

        // On first request, set a 1-minute expiration for the counter
        if (currentCount == 1)
        {
            await db.KeyExpireAsync(rateLimitKey, TimeSpan.FromMinutes(1));
        }

        // Allow up to 5 requests per minute
        return currentCount <= 5;
    }
}

This implementation helps safeguard your APIs by enforcing request limits, protecting backend resources from overload and potential abuse.

Leveraging .NET 9’s HybridCache with Redis

With the release of .NET 9, a new caching library called HybridCache has been introduced. This library simplifies caching by unifying in-memory and distributed caching approaches, making it easier to implement robust caching solutions in your applications. HybridCache supports various data stores as a secondary cache, including Redis.

Example: HybridCache with Redis

To get started with HybridCache and configure it to use Redis as the backing store, follow these steps:

1. Install the necessary packages:

dotnet add package Microsoft.Extensions.Caching.Hybrid --version 9.3.0
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

2. Register the HybridCache service in your Program.cs or Startup.cs file:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddHybridCache(options =>
{
    options.DefaultEntryOptions = new Microsoft.Extensions.Caching.Hybrid.HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(30),
        LocalCacheExpiration = TimeSpan.FromMinutes(10)
    };
});

// Configure Redis as the secondary cache
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379"; // Replace with your Redis server configuration
});

var app = builder.Build();

3. Use HybridCache in your application:

using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Threading.Tasks;

public class CacheService
{
    private readonly HybridCache _cache;

    public CacheService(HybridCache cache)
    {
        _cache = cache;
    }

    public async Task<string> GetOrCreateDataAsync(string key)
    {
        return await _cache.GetOrCreateAsync(key, async () =>
        {
            // Simulate data retrieval from a data source
            await Task.Delay(100); // Simulate delay
            return "Data from source";
        });
    }
}

In this example, the HybridCache service is configured with Redis as the secondary cache. The GetOrCreateAsync method first checks the in-memory cache for the data. If the data is not found, it then checks the Redis cache. If the data is still not found, it retrieves the data from the source and stores it in both the in-memory and Redis caches.

By leveraging HybridCache with Redis, you can achieve a highly efficient and scalable caching solution that combines the speed of in-memory caching with the persistence and scalability of Redis.

Other Applications of Redis

Beyond the use cases discussed above, Redis offers many additional options which can further enhance your system’s performance and scalability. For example, a few worthy of mention:

  1. Advanced Caching Strategies
    Beyond basic caching, Redis can be used for multi-level caching, query caching, and preloading data, thereby reducing latency and offloading database operations.
  2. Real-Time Analytics and Monitoring
    Utilize Redis to aggregate metrics, track events, and build real-time dashboards. This capability enables continuous monitoring of system performance and user interactions.
  3. Redis in Microservices Architectures
    Redis can serve as a distributed cache, message queue, or coordination tool between microservices. This is especially valuable for applications designed with scalability and fault tolerance in mind.

Persistence & Scaling Considerations

While Redis operates as an in-memory data store by default—delivering exceptional speed—it’s important to consider whether you need data durability or high availability in your production environments.

For these scenarios, Redis offers two primary persistence mechanisms:

  • RDB Snapshots: Periodically saves the dataset to disk, providing a balance between performance and durability.
  • AOF (Append Only File): Logs every write operation, offering more robust durability with a minor performance trade-off.

Both options are available in the free, open-source version of Redis. Enabling them is straightforward—simply adjust your redis.conf file to suit your persistence needs. This ensures that, in the event of a restart or failure, your data isn’t lost if durability is a priority.

Additionally, Redis supports running multiple instances, which is essential for scaling out your setup. In the free version, you can configure:

  • Replication: Easily set up “primary/replica” replication to distribute read loads and maintain data redundancy.
  • Clustering: Organize your data across multiple nodes to achieve horizontal scaling. While the free version supports basic clustering, be mindful of the configuration details to optimize performance and data consistency.

These configuration options make it simple to transition to a production-ready setup that is more robust and scalable.

Conclusion

As you can see, Redis is far more than a simple caching solution. Whether you’re implementing real-time messaging, building dynamic leaderboards, managing sessions efficiently, or enforcing API rate limits, Redis offers robust solutions that cater to the evolving needs of today’s software environments.

At Trailhead, we know from our years of experience that technology choices can significantly impact performance and scalability. Our team of experts is ready to help you unlock the full potential of your application by leveraging Redis and other cutting-edge technologies that help unlock its potential. You can contact us if you’re looking to explore the solutions above further or need guidance on your architecture

Picture of J. Tower

J. Tower

Jonathan, or J. as he's known to friends, is a husband, father, and founding partner of Trailhead Technology Partners, a custom software consulting company with employees across the U.S., Europe, and South America. He is a 12-time recipient of the Microsoft MVP award for his work with .NET, a frequent speaker at software conferences around the world, and was recently elected to the .NET Foundation Board for the 2026–2027 term. He doesn’t mind the travel, though, as it allows him to share what he's been learning and also gives him the chance to visit beautiful places like national parks—one of his passions. So far, he's visited 58 of the 63 U.S. national parks. J. is also passionate about building the software community. Over the years, he has served on several non-profit boards, including more than a decade as president of the board for Beer City Code, Western Michigan's largest professional software conference. Outside of work, J. enjoys hiking, reading, photography, and watching all the Best Picture nominees before the Oscars ceremony each year.

Free Consultation

Sign up for a FREE consultation with one of Trailhead's experts.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.