Supercharge Your Application Performance With Redis Cache

Prashant Odhavani
Simform Engineering
7 min readJul 10, 2023

Redis Cache: Accelerate Your Application with Lightning-Fast Performance

In today’s digital landscape, application performance is crucial, and users expect lightning-fast response times. To achieve optimal performance, developers often turn to caching solutions like Redis cache.

Redis is a versatile in-memory data store that can significantly boost application speed.

In this article, we’ll explore Redis cache, its features, benefits, and implementation strategies to help you optimize your application’s performance.

Understanding Redis Cache

Redis, also known as Remote Dictionary Server, is a freely available in-memory data structure store. It functions as a cache, database, or message broker, making it suitable for various applications.

Redis excels in situations where rapid data retrieval and caching are essential. By storing data in memory, Redis achieves exceptional speed compared to disk-based databases. It supports multiple data structures such as strings, lists, sets, and hashes, allowing flexible data storage and manipulation.

Benefits of Redis Cache

  • Lightning-Fast Performance: Redis cache operates entirely in memory, eliminating disk I/O overhead and delivering sub-millisecond response times. It excels at handling high read and writes loads, making it ideal for caching frequently accessed data.
  • Data Persistence: Redis cache offers various persistence options, ensuring data availability even in case of server restarts or failures.
  • Advance Data Structures: Redis provides a rich set of data structures, enabling complex caching scenarios like storing session data, caching query results, or managing real-time leaderboard scores.
  • Pub/Sub and Message Queue: Redis supports publish/subscribe messaging patterns, making it a powerful tool for building real-time applications or implementing message queues for asynchronous processing.
  • Scalability and High Availability: Redis allows you to set up a cluster of nodes, providing automatic shading and replication for scalability and fault tolerance. This ensures your cache remains available and performant even under heavy loads.

Implementing Redis Cache

To leverage the Redis cache in your application, follow these steps:

  1. Choose an appropriate Redis client library for your programming language.
  2. Connect to the Redis server using the client library and configure the necessary options.
  3. Identify the data that can be cached and define a cache expiration strategy.
  4. Implement cache access patterns in your application code, retrieving data from the cache before falling back to the primary data source.
  5. Update the cache whenever the underlying data changes to maintain data consistency.
  6. Monitor and optimize your Redis cache usage by tweaking configurations and analyzing performance metrics.

Integration with Frameworks and Technologies

Redis cache can be seamlessly integrated into various frameworks and technologies. For example:

  • In web applications, you can use Redis cache with popular frameworks like .NET, Django, Ruby on Rails, or Express.js to cache database query results or session data.
  • In microservices architectures, Redis can serve as a shared cache, enhancing performance by reducing the load on individual services and improving overall efficiency.

Setting up Redis in Azure

To set up Redis in Azure, you can use Azure Cache for Redis, a fully managed service that provides a secure and scalable Redis cache. Follow these steps:

  1. Sign in to the Azure portal.
  2. Navigate to the “All Services” tab and search “Azure Cache for Redis”.
  3. Select “Azure Cache for Redis” from the search results and click “Create”.

4. Configure the cache settings, such as the subscription, resource group, and cache name.

5. Choose the pricing tier and other options like region and data persistence settings.

6. Review your settings and click “Create” to create the cache.

Once the resource is deployed successfully, obtain the connection string from the Access Key section. This connection string will be used to connect to the Redis server.

Using Redis with Docker

If you want to use Redis with a Docker container, follow these steps:

  1. Install Docker on your machine.
  2. Pull the Redis image from Docker Hub, as shown below:
docker pull redis

3. Start a Redis container:

docker run --name my-redis-container -p 5002:6379 -d redis

4. Verify that the container is running

docker ps

5. Connect to the Redis server

docker exec -it my-redis-container redis-cli

Let’s create a Blazor app to store using the Redis cache.

  1. In Visual Studio, create a project with the “Blazor Server App” template.

2. Install the following NuGet packages:

  • StackExchange.Redis (to connect with Redis clients)
  • Microsoft.Extensions.Caching.StackExchangeRedis (to use cache)

3. Open the appSettings.json file and add a connection string for Redis under the “ConnectionStrings” section.

