<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Redis - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/redis/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Mon, 23 Nov 2026 17:53:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>Redis - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>StackExchange.Redis Connection String: Fix Cannot Connect</title>
		<link>https://thecodebuzz.com/stackexchange-it-was-not-possible-to-connect-to-the-redis-servers-to-create-a-disconnected-multiplexer-disable-abortonconnectfail/</link>
					<comments>https://thecodebuzz.com/stackexchange-it-was-not-possible-to-connect-to-the-redis-servers-to-create-a-disconnected-multiplexer-disable-abortonconnectfail/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 18 Jan 2022 08:04:00 +0000</pubDate>
				<category><![CDATA[Redis]]></category>
		<category><![CDATA[abortconnect=false]]></category>
		<category><![CDATA[abortonconnectfail redis connection string]]></category>
		<category><![CDATA[connectionmultiplexer]]></category>
		<category><![CDATA[connectionmultiplexer net core]]></category>
		<category><![CDATA[connectionmultiplexer.connect c#]]></category>
		<category><![CDATA[it was not possible to connect to the redis server(s). connecttimeout]]></category>
		<category><![CDATA[stackexchange.redis multiple connections]]></category>
		<category><![CDATA[stackexchangeredis timeout]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=20234</guid>

					<description><![CDATA[<p>Fix the StackExchange.Redis connection string error in .NET 10: check host, port, ssl and password, set abortConnect=false, and reuse one multiplexer.</p>
<p>The post <a href="https://thecodebuzz.com/stackexchange-it-was-not-possible-to-connect-to-the-redis-servers-to-create-a-disconnected-multiplexer-disable-abortonconnectfail/">StackExchange.Redis Connection String: Fix Cannot Connect</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph">Your .NET app starts, calls Redis, and dies with <code>It was not possible to connect to the redis server(s)</code>. The same string works on one machine and fails on another, and adding <code>abortConnect=false</code> only changes what you see next.</p>



<p class="wp-block-paragraph">The <strong>StackExchange.Redis connection string</strong> is almost always the cause: a wrong host or port, a missing <code>ssl=true</code> or <code>password=</code>, a firewall in the way, or an app that creates a new connection on every request. The checks and the code below were run on .NET 10 with StackExchange.Redis 3.4.35 against a local Redis 8.12; the settings are documented in the <a href="https://github.com/StackExchange/StackExchange.Redis/blob/main/docs/Configuration.md" target="_blank" rel="noopener">StackExchange.Redis configuration reference</a>.</p>



<p class="wp-block-paragraph">The diagram shows how to read the message and where to go next.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/11/redisconn-diagnostic-flow.png" alt="Diagram of the StackExchange.Redis connect error branching into authentication failure, unable to connect, and retry cases with the fix for each"/></figure>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#which">Which connection string setting fixes the error?</a></li><li><a href="#prereq">Prerequisites</a></li><li><a href="#causes">Why StackExchange.Redis cannot connect</a></li><li><a href="#checklist">Diagnostic checklist</a></li><li><a href="#string">A working connection string</a></li><li><a href="#code">Step 1: Connect with one shared multiplexer</a></li><li><a href="#di">Step 2: Register it in ASP.NET Core</a></li><li><a href="#azure">Azure Cache for Redis specifics</a></li><li><a href="#result">What each failure looks like</a></li><li><a href="#trouble">Troubleshooting table</a></li><li><a href="#faq">Frequently asked questions</a></li><li><a href="#summary">Summary</a></li></ul></div>



<h2 class="wp-block-heading" id="which">Which connection string setting fixes the error?</h2>



<ul class="wp-block-list">
<li><strong>Wrong or unreachable endpoint</strong>: fix host and port, firewall, DNS or <code>ssl</code>. <code>abortConnect=false</code> will not help.</li>

<li><strong>Authentication failure</strong>: the message mentions <code>NOAUTH</code> or <code>WRONGPASS</code>. Fix <code>password=</code> (and <code>user=</code> for ACL users).</li>

<li><strong>Redis simply starts later than your app</strong>: set <code>abortConnect=false</code> and <code>connectRetry</code> so the client keeps retrying in the background.</li>

<li><strong>New connection per request</strong>: create one <code>ConnectionMultiplexer</code> and reuse it.</li>
</ul>



<h2 class="wp-block-heading" id="prereq">Prerequisites</h2>



<ul class="wp-block-list">
<li>A .NET 10 SDK (the same code compiles on .NET 8 and 9, which were not run here).</li>

<li>The <code>StackExchange.Redis</code> NuGet package: <code>dotnet add package StackExchange.Redis</code> (3.4.35 was tested).</li>

<li>A Redis server you can reach, and its host, port, password and whether it requires TLS.</li>

<li><code>redis-cli</code> or any TCP test tool for the checklist below.</li>
</ul>



<h2 class="wp-block-heading" id="causes">Why StackExchange.Redis cannot connect</h2>



<p class="wp-block-paragraph"><code>abortConnect</code> (<code>AbortOnConnectFail</code> in code) defaults to <code>true</code>, and <code>false</code> on Azure endpoints. With <code>true</code>, <code>Connect()</code> throws this exception when no server can be reached after <code>connectRetry</code> attempts (default 3) of <code>connectTimeout</code> (default 5000 ms) each. The usual reasons:</p>



<ul class="wp-block-list">
<li><strong>Wrong host or port.</strong> Redis defaults to 6379. A typo, a container name that does not resolve from your network, or <code>localhost</code> used inside a container.</li>

<li><strong>Firewall or network security group.</strong> The port is blocked between client and server, or your client IP is not on the server allow list.</li>

<li><strong>TLS mismatch.</strong> <code>ssl=true</code> against a plain port, or a plain connection against a TLS-only port. Azure Cache for Redis uses 6380 for TLS and 6379 for non-TLS (disabled by default on new caches).</li>

<li><strong>Password.</strong> Missing or wrong. This gives an authentication failure rather than a plain timeout.</li>

<li><strong>DNS.</strong> The name does not resolve, or resolves to a private address your client cannot reach (private endpoint).</li>

<li><strong>Timeouts.</strong> A high-latency link, busy server or starved client thread pool and a <code>connectTimeout</code> that is too short.</li>

<li><strong>Redis not up yet.</strong> The app starts before the Redis container or service.</li>

<li><strong>Connection churn.</strong> Creating and disposing a multiplexer per call exhausts sockets and makes timeouts more likely.</li>
</ul>



<h2 class="wp-block-heading" id="checklist">Diagnostic checklist</h2>



<p class="wp-block-paragraph">Work top to bottom. Each step rules out one layer.</p>



<ul class="wp-block-list">
<li>Print the exact connection string the app uses (without the password) and confirm host and port.</li>

<li>From the same machine or container as the app, run <code>redis-cli -h HOST -p PORT ping</code>. For TLS add <code>--tls</code>. If this fails, the problem is not your C# code.</li>

<li>If it fails, test the port alone (<code>nc -vz HOST PORT</code>) and the name (<code>nslookup HOST</code>) to separate DNS, firewall and server problems.</li>

<li>If the server needs a password, run <code>redis-cli -a PASSWORD ping</code> and compare with the app&#8217;s <code>password=</code>.</li>

<li>Match TLS: TLS port needs <code>ssl=true</code>, plain port needs no <code>ssl</code>.</li>

<li>Read the full exception message. After the first sentence it names the endpoint and the inner cause, such as <code>NOAUTH</code>.</li>

<li>Only then tune <code>connectTimeout</code>, <code>connectRetry</code> and <code>abortConnect</code>.</li>
</ul>



<h2 class="wp-block-heading" id="string">A working connection string</h2>



<p class="wp-block-paragraph">A typical connection string for a TLS server with a password. Keep the password in user secrets, environment variables or a key vault, not in source control:</p>


<div class="wp-block-syntaxhighlighter-code ">
my-redis-host:6380,password=YOUR_PASSWORD,ssl=true,abortConnect=false,connectRetry=5,connectTimeout=5000
</div>


<ul class="wp-block-list">
<li><code>abortConnect=false</code>: <code>Connect()</code> returns a disconnected multiplexer and retries in the background instead of throwing. It hides the symptom, so check <code>IsConnected</code>.</li>

<li><code>ssl=true</code>: use TLS. Required on port 6380 of Azure Cache for Redis.</li>

<li><code>connectRetry</code> and <code>connectTimeout</code>: attempts during the first <code>Connect()</code>, and milliseconds per attempt.</li>

<li>Several servers are comma separated: <code>host1:6379,host2:6379</code>.</li>
</ul>



<p class="wp-block-paragraph">More detail on TLS setup is in <a href="https://thecodebuzz.com/redis-connect-with-ssl-tls-using-csharp-asp-net-core/">connecting to Redis with SSL/TLS in C#</a> and <a href="https://thecodebuzz.com/connect-to-remote-redis-server-cache-ssl-tls-auth/">connecting to a remote Redis server with auth</a>.</p>



<h2 class="wp-block-heading" id="code">Step 1: Connect with one shared multiplexer</h2>



<p class="wp-block-paragraph">This console program was compiled and run on .NET 10. It creates the multiplexer once through <code>Lazy&lt;T&gt;</code>, uses retry options, and reads and writes a key:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using StackExchange.Redis;

var options = ConfigurationOptions.Parse(&quot;127.0.0.1:6379&quot;);
options.AbortOnConnectFail = false;                 // keep retrying in the background
options.ConnectRetry = 5;                           // attempts during Connect()
options.ConnectTimeout = 5000;                      // ms per attempt
options.ReconnectRetryPolicy = new ExponentialRetry(5000);

var shared = new Lazy&lt;ConnectionMultiplexer&gt;(() =&gt; ConnectionMultiplexer.Connect(options));

var db = shared.Value.GetDatabase();
await db.StringSetAsync(&quot;demo:key&quot;, &quot;hello&quot;, TimeSpan.FromMinutes(1));
Console.WriteLine($&quot;connected={shared.Value.IsConnected}, value={await db.StringGetAsync(&quot;demo:key&quot;)}&quot;);
</pre></div>


<p class="wp-block-paragraph">To see the error itself, catch <code>RedisConnectionException</code> and print <code>FailureType</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
try
{
    using var mux = ConnectionMultiplexer.Connect(&quot;127.0.0.1:6399,connectTimeout=2000,connectRetry=1&quot;);
}
catch (RedisConnectionException ex)
{
    Console.WriteLine($&quot;{ex.FailureType}: {ex.Message}&quot;);
}
</pre></div>


<h2 class="wp-block-heading" id="di">Step 2: Register it in ASP.NET Core</h2>



<p class="wp-block-paragraph">In ASP.NET Core register one <code>IConnectionMultiplexer</code> as a singleton and inject it where needed. Compiled and run with <code>Microsoft.Extensions.DependencyInjection</code>; resolving it twice returned the same instance:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
services.AddSingleton&lt;IConnectionMultiplexer&gt;(_ =&gt;
{
    var options = ConfigurationOptions.Parse(configuration.GetConnectionString(&quot;Redis&quot;)!);
    options.AbortOnConnectFail = false;
    options.ConnectRetry = 5;
    options.ReconnectRetryPolicy = new ExponentialRetry(5000);
    return ConnectionMultiplexer.Connect(options);
});
</pre></div>


<p class="wp-block-paragraph">Do not create a multiplexer inside a controller or per request, and do not wrap it in <code>using</code> in request code. For a longer walkthrough see <a href="https://thecodebuzz.com/redis-dependency-injection-connectionmultiplexer-redis-cache-netcore-csharp/">Redis dependency injection with ConnectionMultiplexer</a> and <a href="https://thecodebuzz.com/connection-resiliency-redis-cache-stackexchange-redi-best-practices/">Redis connection resiliency best practices</a>. Microsoft also recommends a singleton multiplexer and <code>abortConnect=false</code> in its <a href="https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-best-practices-connection" target="_blank" rel="noopener">connection best practices</a>.</p>



<h2 class="wp-block-heading" id="azure">Azure Cache for Redis specifics</h2>



<ul class="wp-block-list">
<li>Use the host name from the portal (<code>NAME.redis.cache.windows.net</code>), the TLS port 6380, <code>ssl=true</code> and an access key as the password. Non-TLS access on 6379 is off by default on new caches. See the <a href="https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-configure" target="_blank" rel="noopener">cache configuration docs</a>.</li>

<li>If the cache has a firewall, add your client IP. With a private endpoint, public network access may be disabled by default, so the client must be inside the network or have access enabled.</li>

<li>If you use a third-party firewall or proxy, allow <code>*.redis.cache.windows.net</code> and ports 6379 and 6380. Clustered caches may need more ports.</li>

<li>Microsoft&#8217;s <a href="https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-troubleshoot-connectivity" target="_blank" rel="noopener">connectivity troubleshooting guide</a> covers these checks in detail.</li>

<li>Azure endpoints already default to <code>abortConnect=false</code>, so on Azure a failed first connection usually shows up later as timeouts. Check the endpoint and port shown in the portal for your tier.</li>
</ul>



<h2 class="wp-block-heading" id="result">What each failure looks like</h2>



<p class="wp-block-paragraph">Run against a local Redis 8.12 with one server on a plain port, one with <code>requirepass</code>, and one closed port. Messages shortened:</p>



<figure class="wp-block-table"><table><thead><tr><th>Test</th><th>Connection string setting</th><th>Result</th></tr></thead><tbody><tr><td>1</td><td>Closed port, default <code>abortConnect</code></td><td><code>UnableToConnect</code>: It was not possible to connect to the redis server(s). Error connecting right now&#8230;</td></tr><tr><td>2</td><td>Same port, <code>abortConnect=false</code></td><td>No exception, <code>IsConnected=False</code></td></tr><tr><td>3</td><td>Server with password, none supplied</td><td><code>AuthenticationFailure</code>: &#8230; <code>NOAUTH Returned - connection has not yet authenticated</code></td></tr><tr><td>4</td><td>Same server, <code>password=</code> correct</td><td><code>IsConnected=True</code></td></tr><tr><td>5</td><td><code>ssl=true</code> against a non-TLS port</td><td><code>UnableToConnect</code> (same text as test 1)</td></tr><tr><td>6</td><td>Shared multiplexer with retry options</td><td>connected, value read back, ping succeeded</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Test 5 shows why the first sentence of the message is not enough: a TLS mismatch looks the same as a closed port, so check TLS and the port together.</p>



<h2 class="wp-block-heading" id="trouble">Troubleshooting table</h2>



<figure class="wp-block-table"><table><thead><tr><th>Symptom</th><th>Likely cause</th><th>Fix</th></tr></thead><tbody><tr><td><code>UnableToConnect</code> immediately</td><td>Nothing listening, wrong host or port</td><td>Verify with <code>redis-cli ping</code> from the app&#8217;s machine</td></tr><tr><td><code>UnableToConnect</code> after about 5 seconds per attempt</td><td>Firewall or NSG drops packets, or private endpoint</td><td>Open the port, add client IP, check network path</td></tr><tr><td><code>AuthenticationFailure</code>, <code>NOAUTH</code> or <code>WRONGPASS</code></td><td>Missing or wrong password or user</td><td>Set <code>password=</code> (and <code>user=</code>); on Azure use the access key</td></tr><tr><td>Fails only on the TLS port</td><td><code>ssl</code> not set</td><td>Add <code>ssl=true</code></td></tr><tr><td>Fails only on the plain port</td><td><code>ssl=true</code> against non-TLS server</td><td>Remove <code>ssl</code> or use the TLS port</td></tr><tr><td>Works locally, fails in a container</td><td><code>localhost</code> points to the container itself</td><td>Use the Redis service name or host address</td></tr><tr><td>App starts, then Redis calls fail</td><td><code>abortConnect=false</code> hid a bad endpoint</td><td>Log <code>IsConnected</code>; fix the endpoint, not the flag</td></tr><tr><td>Timeouts under load</td><td>Multiplexer created per request, or short <code>connectTimeout</code></td><td>One shared multiplexer, keep default timeouts unless measured</td></tr></tbody></table></figure>



<h2 class="wp-block-heading" id="faq">Frequently asked questions</h2>



<h3 class="wp-block-heading">What does abortConnect=false do in StackExchange.Redis?</h3>



<p class="wp-block-paragraph">It makes Connect() return a multiplexer even if no server is reachable, and the client keeps retrying in the background. The app starts, but commands fail until a connection exists, so it does not fix a wrong host, port or password.</p>



<h3 class="wp-block-heading">Why do I get &#8216;It was not possible to connect to the redis server(s)&#8217; with the right host?</h3>



<p class="wp-block-paragraph">Usual remaining causes are a TLS mismatch (ssl=true against a plain port or the reverse), a firewall or network rule, a wrong password, or DNS resolving to an address the client cannot reach. Run redis-cli ping from the same machine and read the full exception message.</p>



<h3 class="wp-block-heading">Should I create a ConnectionMultiplexer for every request?</h3>



<p class="wp-block-paragraph">No. Create one and share it for the life of the app, for example as an ASP.NET Core singleton. It multiplexes many commands over a few connections, and creating many wastes sockets and can cause timeouts.</p>



<h2 class="wp-block-heading" id="summary">Summary</h2>



<p class="wp-block-paragraph">Read the exception text, run <code>redis-cli ping</code> from the app&#8217;s machine, and match host, port, <code>ssl</code> and <code>password</code> before changing anything else. Then add <code>abortConnect=false</code> and retry settings, and share one multiplexer. Tested here: .NET 10, StackExchange.Redis 3.4.35, local Redis 8.12 on plain ports, including a password-protected server, a closed port, a TLS mismatch and a DI singleton. Not tested: a real TLS server, Azure Cache for Redis, clusters or Sentinel, .NET 8 and 9, and firewall or DNS failures.</p>



<div class="wp-block-group has-background" style="border-radius:8px;background-color:#b6d9ac;padding-top:20px;padding-right:24px;padding-bottom:20px;padding-left:24px"><div class="wp-block-group__inner-container is-layout-constrained wp-container-core-group-is-layout-0d2d72cd wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph" style="font-size:20px"><strong>Found this useful?</strong></p>



<p class="wp-block-paragraph">Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.</p>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noopener">Subscribe to TheCodeBuzz</a></div>
</div>
</div></div>



<script type="application/ld+json">{"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "What does abortConnect=false do in StackExchange.Redis?", "acceptedAnswer": {"@type": "Answer", "text": "It makes Connect() return a multiplexer even if no server is reachable, and the client keeps retrying in the background. The app starts, but commands fail until a connection exists, so it does not fix a wrong host, port or password."}}, {"@type": "Question", "name": "Why do I get 'It was not possible to connect to the redis server(s)' with the right host?", "acceptedAnswer": {"@type": "Answer", "text": "Usual remaining causes are a TLS mismatch (ssl=true against a plain port or the reverse), a firewall or network rule, a wrong password, or DNS resolving to an address the client cannot reach. Run redis-cli ping from the same machine and read the full exception message."}}, {"@type": "Question", "name": "Should I create a ConnectionMultiplexer for every request?", "acceptedAnswer": {"@type": "Answer", "text": "No. Create one and share it for the life of the app, for example as an ASP.NET Core singleton. It multiplexes many commands over a few connections, and creating many wastes sockets and can cause timeouts."}}]}</script><p>The post <a href="https://thecodebuzz.com/stackexchange-it-was-not-possible-to-connect-to-the-redis-servers-to-create-a-disconnected-multiplexer-disable-abortonconnectfail/">StackExchange.Redis Connection String: Fix Cannot Connect</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/stackexchange-it-was-not-possible-to-connect-to-the-redis-servers-to-create-a-disconnected-multiplexer-disable-abortonconnectfail/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Redis Best Practices for Development: Keys, Expiry, Security</title>
		<link>https://thecodebuzz.com/redis-cache-best-practices-development/</link>
					<comments>https://thecodebuzz.com/redis-cache-best-practices-development/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 03 Jan 2022 07:01:00 +0000</pubDate>
				<category><![CDATA[Redis]]></category>
		<category><![CDATA[aws redis best practices]]></category>
		<category><![CDATA[azure redis cache best practices]]></category>
		<category><![CDATA[redis cache example]]></category>
		<category><![CDATA[redis cache key naming convention]]></category>
		<category><![CDATA[redis cache tutorial]]></category>
		<category><![CDATA[redis cache-aside]]></category>
		<category><![CDATA[redis caching patterns]]></category>
		<category><![CDATA[redis configuration best practices]]></category>
		<category><![CDATA[redis design patterns]]></category>
		<category><![CDATA[redis distributed cache]]></category>
		<category><![CDATA[redis hash best practices]]></category>
		<category><![CDATA[redis security best practices]]></category>
		<category><![CDATA[redis system design]]></category>
		<category><![CDATA[redis write-through cacheredis best practices and performance tuning]]></category>
		<category><![CDATA[stackexchange redis best practices]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=18770</guid>

					<description><![CDATA[<p>Redis best practices for developers: key naming, SCAN instead of KEYS, key expiration, cache concurrency, Lua scripts and securing data in the cache.</p>
<p>The post <a href="https://thecodebuzz.com/redis-cache-best-practices-development/">Redis Best Practices for Development: Keys, Expiry, Security</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph">Your Redis cache works in development, then production brings slow commands, memory that never stops growing, or keys nobody can find. Most of those problems come from a handful of habits that are cheap to fix at design time and expensive to fix later.</p>



<p class="wp-block-paragraph">These <strong>Redis best practices</strong> cover key naming, data structures, expiry and eviction, the cache-aside pattern, big and hot keys, SCAN instead of KEYS, pipelining, connection reuse, persistence, security and monitoring. The .NET sample at the end uses StackExchange.Redis 2.8.58 on .NET 10 and was compiled here. It was not run against a live server (see the notes in the summary).</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/11/redisbp-cache-aside.png" alt="Diagram of the cache-aside pattern: the application reads Redis first, loads from the database on a miss and stores the value in Redis with a TTL"/></figure>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#which">Which Redis best practices matter most?</a></li><li><a href="#aioseo-naming-convention-for-redis-key-and-namespace">Key naming and design</a></li><li><a href="#aioseo-storing-the-data-on-the-server">Choose the right data structure</a></li><li><a href="#aioseo-manage-key-expiration-in-redis-cache">TTL, expiry and eviction policies</a></li><li><a href="#aioseo-cache-frequently-used-data">Cache-aside pattern</a></li><li><a href="#bigkeys">Avoid big keys and hot keys</a></li><li><a href="#aioseo-use-the-scan-vs-keys-command-guidelines">Use SCAN, not KEYS</a></li><li><a href="#pipe">Pipelining and connection reuse</a></li><li><a href="#persist">Persistence: RDB vs AOF</a></li><li><a href="#aioseo-redis---security-for-data">Security: auth, ACLs and TLS</a></li><li><a href="#monitor">Monitoring: INFO and SLOWLOG</a></li><li><a href="#example">Example: .NET and StackExchange.Redis</a></li><li><a href="#trouble">Common mistakes and fixes</a></li><li><a href="#faq">Frequently asked questions</a></li><li><a href="#summary">Summary</a></li></ul></div>



<h2 class="wp-block-heading" id="which">Which Redis best practices matter most?</h2>



<ul class="wp-block-list">
<li><strong>Design</strong>: predictable key names, the right data structure, small values.</li>

<li><strong>Lifetime</strong>: a TTL on every cache key, a memory limit and an eviction policy.</li>

<li><strong>Access</strong>: cache-aside reads, SCAN for lookups, pipelining for batches, one shared connection.</li>

<li><strong>Operations</strong>: pick persistence on purpose, lock down access, watch INFO and SLOWLOG.</li>
</ul>



<p class="wp-block-paragraph">This article is the design checklist. For the .NET wiring, see <a href="https://thecodebuzz.com/redis-dependency-injection-connectionmultiplexer-redis-cache-netcore-csharp/">dependency injection of the ConnectionMultiplexer</a> and <a href="https://thecodebuzz.com/redis-distributed-cache-asp-net-core-csharp-redis-examples/">Redis distributed cache in C# .NET with examples</a>.</p>



<h2 class="wp-block-heading" id="aioseo-naming-convention-for-redis-key-and-namespace">Key naming and design</h2>



<p class="wp-block-paragraph">Redis has no schemas or tables, so the key name is your schema. Use one consistent pattern, usually colon separated: <code>app:entity:id[:field]</code>. The keyspace documentation describes keys and their commands.</p>


<div class="wp-block-syntaxhighlighter-code ">
SET shop:product:42 &quot;{&#8230;json&#8230;}&quot;
SET shop:session:9f3a &quot;{&#8230;}&quot;
SET billing:invoice:2024:1007 &quot;{&#8230;}&quot;
</div>


<ul class="wp-block-list">
<li>Start with a namespace (<code>shop:</code>) so several apps or environments can share one instance without collisions.</li>

<li>Put the stable part first and the id last, so a pattern such as <code>shop:product:*</code> stays useful.</li>

<li>Keep keys short but readable. Very long keys cost memory in every copy and every replica.</li>

<li>Do not put secrets or personal data in key names; key names show up in logs, SLOWLOG and monitoring tools.</li>

<li>Add a version when the stored shape changes, for example <code>shop:v2:product:42</code>, so old and new code can coexist during a deployment.</li>
</ul>



<h2 class="wp-block-heading" id="aioseo-storing-the-data-on-the-server">Choose the right data structure</h2>



<p class="wp-block-paragraph">A JSON string is fine for a whole object you always read and write together. Other structures often fit better:</p>



<ul class="wp-block-list">
<li><strong>String</strong>: a serialized object, a counter (<code>INCR</code>) or a flag.</li>

<li><strong>Hash</strong>: an object whose fields you update one at a time (<code>HSET</code>, <code>HGET</code>).</li>

<li><strong>Set</strong>: unique members and membership checks, such as tags.</li>

<li><strong>Sorted set</strong>: leaderboards and time-ordered indexes.</li>

<li><strong>List and stream</strong>: queues and event logs.</li>
</ul>



<p class="wp-block-paragraph">Pick the structure for the operation you run most. Reading one field of a hash is cheaper than deserializing a large JSON string to read one value.</p>



<h2 class="wp-block-heading" id="aioseo-manage-key-expiration-in-redis-cache">TTL, expiry and eviction policies</h2>



<p class="wp-block-paragraph">A cache without expiry grows until it fills memory. Set a TTL when you write (<code>SET key value EX 600</code>, or the <code>expiry</code> argument in StackExchange.Redis) instead of a separate <code>EXPIRE</code> call, so a crash between two commands never leaves an immortal key. EXPIRE documents the command.</p>



<ul class="wp-block-list">
<li>Add random jitter to TTLs so a batch of keys loaded together does not expire together and send a spike to your database.</li>

<li>Choose the TTL from how stale the data may be, not from a habit of one hour.</li>

<li>Set <code>maxmemory</code> so Redis has a ceiling, and choose <code>maxmemory-policy</code> deliberately.</li>
</ul>



<p class="wp-block-paragraph">The <a href="https://redis.io/docs/latest/develop/reference/eviction/" target="_blank" rel="noopener">eviction documentation</a> lists the policies. The ones most used for caches:</p>



<ul class="wp-block-list">
<li><code>allkeys-lru</code>: evict the least recently used keys, whether or not they have a TTL. A common choice for a pure cache.</li>

<li><code>allkeys-lfu</code>: evict the least frequently used keys.</li>

<li><code>volatile-ttl</code>: among keys with a TTL, evict those closest to expiry.</li>

<li><code>noeviction</code>: refuse writes that need more memory. Use it when Redis holds data you cannot lose.</li>
</ul>



<p class="wp-block-paragraph">The <code>volatile-*</code> policies only consider keys that have an expiry, so keys without a TTL are never evicted by them.</p>



<h2 class="wp-block-heading" id="aioseo-cache-frequently-used-data">Cache-aside pattern</h2>



<p class="wp-block-paragraph">In cache-aside the application owns the logic: read the cache, on a miss load from the source, store the result with a TTL, return it. When data changes, update the database first and then delete (or overwrite) the cached key. The diagram above shows the flow and the code in the example section implements it.</p>



<ul class="wp-block-list">
<li>Treat the cache as optional: if Redis is down, fall back to the database instead of failing the request.</li>

<li>Cache missing results briefly too (for example a short TTL on a &#8220;not found&#8221; marker) if repeated misses would hammer the database.</li>

<li>A popular key that expires can make many requests hit the database at once. Jitter helps; for very hot keys also consider a lock or refresh-ahead approach.</li>
</ul>



<h2 class="wp-block-heading" id="bigkeys">Avoid big keys and hot keys</h2>



<p class="wp-block-paragraph">Redis runs commands on one main thread, so one slow command delays every client. Two usual causes are:</p>



<ul class="wp-block-list">
<li><strong>Big keys</strong>: a huge string, or a hash, list or set with millions of members. Reading or deleting it blocks other work. Split it into smaller keys or buckets, and delete large keys with <code>UNLINK</code> (non-blocking free) instead of <code>DEL</code>. Check sizes with <code>MEMORY USAGE key</code>, or run <code>redis-cli --bigkeys</code> against a non-critical instance.</li>

<li><strong>Hot keys</strong>: one key that receives a large share of traffic. Cache a copy in application memory for a few seconds, or spread the load over several keys such as <code>shop:config:1</code> to <code>shop:config:4</code>.</li>

<li><strong>Unbounded collections</strong>: a list or set that only ever grows. Trim it or give it a TTL.</li>
</ul>



<h2 class="wp-block-heading" id="aioseo-use-the-scan-vs-keys-command-guidelines">Use SCAN, not KEYS</h2>



<p class="wp-block-paragraph">The KEYS command page warns to use extreme care in production because it may ruin performance on large databases. <a href="https://redis.io/docs/latest/commands/scan/" target="_blank" rel="noopener">SCAN</a> walks the keyspace in small steps with a cursor, so other clients keep being served.</p>


<div class="wp-block-syntaxhighlighter-code ">
# avoid in production
KEYS shop:product:*

# use a cursor and a hint for the page size
SCAN 0 MATCH shop:product:* COUNT 500
</div>


<p class="wp-block-paragraph">SCAN may return the same key more than once and keys added or removed during the scan may or may not appear, so make the work per key safe to repeat. COUNT is a hint, not a limit. On a cluster each node must be scanned. See <a href="https://thecodebuzz.com/get-all-keys-from-redis-cache-in-c-net/">get all keys from Redis cache in C#.NET</a> for the .NET side.</p>



<span id="aioseo-managing-concurrency-in-a-cache"></span>



<span id="aioseo-redis-server-powerful-with-rich-query-pattern---use-lua-scripts"></span>



<h2 class="wp-block-heading" id="pipe">Pipelining and connection reuse</h2>



<p class="wp-block-paragraph">Each command costs a network round trip. Pipelining sends several commands without waiting for each reply, which cuts the waiting time for batches. In StackExchange.Redis, <code>CreateBatch()</code> does this, and plain async calls from many threads are already multiplexed over one connection.</p>



<p class="wp-block-paragraph">Connection reuse matters just as much. Opening a connection per request costs a TCP (and TLS) handshake each time. Create one <code>ConnectionMultiplexer</code>, register it as a singleton and share it. If connections drop, see <a href="https://thecodebuzz.com/connection-resiliency-redis-cache-stackexchange-redi-best-practices/">Redis connection resiliency in ASP.NET Core</a> and set <code>AbortOnConnectFail=false</code> so the client keeps retrying at start-up.</p>



<h2 class="wp-block-heading" id="persist">Persistence: RDB vs AOF</h2>



<p class="wp-block-paragraph">The <a href="https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/" target="_blank" rel="noopener">persistence documentation</a> describes the options:</p>



<ul class="wp-block-list">
<li><strong>None</strong>: fastest and simplest for a pure cache you can rebuild. Everything is lost on restart.</li>

<li><strong>RDB snapshots</strong>: compact point-in-time files, quick restarts, but changes since the last snapshot can be lost.</li>

<li><strong>AOF</strong>: logs every write. With <code>appendfsync everysec</code> (the default policy) you can lose about one second of writes; <code>always</code> is safer and slower.</li>

<li><strong>RDB + AOF</strong>: both in one instance when you need durability and fast restarts.</li>
</ul>



<p class="wp-block-paragraph">Decide from the data: a cache that can be rebuilt from the database rarely needs AOF, while Redis used as a primary store does.</p>



<h2 class="wp-block-heading" id="aioseo-redis---security-for-data">Security: auth, ACLs and TLS</h2>



<p class="wp-block-paragraph">Never expose Redis directly to the internet. The <a href="https://redis.io/docs/latest/operate/oss_and_stack/management/security/" target="_blank" rel="noopener">security documentation</a> recommends keeping it reachable only by trusted clients.</p>



<ul class="wp-block-list">
<li><strong>Network</strong>: bind to private interfaces and firewall the port.</li>

<li><strong>Authentication and ACLs</strong>: require a password and create ACL users with only the commands and key patterns each application needs, instead of sharing the default user.</li>

<li><strong>TLS</strong>: encrypt traffic between clients and server, especially across networks you do not control.</li>

<li><strong>Dangerous commands</strong>: restrict <code>FLUSHALL</code>, <code>CONFIG</code> and <code>KEYS</code> with ACLs.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code ">
ACL SETUSER shopapp on &gt;use-a-long-secret ~shop:* +get +set +del +expire +scan
</div>


<p class="wp-block-paragraph">For connection strings with TLS and passwords, see <a href="https://thecodebuzz.com/redis-connect-with-ssl-tls-using-csharp-asp-net-core/">Redis connect with SSL/TLS using C# .NET</a>. The ACL line above was not run here.</p>



<h2 class="wp-block-heading" id="monitor">Monitoring: INFO and SLOWLOG</h2>



<p class="wp-block-paragraph">Two commands answer most questions. <code>INFO</code> reports memory, clients, hit and miss counters (<code>keyspace_hits</code>, <code>keyspace_misses</code>), evictions and persistence status. <code>SLOWLOG GET 10</code> shows the slowest recent commands; the SLOWLOG GET reference notes that the time is the command execution time in microseconds and excludes network I/O.</p>


<div class="wp-block-syntaxhighlighter-code ">
redis-cli INFO memory
redis-cli INFO stats
redis-cli SLOWLOG GET 10
</div>


<ul class="wp-block-list">
<li>A falling hit ratio means TTLs are too short or keys are evicted too early.</li>

<li>Rising <code>evicted_keys</code> means memory is too small or too many keys are stored.</li>

<li>Slow entries for <code>KEYS</code>, large <code>HGETALL</code> or <code>SMEMBERS</code> point to big keys or missing SCAN.</li>
</ul>



<h2 class="wp-block-heading" id="example">Example: .NET and StackExchange.Redis</h2>



<p class="wp-block-paragraph">This program uses cache-aside with a TTL and jitter, a pipelined batch, SCAN through <code>server.KeysAsync</code> and one shared multiplexer. Create it with <code>dotnet new console</code> and <code>dotnet add package StackExchange.Redis --version 2.8.58</code>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using System.Text.Json;
using StackExchange.Redis;

// One multiplexer for the whole process: create it once and reuse it.
var options = ConfigurationOptions.Parse(&quot;localhost:6379&quot;);
options.AbortOnConnectFail = false;
options.ConnectTimeout = 5000;
using var mux = await ConnectionMultiplexer.ConnectAsync(options);
IDatabase db = mux.GetDatabase();

// Cache-aside: read the cache, on a miss load from the source and store with a TTL.
async Task&lt;Product?&gt; GetProductAsync(int id)
{
    string key = $&quot;shop:product:{id}&quot;;
    RedisValue cached = await db.StringGetAsync(key);
    if (cached.HasValue)
        return JsonSerializer.Deserialize&lt;Product&gt;((string)cached!);

    Product? fromDb = await LoadFromDatabaseAsync(id);   // your real data source
    if (fromDb is not null)
    {
        // Add random jitter so many keys do not expire at the same second.
        var ttl = TimeSpan.FromMinutes(10) + TimeSpan.FromSeconds(Random.Shared.Next(0, 60));
        await db.StringSetAsync(key, JsonSerializer.Serialize(fromDb), ttl);
    }
    return fromDb;
}

Task&lt;Product?&gt; LoadFromDatabaseAsync(int id) =&gt;
    Task.FromResult&lt;Product?&gt;(new Product(id, $&quot;Item {id}&quot;, 9.99m));

Console.WriteLine((await GetProductAsync(1))?.Name);   // miss, then cached
Console.WriteLine((await GetProductAsync(1))?.Name);   // hit

// Pipelining: queue commands and wait once for all replies.
var batch = db.CreateBatch();
var tasks = Enumerable.Range(1, 100)
    .Select(i =&gt; batch.StringSetAsync($&quot;shop:counter:{i}&quot;, i, TimeSpan.FromMinutes(5)))
    .ToArray();
batch.Execute();
await Task.WhenAll(tasks);

// SCAN instead of KEYS: Keys() uses SCAN on servers that support it.
IServer server = mux.GetServer(mux.GetEndPoints()&#x5B;0]);
int count = 0;
await foreach (var k in server.KeysAsync(pattern: &quot;shop:counter:*&quot;, pageSize: 250))
    count++;
Console.WriteLine($&quot;counters: {count}&quot;);

record Product(int Id, string Name, decimal Price);
</pre></div>


<p class="wp-block-paragraph">Status: this sample compiled with no warnings or errors on .NET 10. It was <strong>not run</strong>, because no Redis server was available in the test environment, so the console output is not shown. Run it against a local Redis and check that the second lookup prints without calling your data source.</p>



<h2 class="wp-block-heading" id="trouble">Common mistakes and fixes</h2>



<ul class="wp-block-list">
<li><strong>Memory keeps growing</strong>: keys have no TTL or <code>maxmemory</code> is unset. Add TTLs and a limit.</li>

<li><strong>Writes fail with an OOM error</strong>: the policy is <code>noeviction</code> and memory is full. Use an <code>allkeys-*</code> policy for a cache.</li>

<li><strong>Latency spikes</strong>: check SLOWLOG for <code>KEYS</code> and big keys.</li>

<li><strong>Many connections</strong>: a connection is created per request. Share one multiplexer.</li>

<li><strong>Database load spikes at regular times</strong>: many keys expire together. Add jitter.</li>
</ul>



<h2 class="wp-block-heading" id="faq">Frequently asked questions</h2>



<h3 class="wp-block-heading">What are the most important Redis best practices?</h3>



<p class="wp-block-paragraph">Use consistent key names, set a TTL on cache keys, set maxmemory with an eviction policy, avoid big keys and the KEYS command, reuse one connection, and secure access with authentication, ACLs and TLS.</p>



<h3 class="wp-block-heading">What are Redis key naming best practices?</h3>



<p class="wp-block-paragraph">Use a colon-separated pattern such as app:entity:id, start with a namespace, keep names short but readable, add a version when the stored shape changes, and avoid secrets or personal data in key names.</p>



<h3 class="wp-block-heading">Should I use KEYS or SCAN in production?</h3>



<p class="wp-block-paragraph">Use SCAN. KEYS walks the whole keyspace in one command and can block other clients on a large database, while SCAN returns results in small steps with a cursor. Make the per-key work safe to repeat because SCAN can return duplicates.</p>



<h2 class="wp-block-heading" id="summary">Summary</h2>



<p class="wp-block-paragraph">Name keys consistently, choose the structure for your most common operation, give every cache key a TTL, bound memory with an eviction policy, and read through cache-aside. Avoid big keys, hot keys and KEYS, reuse one connection, pick persistence on purpose, restrict access with ACLs and TLS, and watch INFO and SLOWLOG. Tested here: the C# sample compiled on .NET 10 with StackExchange.Redis 2.8.58, and the documentation claims were checked against the official Redis docs. Not tested: running the sample against a live Redis server, the ACL command, Redis Cluster and managed services, and .NET 8 or 9.</p>



<div class="wp-block-group has-background" style="border-radius:8px;background-color:#b6d9ac;padding-top:20px;padding-right:24px;padding-bottom:20px;padding-left:24px"><div class="wp-block-group__inner-container is-layout-constrained wp-container-core-group-is-layout-0d2d72cd wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph" style="font-size:20px"><strong>Found this useful?</strong></p>



<p class="wp-block-paragraph">Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.</p>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noopener">Subscribe to TheCodeBuzz</a></div>
</div>
</div></div>



<script type="application/ld+json">{"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "What are the most important Redis best practices?", "acceptedAnswer": {"@type": "Answer", "text": "Use consistent key names, set a TTL on cache keys, set maxmemory with an eviction policy, avoid big keys and the KEYS command, reuse one connection, and secure access with authentication, ACLs and TLS."}}, {"@type": "Question", "name": "What are Redis key naming best practices?", "acceptedAnswer": {"@type": "Answer", "text": "Use a colon-separated pattern such as app:entity:id, start with a namespace, keep names short but readable, add a version when the stored shape changes, and avoid secrets or personal data in key names."}}, {"@type": "Question", "name": "Should I use KEYS or SCAN in production?", "acceptedAnswer": {"@type": "Answer", "text": "Use SCAN. KEYS walks the whole keyspace in one command and can block other clients on a large database, while SCAN returns results in small steps with a cursor. Make the per-key work safe to repeat because SCAN can return duplicates."}}]}</script><p>The post <a href="https://thecodebuzz.com/redis-cache-best-practices-development/">Redis Best Practices for Development: Keys, Expiry, Security</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/redis-cache-best-practices-development/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Redis Connect with SSL/TLS using C# .NET</title>
		<link>https://thecodebuzz.com/redis-connect-with-ssl-tls-using-csharp-asp-net-core/</link>
					<comments>https://thecodebuzz.com/redis-connect-with-ssl-tls-using-csharp-asp-net-core/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 21 Sep 2021 22:51:00 +0000</pubDate>
				<category><![CDATA[Redis]]></category>
		<category><![CDATA[Redis SSL connection]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=18727</guid>

					<description><![CDATA[<p>Redis connect with SSL/TLS using C# .NET Today in this article we shall see how to enable Redis connect with SSL certificate using C# .NET application. Install StackExchange.Redis&#160; Please install the Redis NuGet package Microsoft.Extensions.Caching.StackExchangeRedis as below, PM>Install-Package Microsoft.Extensions.Caching.StackExchangeRedis -Version &#60;version> Or using .NET CLI dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis --version 5.0.1 Console application with Redis [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/redis-connect-with-ssl-tls-using-csharp-asp-net-core/">Redis Connect with SSL/TLS using C# .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading" id="aioseo-redis-connect-with-ssl-using-c-net">Redis connect with SSL/TLS using C# .NET</h1>



<figure class="wp-block-image size-full is-resized"><img fetchpriority="high" decoding="async" width="784" height="688" src="https://www.thecodebuzz.com/wp-content/uploads/2022/11/Redis-SSL.jpg" alt="" class="wp-image-24173" style="width:262px;height:230px" srcset="https://thecodebuzz.com/wp-content/uploads/2022/11/Redis-SSL.jpg 784w, https://thecodebuzz.com/wp-content/uploads/2022/11/Redis-SSL-300x263.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/11/Redis-SSL-768x674.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/11/Redis-SSL-593x520.jpg 593w" sizes="(max-width: 784px) 100vw, 784px" /></figure>



<p class="wp-block-paragraph">Today in this article we shall see how to enable Redis connect with SSL certificate using C# .NET application.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="installing-stackexchangeredis">Install StackExchange.Redis&nbsp;</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph" id="block-4161c405-d64c-4900-87b3-4bfcf3a14725">Please install the <strong><em>Redis </em></strong>NuGet package <a href="https://www.nuget.org/packages/Microsoft.Extensions.Caching.StackExchangeRedis/5.0.1" target="_blank" rel="noreferrer noopener">Microsoft.Extensions.Caching.StackExchangeRedis</a></p>



<p class="wp-block-paragraph" id="block-4161c405-d64c-4900-87b3-4bfcf3a14725"> as below,</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-preformatted">PM>Install-Package<a href="https://www.nuget.org/packages/Microsoft.Extensions.Caching.StackExchangeRedis/5.0.1" target="_blank" rel="noreferrer noopener"> Microsoft.Extensions.Caching.StackExchangeRedis</a> -Version &lt;version>
</pre>



<p class="wp-block-paragraph">Or using .NET CLI</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-preformatted has-medium-font-size">dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis --version 5.0.1</pre>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-console-application-with-redis-ssl"><strong>Console application with Redis SSL</strong></h2>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-syntaxhighlighter-code">            var configurationOptions = new ConfigurationOptions
            {
                EndPoints = { "localhost:6379" },
                Ssl = true
            };

            configurationOptions.CertificateSelection += delegate {
                var cert = new X509Certificate2(PATH_TO_CERT_FILE, "");
                return cert;
            };


            var redis = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
            Console.WriteLine(redis.GetDatabase().Ping());
        
    </pre>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><strong><em>ConfigurationOptions </em></strong>let&#8217;s you specify SSL property using the property &#8220;Ssl&#8221;. Please set this as true.</li>
</ul>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li>PATH_TO_CERT_FILE is the location of the <strong><em>X509Certificate2 </em></strong>certificate file on the server. </li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong>Example</strong>&#8211;   &#8220;c:\\cert\\path\\CERT.pfx&#8221;;</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">If using the ASP.NET Core application below is a sample that can be used to specify the certificate file.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">If using the cloud with docker, please specify the docker file with the certificate location.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-asp-net-core-example-for-redis-ssl"><strong>ASP.NET Core example for Redis SSL </strong></h2>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-syntaxhighlighter-code">public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddScoped&lt;ISalaryRepository, SalaryRepository>();
            services.AddDbContext&lt;EmployeeContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("EmployeeDB"),
                sqlServerOptionsAction: sqlOptions =>
                {
                    sqlOptions.EnableRetryOnFailure();
                });
            });
 
            if (_hostEnvironment.IsDevelopment())
            {
                services.AddDistributedMemoryCache();//Use this for only DEV testing purpose
            }
            else
            {
               var configurationOptions = new ConfigurationOptions
                {
                    EndPoints = { $"{Configuration.GetValue&lt;string>("RedisCache:Host")}:{Configuration.GetValue&lt;int>("RedisCache:Port")}" },
                    Ssl = true,
                };
                configurationOptions.CertificateSelection += delegate
                {
                    var cert = new X509Certificate2(Configuration.GetValue&lt;string>("RedisCache:CertificatePath"), "");
                    return cert;
                };
                var multiplexer = ConnectionMultiplexer.Connect(configurationOptions); ;
                
                services.AddSingleton&lt;IConnectionMultiplexer>(multiplexer);
            }
</pre>



<p class="wp-block-paragraph"> </p>



<p class="wp-block-paragraph">In a case using a self-signed certificate, then please make sure to install the certificate on your server.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong><em>References</em></strong>: </p>



<p class="wp-block-paragraph"></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/redis-distributed-cache-asp-net-core-csharp-redis-examples/" title="Redis Distributed cache in .NET with examples" target="_blank" rel="noreferrer noopener"><strong><em>Redis Distributed cache in .NET with examples</em></strong></a></li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph" style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size wp-block-paragraph"></p>



<p class="wp-block-paragraph" style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size wp-block-paragraph"></p>



<p class="has-medium-font-size wp-block-paragraph"><strong>Happy Coding </strong>!!</p>



<p class="wp-block-paragraph"></p>



<hr>



<p class="wp-block-paragraph"></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2026) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p><p>The post <a href="https://thecodebuzz.com/redis-connect-with-ssl-tls-using-csharp-asp-net-core/">Redis Connect with SSL/TLS using C# .NET</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/redis-connect-with-ssl-tls-using-csharp-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Publish and Subscribe messages with Redis &#8211; C# .NET Core</title>
		<link>https://thecodebuzz.com/redis-publish-subscribe-messages-redis-net-core-csharp/</link>
					<comments>https://thecodebuzz.com/redis-publish-subscribe-messages-redis-net-core-csharp/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 19 Sep 2021 22:34:00 +0000</pubDate>
				<category><![CDATA[Redis]]></category>
		<category><![CDATA[c# redis set]]></category>
		<category><![CDATA[pub sub redis]]></category>
		<category><![CDATA[pub/sub in .net core]]></category>
		<category><![CDATA[Publish Subscribe Redis]]></category>
		<category><![CDATA[Redis .NET]]></category>
		<category><![CDATA[Redis .NET Core]]></category>
		<category><![CDATA[redis pub/sub protocol]]></category>
		<category><![CDATA[redis pub/sub queue]]></category>
		<category><![CDATA[redis queue .net core]]></category>
		<category><![CDATA[redis subscribe to key]]></category>
		<category><![CDATA[stackexchange redis pub/sub]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=18767</guid>

					<description><![CDATA[<p>Publish and Subscribe messages with Redis &#8211; C# .NET Core Today in this article, we shall see how to Publish and Subscribe messages with Redis using C# .NET Core. Redis is widely regarded as the most efficient cache tool for stateless back-end app servers. Many people are however unaware that apart from an excellent cache [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/redis-publish-subscribe-messages-redis-net-core-csharp/">Publish and Subscribe messages with Redis – C# .NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Publish and Subscribe messages with Redis &#8211; C# .NET Core</h1>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="530" src="https://www.thecodebuzz.com/wp-content/uploads/2021/10/redis-publish-subscribe-net-core-c-example-1-1024x530.jpg" alt="Publish and Subscribe messages with Redis" class="wp-image-18801" srcset="https://thecodebuzz.com/wp-content/uploads/2021/10/redis-publish-subscribe-net-core-c-example-1-1024x530.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/10/redis-publish-subscribe-net-core-c-example-1-300x155.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/10/redis-publish-subscribe-net-core-c-example-1-768x398.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/10/redis-publish-subscribe-net-core-c-example-1-1536x795.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2021/10/redis-publish-subscribe-net-core-c-example-1-2048x1060.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2021/10/redis-publish-subscribe-net-core-c-example-1-785x406.jpg 785w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p class="wp-block-paragraph">Today in this article, we shall see how to Publish and Subscribe messages with Redis using C# .NET Core.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"> Redis is widely regarded as the most efficient cache tool for stateless back-end app servers. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Many people are however unaware that apart from an excellent cache server, it also provides built-in Publishing / Subscribe / Messaging functionality helping developers create event-driven based applications, microservices, etc. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Today in this article, we will cover below aspects,</p>



<p class="wp-block-paragraph"></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-started">Getting started</a></li><li><a href="#aioseo-publish-subscribe-messages-with-redis-subscriber-example-c">Publish/Subscribe messages with Redis &#8211; subscriber example C#</a></li><li><a href="#aioseo-publish-subscribe-messages-with-redis-publisher-example-c">Publish/Subscribe messages with Redis &#8211; Publisher example c#</a></li></ul></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Today in this article, we shall try to cover the basics pub-sub model and how to get started.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-getting-started">Getting started</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Let&#8217;s start creating&nbsp;<strong>.NET Core</strong>&nbsp;console application as below,</p>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="182" src="https://www.thecodebuzz.com/wp-content/uploads/2021/10/redis-net-core-csharp-c-console-app-1024x182.jpg" alt="Redis subscriber example C#" class="wp-image-18798" srcset="https://thecodebuzz.com/wp-content/uploads/2021/10/redis-net-core-csharp-c-console-app-1024x182.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2021/10/redis-net-core-csharp-c-console-app-300x53.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2021/10/redis-net-core-csharp-c-console-app-768x137.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2021/10/redis-net-core-csharp-c-console-app-1536x273.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2021/10/redis-net-core-csharp-c-console-app-2048x364.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2021/10/redis-net-core-csharp-c-console-app-785x140.jpg 785w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph" id="block-4161c405-d64c-4900-87b3-4bfcf3a14725">Please install the&nbsp;<strong><em>Redis&nbsp;</em></strong>NuGet package&nbsp;<a href="https://www.nuget.org/packages/Microsoft.Extensions.Caching.StackExchangeRedis/5.0.1" target="_blank" rel="noreferrer noopener"><em><strong>Microsoft.Extensions.Caching.StackExchangeRedis</strong></em></a></p>



<p class="wp-block-paragraph" id="block-4161c405-d64c-4900-87b3-4bfcf3a14725">as below,</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-preformatted has-medium-font-size"><strong>> Install-Package<a href="https://www.nuget.org/packages/Microsoft.Extensions.Caching.StackExchangeRedis/5.0.1" target="_blank" rel="noreferrer noopener"> Microsoft.Extensions.Caching.StackExchangeRedis</a> -Version </strong>&lt;version></pre>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-publish-subscribe-messages-with-redis-subscriber-example-c">Publish/Subscribe messages with Redis &#8211; subscriber example C#</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Below shows a simple example for Redis subscribers.</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-syntaxhighlighter-code">            using ConnectionMultiplexer redis = 
            ConnectionMultiplexer.Connect(redisConnectionString);
            ISubscriber subScriber = redis.GetSubscriber();
            //Subscribe to the channel "thecode-buzz-channel"
            subScriber.Subscribe(publishChannel, (channel, message) =>
            {
                //Output received message
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}]: {$"Message {message} received successfully"}");
            });</pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Above we are using the <strong><em>ConnectionMultiplexer interface to create </em></strong>subscriber objects to subscribe to the name channel.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading" id="aioseo-publish-subscribe-messages-with-redis-publisher-example-c">Publish/Subscribe messages with Redis &#8211; Publisher example c#</h2>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Below shows a simple example for Redis  Publisher,</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-syntaxhighlighter-code">            using ConnectionMultiplexer redis = 
            ConnectionMultiplexer.Connect(redisConnectionString);
            ISubscriber sub = redis.GetSubscriber();
            for (int i = 0; i &lt;= 10; i++)
            {
                sub.Publish(publishChannel, $"Message {i}");
                Console.WriteLine($"Message {i} published successfully");
                Thread.Sleep(2000);
            }</pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong><em>ConnectionMultiplexer </em>lets you create publisher</strong> objects to create a publisher which can publish the business events to the registered named channel.</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">For example, we are simply publishing 10 messages to the Redis channel. </p>



<p class="wp-block-paragraph"></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="320" height="180" src="https://www.thecodebuzz.com/wp-content/uploads/2021/10/gif.gif" alt="Redis Publisher example c#" class="wp-image-18802" style="width:457px;height:257px"/></figure>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">All the clients which are subscribed for the updates will receive updates when the message is published to the channel successfully.</p>



<p class="wp-block-paragraph"></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong><em>ConnectionMultiplexer </em></strong>interface can be used via <em><strong>dependency injection </strong></em>providing better control on lifetime management of the instance. Please visit <em><a href="https://www.thecodebuzz.com/redis-dependency-injection-connectionmultiplexer-redis-cache-netcore-csharp/" target="_blank" rel="noreferrer noopener" title="Redis-Dependency Injection of the ConnectionMultiplexer – Best Practices"><strong>this </strong></a></em>article for more details.</p>
</blockquote>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><strong><em>References: </em></strong></p>



<p class="wp-block-paragraph"></p>



<ul class="has-medium-font-size wp-block-list">
<li><a href="https://www.thecodebuzz.com/kafka-asp-net-core-event-driven-microservices/" title="Getting Started with Kafka in ASP.NET Core" target="_blank" rel="noreferrer noopener"><strong><em>Getting Started with Kafka in ASP.NET Core</em></strong></a></li>
</ul>



<ul class="has-medium-font-size wp-block-list">
<li><a href="https://www.thecodebuzz.com/redis-dependency-injection-connectionmultiplexer-redis-cache-netcore-csharp/" target="_blank" rel="noreferrer noopener" title="Redis-Dependency Injection of the ConnectionMultiplexer – Best Practices"><strong><em>Redis-Dependency Injection of the ConnectionMultiplexer</em></strong></a></li>
</ul>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">That&#8217;s all! Happy coding!</p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Does this help you fix your issue? </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Do you have any better solutions or suggestions? Please sound off your comments below.</p>



<p class="wp-block-paragraph"></p>



<hr>



<p class="wp-block-paragraph"></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2026) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p><p>The post <a href="https://thecodebuzz.com/redis-publish-subscribe-messages-redis-net-core-csharp/">Publish and Subscribe messages with Redis – C# .NET Core</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/redis-publish-subscribe-messages-redis-net-core-csharp/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
