Speeding Things Up: How I Used Azure Cache for Redis to Boost API Performance
Introduction
Building fast, efficient applications isn’t just about great code—it's also about making smart architectural decisions. One of the simplest ways to speed up your app is caching. Let me show you how I used Azure Cache for Redis to supercharge a simple API and why you should consider it for your next project.
Why Caching Matters
Think of caching as your app’s “shortcut.” Instead of running back to the database every time a user makes a request, you save commonly used data in memory, making it instantly available.
Faster Response Times: Data stored in memory is way quicker to fetch.
Lower Database Load: The database gets a breather when repetitive queries are handled by Redis.
Better User Experience: Faster apps mean happier users.
How Redis Fits In
Azure Cache for Redis is a managed service that takes care of caching for you. It’s fast, easy to set up, and integrates well with .NET applications.
Here’s a scenario to show its power:
A user requests product details (e.g.,
/api/products/5
).The app checks Redis for the product:
If it’s in the cache: The data is returned instantly.
If it’s not: The app fetches it from the database, caches it, and serves it to the user.
Future requests for the same product are handled by Redis, not the database.
Set Up Azure Cache for Redis
Step 1: Log in to Azure CLI
Run the following command to log in to your Azure account:
az login
Step 2: Create a Resource Group
Replace <RESOURCE_GROUP_NAME>
with your desired name and <LOCATION>
with your Azure region (e.g., eastus
, westeurope
).
az group create --name <RESOURCE_GROUP_NAME> --location <LOCATION>
Example:
az group create --name my-redis-rg --location eastus
Step 3: Create a Redis Cache Instance
Replace <REDIS_CACHE_NAME>
with a unique name for your Redis instance and <LOCATION>
with the same region as your resource group.
az redis create \
--name <REDIS_CACHE_NAME> \
--resource-group <RESOURCE_GROUP_NAME> \
--location <LOCATION> \
--sku Basic \
--vm-size C0
🕒 Note: This may take a few minutes to complete.
Step 4: Access the Redis Connection String
In the Azure Portal, navigate to the Redis Cache instance you just created.
Go to Access keys under Settings > Authentication.
Copy the Primary connection string (StackExchange.Redis).
Use this connection string in your application to connect to the Redis instance.
Redis in Action
For this project, I built a simple API to manage product data, powered by Azure Cache for Redis to improve performance. Here’s how it works:
Redis Service:
A dedicated service handles Get and Set operations, making it easy to interact with Redis.Caching in Endpoints:
Every API call checks Redis first. If the data isn’t cached, it’s fetched from the database, cached in Redis for future use, and returned to the user.
This approach drastically reduces database load and speeds up responses.
Code Example
Here’s how I handled fetching a single product:
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(long id)
{
var cacheKey = $"{Request.Scheme}://{Request.Host}{Request.Path}";
// Check cache
var cachedProduct = await _redisCacheService.Get(cacheKey);
if (!string.IsNullOrEmpty(cachedProduct))
{
var product = JsonSerializer.Deserialize<Product>(cachedProduct);
return Ok(product);
}
// Fetch from database
var productFromDb = await _context.Products.FindAsync(id);
if (productFromDb == null) return NotFound();
// Cache result
await _redisCacheService.Set(cacheKey, JsonSerializer.Serialize(productFromDb), TimeSpan.FromMinutes(1));
return productFromDb;
}
You can check out the full project on GitHub.
Why This Matters
For Developers: Redis simplifies caching logic, letting you focus on building features.
For Businesses: Faster apps mean happier users, higher engagement, and better performance during high-traffic events.
For Everyone: Your app doesn’t just work—it works fast.
Key Takeaways
Start Small: Even a basic Redis setup can make a noticeable difference.
Use TTL (Time-to-Live): Expiring cached data ensures users see up-to-date info.
Monitor: Keep an eye on your cache hit rate to ensure it's being used effectively.