"ConnectionStrings": {
"Redis": "YOUR CONNECTION STRING" // Azure Redis server connection string
//"Redis": "localhost:5002" // connect Redis container
}

4. In the Program.cs file, register the Redis cache dependency using the following code:

builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("Redis");
//options.InstanceName = "RedisDemo_"; // Optional: Provide instance name for multiple applications using the same Redis instance.
});

5. Create two extension methods of IDistributedCache to store and use cache in the entire project easily.

public static class DistributedCacheExtensions
{
public static async Task setRecordAsync<T>(this IDistributedCache cache,
string recordId,
T data,
TimeSpan? absoluteExpireTime = null,
TimeSpan? unusedExpireTime = null)
{
var options = new DistributedCacheEntryOptions();
options.AbsoluteExpirationRelativeToNow = absoluteExpireTime ?? TimeSpan.FromSeconds(60);
options.SlidingExpiration = unusedExpireTime;

var jsonData = JsonSerializer.Serialize(data);
await cache.SetStringAsync(recordId, jsonData,options);
}

public static async Task<T> GetRecordAsync<T>(this IDistributedCache cache, string recordId)
{
var jsonData = await cache.GetStringAsync(recordId);
if (jsonData is null)
{
return default(T);
}
return JsonSerializer.Deserialize<T>(jsonData);
}
}

6. Replace the WeatherForecastService.cs file in the Data folder with the provided code.

public class WeatherForecastService
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

public WeatherForecast[] GetForecastAsync(DateOnly startDate)
{
Task.Delay(3000);
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = startDate.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
}
}

7. Replace the FetchData.razor file in the Pages folder with the provided code.

@page "/fetchdata"
@using RedisDemo.Data
@using RedisDemo.Extensions
@inject WeatherForecastService ForecastService
@inject IDistributedCache Cache
<PageTitle>Weather forecast</PageTitle>

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

<button class="btn btn-primary" @onclick="LoadForeCast">Load Forecast</button>
@if (forecasts is null && loadLocation == "")
{
<p><em>Click the button to load the forecast</em></p>
}
else if (forecasts is null)
{
<p><em>Loading...</em></p>
}
else
{
<div class="h3 @isCachedData">@loadLocation</div>
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}

@code {
private WeatherForecast[]? forecasts;
private string loadLocation = "";
private string isCachedData = "";

private async Task LoadForeCast()
{

string recordKey = "WeatherForecast_" + DateTime.Now.ToString("yyyMMdd_hhmm");

var cachData = await Cache.GetRecordAsync<WeatherForecast[]>(recordKey);
if (cachData is null)
{
forecasts = ForecastService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now));
await Cache.setRecordAsync(recordKey, forecasts);

loadLocation = $"Loaded from API at {DateTime.Now}";
isCachedData = "";

}
else
{
forecasts = cachData;
loadLocation = $"Loaded from cache at {DateTime.Now}";
isCachedData = "text-danger";
}
}
}

With these steps, you can store and use the Redis cache in your Blazor app. Run the app by pressing CTRL + F5.

When the application opens in your browser, go to the Fetch Data tab and click the “Load Forecast” button. You will see the message “Loaded data from API with date and time”.

Click on the “Load Forecast” button again. This time, you will see the message “Loaded data from cache with date and time”.

You can also check the cache items in the Redis server.

For Azure:

Go to the Redis Cache resource and click on “Console”.

Once the console launches, type “ping” to get a response of “PONG”.

To list the cache items, type “Scan 0”.

You can also see the stored data inside a specific key by typing “hgetall your-cache-key”.

To check the current size of the database, use the command “dbsize”.

For Redis container:

Go to the command line interface and follow the same step to see cache items.

Following these steps, you can easily set up and use Redis cache in your Azure environment or with a Docker Redis image.

Summary

Redis cache in Azure offers a robust and scalable solution for caching in your applications. Whether you use Azure Cache for Redis or run Redis in a Docker container, Redis caching provides substantial benefits to enhance application performance and responsiveness.

You can learn more about it here: GitHub Repository.

Next, follow the Simform Engineering blogs for more such updates and insights.

Connect with us: Twitter | LinkedIn

--

--