Introduction
Modern applications often depend on multiple infrastructure services to handle different types of data. A database such as PostgreSQL stores permanent application data, while a caching system such as Redis helps retrieve frequently accessed information quickly.
Using both services in an ASP.NET Core application is common. However, managing them during local development can become challenging. Developers need to start database servers, configure connection strings, manage ports, check service availability, and make sure the application connects to the correct resources.
.NET Aspire simplifies this process by allowing developers to define infrastructure resources and application dependencies in one place. Instead of manually configuring every service, developers can use the Aspire AppHost project to manage PostgreSQL, Redis, and the application together.
In this article, we will build a small ASP.NET Core application that uses PostgreSQL for persistent storage and Redis for caching. We will configure both services through .NET Aspire and understand how the application communicates with them.
Why Use Redis and PostgreSQL Together?
PostgreSQL and Redis solve different problems. They are not alternatives to each other.
PostgreSQL is a relational database designed to store structured data. It supports transactions, relationships, indexing, and complex queries.
Redis is an in-memory data store commonly used for caching, session management, distributed locks, and temporary data storage.
Consider an e-commerce application that displays product information. Product details are stored in PostgreSQL. However, the same products may be requested by thousands of users.
Instead of executing the same database query for every request, the application can retrieve frequently requested product information from Redis.
The basic request flow looks like this:
The application receives a request for product information.
It checks whether the product exists in Redis.
If the product is available in Redis, the application returns the cached data.
If the product is not available, the application retrieves it from PostgreSQL.
The application stores the retrieved data in Redis for future requests.
This approach reduces repeated database queries and can improve response times.
Understanding the Application Architecture
We will build an application containing three main resources.
Resource | Responsibility |
|---|
ASP.NET Core Web API | Handles incoming HTTP requests |
PostgreSQL | Stores permanent product information |
Redis | Stores frequently accessed product data |
Aspire AppHost | Manages application resources and dependencies |
The AppHost will start PostgreSQL and Redis and provide their connection information to the API.
<text color="secondary" size="sm">Application architecture</text>
ASP.NET Core Web API
|
-----------------------
| |
PostgreSQL Redis
Permanent Storage Cache Storage
| |
-----------------------
|
.NET Aspire
AppHost
Step 1. Create a .NET Aspire Project
First, make sure the required .NET SDK and Aspire project templates are installed.
You can check the available SDK versions using:
dotnet --list-sdks
Install the Aspire templates if they are not already available:
dotnet new install Aspire.ProjectTemplates
Create a new Aspire starter application:
dotnet new aspire-starter -n AspireRedisPostgres
Navigate to the solution directory:
cd AspireRedisPostgres
The solution includes an AppHost project and a ServiceDefaults project. The starter template may also include sample application projects.
For this example, we will use an API project named AspireRedisPostgres.Api.
Step 2. Add PostgreSQL and Redis Integrations
.NET Aspire provides hosting integrations for PostgreSQL and Redis.
Add the required packages to the AppHost project:
dotnet add AspireRedisPostgres.AppHost package Aspire.Hosting.PostgreSQL
dotnet add AspireRedisPostgres.AppHost package Aspire.Hosting.Redis
These packages allow Aspire to manage PostgreSQL and Redis as application resources.
Next, add the client integration packages to the API project:
dotnet add AspireRedisPostgres.Api package Aspire.Npgsql
dotnet add AspireRedisPostgres.Api package Aspire.StackExchange.Redis
The PostgreSQL integration provides an Npgsql data source, while the Redis integration registers a Redis connection multiplexer.
These integrations reduce the amount of manual connection configuration required in the application.
Step 3. Configure PostgreSQL and Redis in AppHost
Open the Program.cs file inside the AppHost project.
Add the following configuration:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");
var database = postgres.AddDatabase("productdb");
var redis = builder.AddRedis("cache");
builder.AddProject<Projects.AspireRedisPostgres_Api>("api")
.WithReference(database)
.WithReference(redis)
.WaitFor(database)
.WaitFor(redis);
builder.Build().Run();
Let's understand the configuration.
The AddPostgres method registers a PostgreSQL server resource.
The AddDatabase method creates a logical database named productdb.
The AddRedis method registers a Redis resource with the name cache.
The WithReference method makes the corresponding connection configuration available to the API project.
The WaitFor method establishes startup dependencies so the API waits for the required resources to become ready.
When you run the AppHost, Aspire can start the PostgreSQL and Redis containers using the configured container runtime.
This means developers do not need to manually start both services before running the API.
Step 4. Configure PostgreSQL in the API
Now open the API project's Program.cs file.
Register the PostgreSQL data source:
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.AddNpgsqlDataSource("productdb");
builder.AddRedisClient("cache");
var app = builder.Build();
app.MapDefaultEndpoints();
app.MapGet("/", () =>
"Redis and PostgreSQL are running.");
app.Run();
The AddServiceDefaults method configures common application features such as health checks and telemetry.
The AddNpgsqlDataSource method creates a PostgreSQL data source using the connection information provided by Aspire.
The AddRedisClient method registers a Redis connection multiplexer using the Redis resource configuration.
Both services are now available through dependency injection.
Step 5. Create a Product Model
Let's create a simple model that represents product information.
Create a Product.cs file:
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
The model contains three properties: product ID, product name, and price.
We will use PostgreSQL to store these records and Redis to cache the retrieved product information.
Step 6. Create the Product Table
For this example, we will create the product table when the application starts.
Add the following code before app.Run():
using Npgsql;
using var scope = app.Services.CreateScope();
var dataSource = scope.ServiceProvider
.GetRequiredService<NpgsqlDataSource>();
await using var connection =
await dataSource.OpenConnectionAsync();
await using var command = connection.CreateCommand();
command.CommandText = """
CREATE TABLE IF NOT EXISTS products
(
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price NUMERIC(10, 2) NOT NULL
);
""";
await command.ExecuteNonQueryAsync();
This code creates the products table if it does not already exist.
For a real application, database schema changes should be managed through a migration tool such as Entity Framework Core migrations or a dedicated database migration process.
Running schema creation directly during application startup is suitable for a small demonstration, but it is not a replacement for production database migrations.
Step 7. Implement Redis Caching
Now let's implement an API endpoint that retrieves product information.
We will use Redis to cache the product data.
Add the following endpoint to Program.cs:
using System.Text.Json;
using Npgsql;
using StackExchange.Redis;
app.MapGet("/api/products/{id:int}", async (
int id,
NpgsqlDataSource dataSource,
IConnectionMultiplexer redis) =>
{
var cache = redis.GetDatabase();
var cacheKey = $"product:{id}";
// Check Redis first
var cachedProduct = await cache.StringGetAsync(cacheKey);
if (cachedProduct.HasValue)
{
var product = JsonSerializer.Deserialize<Product>(
cachedProduct.ToString());
return product is null
? Results.Problem("Invalid cached product data.")
: Results.Ok(product);
}
// Retrieve product from PostgreSQL
await using var connection =
await dataSource.OpenConnectionAsync();
await using var command = connection.CreateCommand();
command.CommandText = """
SELECT id, name, price
FROM products
WHERE id = @id
""";
command.Parameters.AddWithValue("id", id);
await using var reader = await command.ExecuteReaderAsync();
if (!await reader.ReadAsync())
{
return Results.NotFound();
}
var productFromDatabase = new Product
{
Id = reader.GetInt32(0),
Name = reader.GetString(1),
Price = reader.GetDecimal(2)
};
// Store the product in Redis
var json = JsonSerializer.Serialize(productFromDatabase);
await cache.StringSetAsync(
cacheKey,
json,
TimeSpan.FromMinutes(10));
return Results.Ok(productFromDatabase);
});
This endpoint demonstrates the cache-aside pattern.
First, the application checks Redis using the product ID as the cache key.
If the product exists in Redis, it returns the cached information without querying PostgreSQL.
If the product is not available, the application executes a database query, retrieves the product, and stores the result in Redis.
The cache entry expires after 10 minutes. This prevents cached data from remaining indefinitely.
For simplicity, this example uses direct SQL queries and JSON serialization. Larger applications can move this logic into dedicated services and repositories.
Step 8. Add a Product Insert Endpoint
We also need a way to insert products into PostgreSQL.
Add the following endpoint:
app.MapPost("/api/products", async (
Product product,
NpgsqlDataSource dataSource,
IConnectionMultiplexer redis) =>
{
await using var connection =
await dataSource.OpenConnectionAsync();
await using var command = connection.CreateCommand();
command.CommandText = """
INSERT INTO products (id, name, price)
VALUES (@id, @name, @price)
""";
command.Parameters.AddWithValue("id", product.Id);
command.Parameters.AddWithValue("name", product.Name);
command.Parameters.AddWithValue("price", product.Price);
await command.ExecuteNonQueryAsync();
var cache = redis.GetDatabase();
await cache.KeyDeleteAsync($"product:{product.Id}");
return Results.Created(
$"/api/products/{product.Id}",
product);
});
After inserting the product, the application removes the corresponding Redis cache entry.
This is important because an existing cache entry may contain outdated information.
For production applications, cache invalidation should be designed carefully. If multiple services update the same data, they must follow a consistent invalidation or update strategy.
Step 9. Run and Test the Application
Now run the Aspire AppHost:
dotnet run --project AspireRedisPostgres.AppHost
Aspire starts the API, PostgreSQL, and Redis resources.
Open the Aspire dashboard using the address displayed in the terminal.
You should see the API, PostgreSQL, and Redis resources along with their current status.
Now test the product creation endpoint.
Send a POST request to:
/api/products
Request body:
{
"id": 1,
"name": "Wireless Keyboard",
"price": 1499.00
}
Next, retrieve the product:
/api/products/1
The first request retrieves the product from PostgreSQL and stores it in Redis.
Subsequent requests can retrieve the same product from Redis until the cache expires or is invalidated.
You can also inspect the Redis resource through the available diagnostic tools to verify that the cache key has been created.
PostgreSQL vs Redis in This Application
Feature | PostgreSQL | Redis |
|---|
Primary purpose | Permanent data storage | Fast data access and caching |
Data storage | Disk-based with memory caching | Primarily in-memory |
Data structure | Relational tables | Key-value and other supported structures |
Transactions | Full relational transaction support | Redis transaction capabilities |
Common use | Orders, users, products | Cache, sessions, temporary data |
Data persistence | Designed for durable storage | Persistence depends on configuration |
Both services work together, but each has a separate responsibility.
Best Practices When Using Redis and PostgreSQL
Set Appropriate Cache Expiration
Avoid storing every cache entry permanently.
Use expiration times based on how frequently the underlying data changes and how stale the application can allow the data to become.
Handle Cache Failures
Redis should not become an unnecessary single point of failure for data that already exists in PostgreSQL.
If the application requires availability during Redis outages, design a fallback strategy that retrieves data from PostgreSQL when appropriate.
Keep Cache Keys Consistent
Use a predictable naming convention for Redis keys.
For example:
product:1
product:2
user:100
order:500
Consistent naming makes cache management and troubleshooting easier.
Avoid Caching Everything
Cache frequently accessed data that is expensive to retrieve.
Caching every database response can increase memory consumption and create additional maintenance work.
Manage Database Connections Properly
Use a shared NpgsqlDataSource rather than creating a new data source for every request.
The data source manages connection pooling and helps applications use database connections efficiently.
Protect Connection Information
Do not hardcode database passwords or Redis credentials in source code.
Use secure configuration providers and appropriate secret management when deploying applications.
Common Mistakes and Troubleshooting
Problem | Possible Cause | Solution |
|---|
PostgreSQL connection fails | Incorrect resource configuration | Verify the database reference |
Redis connection fails | Redis resource is unavailable | Check the Aspire dashboard |
Old product information appears | Cache was not invalidated | Remove or update the affected cache entry |
Redis memory usage increases | Too many cached entries | Configure expiration and eviction policies |
API starts before dependencies | Missing startup dependency | Configure WaitFor appropriately |
Database queries fail | Incorrect SQL or table structure | Check PostgreSQL logs and query configuration |
One important consideration is that startup dependency management does not guarantee that Redis or PostgreSQL will remain available throughout the application's lifetime. The API must still handle runtime connection failures.
Advantages and Disadvantages
Advantages
Runs PostgreSQL and Redis together through one Aspire application.
Reduces manual connection string configuration.
Makes local development easier to manage.
Provides centralized resource monitoring.
Supports realistic application development using actual infrastructure services.
Helps developers identify service startup and connectivity problems.
Disadvantages
Requires additional Aspire hosting and client integration packages.
Container-based resources require a compatible container runtime.
Developers must understand cache invalidation and data consistency.
Redis introduces additional memory and infrastructure requirements.
Production deployment still requires separate infrastructure and operational planning.
Summary
Running Redis and PostgreSQL together is a practical approach for applications that need reliable data storage and faster access to frequently requested information.
In this article, we created an ASP.NET Core application using .NET Aspire and configured PostgreSQL and Redis through the AppHost project.
We implemented a product API that retrieves data from PostgreSQL, stores frequently accessed information in Redis, and invalidates the cache when a product is added.
.NET Aspire makes the local development experience easier by managing infrastructure resources, providing connection configuration, and offering a centralized dashboard.
By combining PostgreSQL, Redis, and .NET Aspire, developers can build a more organized development environment while following application architecture patterns that can also be applied to larger distributed systems.
Join the conversation! Your thoughts help the community grow.