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 Jonathan "J." Tower

Jonathan "J." Tower

Jonathan, or J. as he's known to friends, is a founding partner of Trailhead Technology Partners, a custom software consulting company with employees across the U.S., Europe, and South America. He is Vice President of the .NET Foundation, a 13-time recipient of the Microsoft MVP award for his work with .NET and AI, and a frequent speaker at software conferences around the world. 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:

Slow .NET API? Redis Caching May Be the Answer

Just like venturing into the wilderness requires the proper gear, developing REST APIs with ASP.NET Core also requires the right tools and equipment for your application to perform at its best. At Trailhead, Redis caching is one such

Read More

Introducing HybridCache in .NET 9

Caching plays a crucial role in performance in web applications by reducing strain on backend systems. The new HybridCache library, available in preview in .NET 9, simplifies caching and addresses some limitations of previous approaches, ma

Read More

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! 

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.