RedisConnectionException at each first Connect(), while redis-py and hiredis work fine
Hi Marc,
Version 1.0.289.0 (nuget, .net 4.0).
When I leave my workstation alone for five minutes, after calling Connect() I get a RedisConnectionException the first time. Immediately retrying does work with no delay at a 90% success rate. No info is written to the supplied TextWriter.
var oCli = ConnectionMultiplexer.Connect("srv-flux-01:14144", log);
Complete exception message:
An unhandled exception of type 'StackExchange.Redis.RedisConnectionException' occurred in StackExchange.Redis.dll
Additional information: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail
I connect from Win7 Pro X64 to Redis 2.8.9 (x64) on a Debian machine on our LAN (same subnet). No hardware firewalls in between, only Windows firewall. Redis connections from redis-py or RedisDesktopManager(which uses hiredis) never fail, and always connect within milliseconds.
I use a simple Windows Forms project, VS2013 Express, for testing. I use (and need) the .NET Framework 4 Client Profile.
Any ideas?
Kind regards, TW
I was never able to come up with a real solution to this problem so I ended up creating a 'WatchDog' timer which performs a write operation every 30 seconds and re-initializes the ConnectionMultiplexer if the operation fails. Seems to be working pretty well, haven't had a single outage caused by this since the timer was put in place.
Just saw this in production twice.
My team and I just noticed a correlation between our web servers having connection issues with Redis (No Connections Available / Timeouts) and Redis saving snapshots of itself.
After a little digging I stumbled on this gem on http://redis.io/topics/persistence

