StackExchange.Redis NuGet Setup Giving You Trouble?
If you’re facing installation, version, or compatibility issues with the StackExchange.Redis NuGet package, the right setup can help you connect Redis reliably and avoid development roadblocks.
- NuGet package configuration
- Redis connection setup
- Version compatibility checks
- .NET integration support
StackExchange.Redis is one of the most widely used Redis client libraries for .NET applications. It allows C# and other .NET applications to connect to Redis-compatible servers for caching, session storage, distributed locking, pub/sub messaging, counters, queues, and other high-performance data operations.
The library is distributed through NuGet, making it easy to add Redis support to ASP.NET Core, APIs, microservices, background services, and enterprise applications. The official package is maintained under the StackExchange.Redis name, and the current NuGet package page lists version 3.1.13 as of August 2026.
This guide explains what the StackExchange.Redis NuGet package is, how to install it, configure Redis connections, perform basic operations, integrate it into ASP.NET Core, handle common issues, and follow production best practices.
What is StackExchange.Redis NuGet?
StackExchange.Redis is a high-performance RESP client for .NET applications. It is designed to communicate with Redis and Redis-compatible servers through a lightweight and efficient API. The official package is available on NuGet under the name StackExchange.Redis.
The library provides support for both synchronous and asynchronous Redis operations and can be used with applications that need fast in-memory data access. It also works with Redis-compatible platforms such as Azure Managed Redis, AWS ElastiCache, Valkey, Garnet, and other RESP-based servers.
A common architecture looks like this:
.NET Application
↓
StackExchange.Redis
↓
ConnectionMultiplexer
↓
Redis Server
↓
Cache / Data / Pub-Sub / Counters
The package acts as the communication layer between your application and the Redis server.
Why Use StackExchange.Redis in .NET?
Redis is often introduced when an application needs faster access to frequently requested data, shared state across multiple application instances, or lightweight messaging between services.
StackExchange.Redis is especially useful because it exposes Redis commands through strongly typed .NET APIs while keeping connection management efficient. The library’s ConnectionMultiplexer is designed to handle communication with one or more Redis servers and should be reused across the application rather than recreated for every operation.
- Improve Application Performance
- Support Distributed Applications
- Enable Pub/Sub Messaging
How to Install StackExchange.Redis NuGet?
There are several ways to install the package depending on your development workflow. The Redis documentation recommends installing the StackExchange.Redis NuGet package before creating a ConnectionMultiplexer.
Install Using .NET CLI
Run the following command from the directory containing your .csproj file:
dotnet add package StackExchange.Redis
If you want to install a specific version:
dotnet add package StackExchange.Redis --version 3.1.13
The exact current version should always be checked on NuGet before pinning it in a production project. The official package page currently lists 3.1.13.
Install Using NuGet Package Manager Console
Inside Visual Studio, open Package Manager Console and run:
Install-Package StackExchange.Redis
For a specific version:
Install-Package StackExchange.Redis -Version 3.1.13
Add PackageReference Manually
You can also edit the project file directly:
<ItemGroup>
<PackageReference Include="StackExchange.Redis" Version="3.1.13" />
</ItemGroup>
Then restore packages:
dotnet restore
How to Connect to Redis Using StackExchange.Redis?
The central class in the library is ConnectionMultiplexer. The official documentation describes it as the main object used to hide the details of one or more Redis servers and specifically recommends storing and reusing it rather than creating a new connection for every operation.
A basic connection looks like this:
using StackExchange.Redis;
ConnectionMultiplexer redis =
ConnectionMultiplexer.Connect("localhost:6379");
IDatabase db = redis.GetDatabase();
Once the connection is established, IDatabase provides access to Redis commands.
Basic Redis Operations in C#
Once ConnectionMultiplexer is available, you can begin reading and writing values.
Store a String Value
await db.StringSetAsync("user:1001:name", "John");
Retrieve a String Value
RedisValue value =
await db.StringGetAsync("user:1001:name");
Console.WriteLine(value);
Store a Value With Expiration
Caching usually works best when values expire automatically.
await db.StringSetAsync(
"product:500",
"Laptop",
TimeSpan.FromMinutes(30)
);
After 30 minutes, Redis automatically removes the key.
Delete a Key
await db.KeyDeleteAsync("product:500");
Check Whether a Key Exists
bool exists =
await db.KeyExistsAsync("product:500");
How to Configure StackExchange.Redis
StackExchange.Redis supports both configuration strings and ConfigurationOptions objects. The official configuration documentation states that both formats can be passed to Connect or ConnectAsync.
Simple Configuration String
var redis = ConnectionMultiplexer.Connect(
"redis-server:6379"
);
Configuration With Password
var redis = ConnectionMultiplexer.Connect(
"redis-server:6379,password=YourPassword"
);
Sensitive credentials should normally come from environment variables, secrets managers, or secure configuration rather than being hardcoded in source code.
ConfigurationOptions Example
var options = new ConfigurationOptions
{
EndPoints =
{
"redis-server:6379"
},
ConnectRetry = 3,
ConnectTimeout = 5000,
SyncTimeout = 5000,
AbortOnConnectFail = false
};
var redis =
await ConnectionMultiplexer.ConnectAsync(options);
This approach is useful when configuration requires multiple settings or conditional logic.
Using StackExchange.Redis in ASP.NET Core
In ASP.NET Core, the ConnectionMultiplexer should typically be registered as a singleton because it is thread-safe and designed to be shared. Redis’ official .NET tutorial also recommends maintaining a single multiplexer instance throughout the application lifetime.
Register ConnectionMultiplexer
In Program.cs:
using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(
ConnectionMultiplexer.Connect(
builder.Configuration.GetConnectionString("Redis")!
)
);
var app = builder.Build();
app.Run();
Add the connection string:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}
Inject Redis Into a Service
using StackExchange.Redis;
public class ProductCacheService
{
private readonly IDatabase _database;
public ProductCacheService(
IConnectionMultiplexer redis)
{
_database = redis.GetDatabase();
}
public async Task SetProductAsync(
string id,
string value)
{
await _database.StringSetAsync(
$"product:{id}",
value,
TimeSpan.FromMinutes(20)
);
}
public async Task<string?> GetProductAsync(
string id)
{
RedisValue value =
await _database.StringGetAsync(
$"product:{id}"
);
return value.HasValue
? value.ToString()
: null;
}
}
This keeps Redis access centralized and easier to test.
StackExchange.Redis vs Microsoft.Extensions.Caching.StackExchangeRedis
These two NuGet packages are related but serve different purposes.
StackExchange.Redis gives developers direct access to Redis commands and data structures. Microsoft.Extensions.Caching.StackExchangeRedis provides an IDistributedCache implementation that uses Redis underneath. The latter is intended for applications that want the standard ASP.NET Core distributed caching abstraction.
| Feature | StackExchange.Redis | Microsoft.Extensions.Caching.StackExchangeRedis |
|---|---|---|
| Direct Redis access | Yes | Limited abstraction |
| Strings | Yes | Yes |
| Hashes | Yes | Through lower-level client if needed |
| Lists | Yes | No direct API |
| Sorted Sets | Yes | No direct API |
| Pub/Sub | Yes | No |
| Distributed Cache API | Manual | Built-in |
| Best For | Advanced Redis usage | Standard ASP.NET caching |
Choose StackExchange.Redis when your application needs Redis-specific features. Choose the Microsoft caching package when you only need standard distributed cache behavior.
Using Redis Hashes
Hashes are useful for storing structured fields under one Redis key.
await db.HashSetAsync(
"user:1001",
new HashEntry[]
{
new("name", "John"),
new("email", "john@example.com"),
new("role", "admin")
}
);
Read a field:
RedisValue email =
await db.HashGetAsync(
"user:1001",
"email"
);
Hashes are often used for compact profile data and related key-value fields.
Using Redis Counters
Redis supports atomic increment and decrement operations.
long pageViews =
await db.StringIncrementAsync(
"page:home:views"
);
This is useful for:
- API rate counters
- Page views
- Login attempts
- Inventory counters
- Usage metrics
Because increment operations are atomic, multiple application instances can update the same counter safely.
Using Redis Pub/Sub
The ConnectionMultiplexer can create an ISubscriber for Redis publish/subscribe operations. Pub/sub is one of the three main uses highlighted in the project’s basic usage documentation.
Subscribe to a Channel
ISubscriber subscriber =
redis.GetSubscriber();
await subscriber.SubscribeAsync(
RedisChannel.Literal("notifications"),
(channel, message) =>
{
Console.WriteLine(
$"Received: {message}"
);
}
);
Publish a Message
await subscriber.PublishAsync(
RedisChannel.Literal("notifications"),
"Order completed"
);
Pub/sub is best for transient notifications. If consumers must receive messages even when they are offline, consider Redis Streams or a durable message broker instead.
Best Practices for StackExchange.Redis
Production Redis performance depends heavily on how the client is used. The following practices help reduce connection overhead and improve stability.
Reuse ConnectionMultiplexer
Do not do this for every request:
var redis =
ConnectionMultiplexer.Connect(
"localhost"
);
Instead, create one instance and reuse it. The project documentation specifically states that ConnectionMultiplexer is thread-safe and intended to be shared.
Prefer Async Operations
Use:
await db.StringGetAsync(key);
instead of blocking threads unnecessarily.
Async Redis calls are particularly important in high-traffic ASP.NET Core applications.
Use Key Expiration for Cache Data
Avoid unlimited cache growth.
await db.StringSetAsync(
key,
value,
TimeSpan.FromMinutes(15)
);
Expiration reduces stale data and helps control memory usage.
Avoid Large Values
Redis performs best when values remain reasonably small.
Large objects increase:
- Serialization time
- Network transfer
- Memory consumption
- Operation latency
Consider splitting data or caching only the fields actually required.
Avoid Expensive Redis Commands
Commands that scan large keyspaces can affect performance.
For key discovery and server-level operations, use the server APIs carefully and avoid running expensive operations inside frequent application requests.
Monitor Connection Events
Applications should monitor connectivity problems. Redis’ .NET guidance recommends registering for connection failure and restoration events.
Example:
redis.ConnectionFailed +=
(sender, args) =>
{
Console.WriteLine(
$"Redis connection failed: {args.Exception?.Message}"
);
};
redis.ConnectionRestored +=
(sender, args) =>
{
Console.WriteLine(
"Redis connection restored"
);
};
How Moon Technolabs Helps with Redis and .NET Development?
Moon Technolabs helps businesses develop scalable .NET applications using Redis caching, distributed architectures, microservices, cloud platforms, and performance-focused backend systems.
Our development teams can integrate StackExchange.Redis, design caching strategies, configure distributed session storage, implement counters and pub/sub workflows, optimize timeout handling, and connect Redis with ASP.NET Core APIs and enterprise applications.
Whether you need to improve application response times, reduce database load, implement distributed caching, or troubleshoot Redis performance issues, Moon Technolabs can help build and optimize a reliable Redis-backed .NET architecture.
Need Help Integrating Redis Into Your .NET Application?
We help you configure StackExchange.Redis, optimize caching, and build reliable .NET applications with fast and scalable Redis integrations.
Conclusion
The StackExchange.Redis NuGet package provides a powerful and efficient way for .NET applications to communicate directly with Redis. It supports core Redis features such as strings, hashes, counters, pub/sub, expiration, and asynchronous operations while giving developers fine-grained control over connections and commands.
The most important implementation rule is to create and reuse a shared ConnectionMultiplexer instead of opening a new Redis connection for every operation. From there, developers should use async methods, sensible expiration policies, secure configuration, connection monitoring, and lightweight Redis values to maintain performance.
When configured correctly, StackExchange.Redis can serve as a reliable foundation for caching, session storage, distributed counters, real-time notifications, and high-performance application data in modern .NET systems.
Get in Touch With Us
Submitting the form below will ensure a prompt response from us.