For our application we don't need persistence so I'm just disabling it altogether, but might be worth looking into as a potential cause or if it's tied to the difficulty with reproducing the issue.
I'll post again if the errors show again with persistence disabled
Unfortunately I am still seeing the issue relatively frequently
I've the same problem. I'm using Azure redis cache as a session provider: "Exception": { "ClassName": "StackExchange.Redis.RedisConnectionException", "Message": "No connection is available to service this operation: EXISTS xxxx, "Data": { "redis-command": "EXISTS xxxx" },
Where xxxx is an arbitrary key.
Checking on this issue, as we're seeing it in production as well (Azure Redis cache). Has there been progress made on determining a fix? Or is first opening a dummy connection still the accepted workaround?
Do you really have any workaround? We can't use on azure last two months. We stop to use it. 30 Ara 2015 00:35 tarihinde "swmech" [email protected] yazdı:
Checking on this issue, as we're seeing it in production as well (Azure Redis cache). Has there been progress made on determining a fix? Or is opening a dummy connection first still the accepted workaround?
— Reply to this email directly or view it on GitHub.
Marc, I have a unit test for you that can reproduce the issue. Attaching screenshot of error, and unit test below. In the unit test, if you dial back the number of threads below 30 (on my host) there are no issues. If you turn it up over 50, the errors begin.
Looks like line 771 in ConnectionMultiplexer (task.wait) is timing out. Its not that the connection timeout occurs - rather, the task never starts (deadlock / depletion?). The error materializes as a connection error, but its really the task not starting. The breakpoint in the lamda on line 767 never gets hit / task never starts.
** Edited the test to force the issue more reliably - ** I know there should be only one multiplexer (unit test news one up each time). ** But I just wanted to force the condition to illustrate thread pool depletion, materializing the error.
Hope this helps, and thanks, Steve

[Test]
public void CanSetAndGetItemsAcrossThreads()
{
var opts = ConfigurationOptions.Parse("localhost:6379");
opts.ConnectTimeout = 10000;
opts.SyncTimeout = 10000;
List<Task> tasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
var task = Task.Run(() =>
{
using (var conn = ConnectionMultiplexer.Connect(opts, Console.Out))
{
var str = Guid.NewGuid().ToString();
var redis = conn.GetDatabase(0);
redis.StringSet(str, str);
redis.StringSet(str, str);
}
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Test Completed");
}
So I ran into this issue as well. After reading through some of the comments and taking a look at the code, I noticed an unnecessary indirection in ConnectionMultiPlexer.ConnectImpl which appears to be causing a deadlock:
// note that task has timeouts internally, so it might take *just over* the regular timeout
// wrap into task to force async execution
var task = Factory.StartNew(() => muxer.ReconfigureAsync(true, false, log, null, "connect").Result);
What's happening here is the code is spawning an async task which waits synchronously on an async task result. This is bad juju. What it appears is happening next is the code blocks the context thread waiting for the wrapper task created with Factory.StartNew to return:
if (!task.Wait(muxer.SyncConnectTimeout(true)))
When the continuation from ReconfigureAsync returns, it waits for the context thread to become available. Since the context thread is blocked waiting for the continuation, it results in deadlock. Stephen Cleary has an excellent description of the pattern on his blog.
The fix, I believe, is simple: spawn the ReconfigureAsync method directly:
// note that task has timeouts internally, so it might take *just over* the regular timeout
var task = muxer.ReconfigureAsync(true, false, log, null, "connect");
if (!task.Wait(muxer.SyncConnectTimeout(true)))
If I had to guess, I'd say ReconfigureAsync was once a synchronous method that was converted to async without updating the ConnectImpl implementation to remove the async wrapping.
The above is conjecture at this point, however in limited testing it appears to solve the problem.
Submitted as pull request #353.
I had the same issue, I implemented the rjmooney change and the problem is not happening anymore.
:+1: @rjmooney Thanks! @mgravell @NickCraver Guys this is bringing our site down once a day, can you please review and release the fix?
@aliostad please let us know if this resolves your issue after a few days?
@smiket we are deploying next week, I will keep you posted.
Is this code in any nuget releases? I've cloned latest and included and still very much seeing this in dnx on linux. redis-cli works fine, but still cant connect via stackexchange.redis
@smiket it looks like my problem had nothing to do with this. But still investigating.
@ronnyek @aliostad https://www.nuget.org/packages/StackExchange.Redis/1.1.572-alpha. What issue are you each seeing exactly?
@aliostad @rjmooney we solved our problem - but it had nothing to do with the pull request associated with this issue. Our connection errors were caused by what I outlined above (see my previous post). We were seeing the errors every day - and now we have not seen it in two weeks.
If the threadpool is drained then SE redis will not be able to connect. The reason is that it times out waiting for a thread to become available, as it tries to connect. The error indicates a connection issue, but its really thread starvation in our case (not a deadlock).
We took a hard look at our code, and found we were running several simultaneous jobs to load our cache. The jobs kick off at the same time, and each uses parallel loops etc. Lots of simultaneous, parallel loops - drained the pool.
We lightened up on parallelism, decreased the number of jobs running at same time and such. By putting less pressure on the thread pool, we solved the issue. In our case (and I suspect same for a number of other folks here) we were causing the issue. Its just unfortunate the error message is a bit misleading.
Hope it helps! Steve
@rjmooney basically in vnext with I believe that alpha, I was getting this: An unhandled exception of type 'StackExchange.Redis.RedisConnectionException' occurred in StackExchange.Redis.dll Additional information: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail on launch
only running on linux.
Same thing, although we launch multiple separate instances for a desktop (yikes!)-based WPF 4.5 app.
Issue remains when using both the latest stable, and the latest alpha versions of StackExchange.Redis from NuGet.
Maybe it's a good idea to create own threads instead of using the Managed Thread Pool?
StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. UnableToResolvePhysicalConnection on PING
at StackExchange.Redis.ConnectionMultiplexer.<ConnectAsync>d__20.MoveNext() in c:\TeamCity\buildAgent\work\3ae0647004edff78\StackExchange.Redis\StackExchange\Redis\ConnectionMultiplexer.cs:line 765
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at ZU.Storage.Redis.RedisEnvironmentManagement.<>c__DisplayClass0_0.<<CreateRedisInstance>b__0>d.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at ZU.Storage.Redis.RedisEnvironmentManagement.CreateRedisInstance(String currentFolder, Boolean showRedisInstanceCommandPrompt)
Please see http://stackoverflow.com/questions/23871110/stackexchange-redis-failing-to-connect-with-mono-in-mac-os-x ,
And I use the follows package, https://www.nuget.org/packages/StackExchange.Redis.Mono/
it solved my question.