Restoring connection to redis
Hi, there.
I use StackExchange.Redis.1.0.281.0 It is turned out that lib can't restore connection to redis in some cases.
My application executes next code every few seconds
try
{
var server = this.application.Multiplexer.GetServer(RedisServerAddress);
var keys = server.Keys(Properties.Settings.Default.BackendRedisDBId);
...............
}
catch(Exception e)
{
//log exception
}
In order to check how this code works when connection lost and restored, i just stopped Redis and started it again. Most of the time connection restored, but some times does not. The code above fails with exception until i restart Redis again. After restart lib restores connection.
I create ConnectionMultiplexer next way
var config = ConfigurationOptions.Parse(RedisServerAddress);
config.KeepAlive = 5;
config.SyncTimeout = 1000;
config.AbortOnConnectFail = false;
config.AllowAdmin = true;
var muxer = ConnectionMultiplexer.Connect(config);
muxer.ConfigurationChanged += (sender, args) => log.DebugFormat("ConfigurationChanged with endpoint: {0}", args.EndPoint);
muxer.ConfigurationChangedBroadcast += (sender, args) => log.DebugFormat("ConfigurationChangedBroadcast with endpoint: {0}", args.EndPoint);
muxer.ConnectionFailed += (sender, args) => log.DebugFormat("ConnectionFailed with args: {0}", args.Exception.Message);
muxer.ConnectionRestored += (sender, args) => log.DebugFormat("ConnectionRestored with args: {0}", args.EndPoint);
muxer.ErrorMessage += (sender, args) => log.DebugFormat("ErrorMessage with args: {0}", args.Message);
muxer.HashSlotMoved += (sender, args) => log.DebugFormat("HashSlotMoved with args: {0}", args.NewEndPoint);
muxer.InternalError += (sender, args) => log.DebugFormat("InternalError with args: {0}", args.Exception);
What information yet should i provide in order to help find reason?
I found in logs that connection was restored, but code above fails. if i debug code, i see that muxer.IsConnected returns false. log messages are:
ConfigurationChanged with endpoint: 127.0.0.1:6379
StackExchange.Redis.RedisConnectionException: No connection is available to service this operation: KEYS
I ran into the same problem, and have been attempting to get a good reproducible case. It seems it's highly intermittent, but once a ConnectionMultiplexer is broken it's broken for good, it will never reconnect without restarting the process.
For me it reconnects if i restart Redis. I even see report that connection was lost. I mean that getting keys from DB fails, because "No connection is available to service this operation: KEYS", but when i stop redis i see, that connection was lost.
I'm writing simple console application, in order to have simpler way to reproduce this behavior
it is sad, but with simple console app i failed to reproduce this behavior. All what i got this
18:39:54,200 WARN Program ConnectionFailed with args: SocketFailure on 127.0.0.1:6379/Subscription, input-buffer: 0, outstanding: 0, last-read: 2s ago, last-write: 2s ago, keep-alive: 5s, pending: 0, state: ConnectedEstablished, last-heartbeat: 0s ago, last-mbeat: 0s ago, global: 0s ago [11]
18:39:54,210 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [11]
18:39:54,212 WARN Program ConnectionFailed with args: SocketFailure on 127.0.0.1:6379/Interactive, input-buffer: 0, outstanding: 0, last-read: 2s ago, last-write: 2s ago, keep-alive: 5s, pending: 0, state: ConnectedEstablished, last-heartbeat: 0s ago, last-mbeat: 0s ago, global: 0s ago [11]
18:39:54,223 ERROR Program InternalError with args: System.NullReferenceException: ...
в StackExchange.Redis.PhysicalConnection.WriteHeader(RedisCommand command, Int32 arguments) в c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\PhysicalConnection.cs:line 379
в StackExchange.Redis.Message.CommandKeyMessage.WriteImpl(PhysicalConnection physical) в c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\Message.cs:line 734
в StackExchange.Redis.PhysicalBridge.WriteMessageToServer(PhysicalConnection connection, Message message) в c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\PhysicalBridge.cs:line 766 [11]
18:39:54,239 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [11]
I am getting something semi-reproducible by spinning up a bunch of threads with their own ConnectionMultiplexers instead of a shared one
Alright, so this is a bit of a far shot, but here's a small sample app. This will spin up some amount of threads against a given host (for my testing I used 20 threads against my test VM). I used the latest build of MSOpen redis-server 2.8.4 and latest pull from SE.Redis for this. redis-server was started with a --maxmemory 512mb parameter.
These threads will simply do busy work to simulate usage like listing keys, and getting/setting values. Each thread has a timer that checks IsConnected every second, which will then report an error if a connection does not exist. The connection restore/fail will also mark what type of connection the event handler was called on which keeps track of what connection types were restored, or went down. Curiously, I noticed that every time I was able to reproduce the problem it was the "Interactive" connection that was marked as dead this way.
I ran this test program in Debug from within Studio 2013 (I simply added a new project to the SE.Redis solution locally called Minimus). Once it's running it's a little tricky to see the behavior in question, but I've had decent luck with stopping redis-server via Ctrl-C and then starting it up after 3 seconds. This works with relative consistency on my local machine to get at least one of the threads into the weird "half-connected" state. It's not guaranteed to break on the first try though, so sometimes you have to try it a few times (kill redis-server, wait a few seconds, start it back up).
Hope this helps somewhat, and any input or feedback is more than welcome.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using StackExchange.Redis;
namespace Minimus
{
class Program
{
static void Main()
{
Trace.Listeners.Add(new ConsoleTraceListener());
Trace.AutoFlush = true;
// Spin up X number of "clients" against provided host
SpinnersUp(20, "somehost", 7777);
}
private static void SpinnersUp(int numSpinners, string host, int port)
{
foreach (var i in Enumerable.Range(0, numSpinners))
{
new Spinner(host, port, i);
}
}
}
internal class Spinner
{
protected ConnectionMultiplexer Redis { get; private set; }
private readonly string _localKey;
private readonly string _host;
private readonly int _port;
private readonly int _spinnerNumber;
private int _notConnectedTicksCount;
private readonly Dictionary<ConnectionType, bool> _aliveConnections;
public Spinner(string host, int port, int spinnerNumber)
{
_host = host;
_port = port;
_spinnerNumber = spinnerNumber;
_localKey = Guid.NewGuid().ToString(); // just wanted some unique key here
_aliveConnections = new Dictionary<ConnectionType, bool>();
var config = new ConfigurationOptions
{
AllowAdmin = true,
EndPoints = { { host, port } },
AbortOnConnectFail = false
};
Redis = ConnectionMultiplexer.Connect(config);
// Mark connection types alive/not alive for diagnostic purposes
Redis.ConnectionRestored += (sender, args) => _aliveConnections[args.ConnectionType] = true;
Redis.ConnectionFailed += (sender, args) => _aliveConnections[args.ConnectionType] = false;
var connectionWatcher = new Timer(_ => CheckConnection());
connectionWatcher.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
DoBusyWork();
}
// Called every second to check that there is a connection
private void CheckConnection()
{
// reset the counter if connection is present
if (Redis.IsConnected) {_notConnectedTicksCount = 0; return;}
_notConnectedTicksCount++;
if (_notConnectedTicksCount < 20 || _notConnectedTicksCount%20 == 0)
{
// Will dump out a list of types of connections that are not connected
Trace.TraceError("Spinner {0} (dead connections: {1}) couldn't connect for {2} ticks", _spinnerNumber,
string.Join(",", _aliveConnections.Where(x=>!x.Value).Select(x=> x.Key)), _notConnectedTicksCount);
}
}
// Just random redis chatter
public void DoBusyWork()
{
new Thread(() => Looper(() => Redis.GetServer(_host, _port).Keys().ToList())).Start();
new Thread(() => Looper(() => Redis.GetDatabase().StringGet(_localKey))).Start();
new Thread(() => Looper(() => Redis.GetDatabase().StringSet(_localKey, "value"))).Start();
}
public void Looper(Action action)
{
while (true)
{
try
{
action();
Thread.Sleep(500);
} catch { }
}
}
}
}
I managed to reproduce bug in my sample. here it is: https://dl.dropboxusercontent.com/u/27459474/StackExchangeTest.zip
It started to repeat after i created 3 thereads which use shared ConnectionMultiplexer
In my tests i use SE.Redis.1.0.281.0 and redis Redis-64.2.6.12.1 Redis started with default parameters on localhost. Windows 8.1
Way to reproduce:
- start Redis
- start sample
- stop redis. You will see log in console: GetServerList got exception. this is ok
- start redis again. Logging about exception should stop. if it does not stop than we faced problem
- repeat 3 and 4 until reproducing
I managed to reproduce after 3 start of Redis. My PC has only two cores, so may be you need more threads in case of 4 cores. Just add more ThreadPool.QueueUserWorkItem(testBody); in line 30
Hope this will help
After some testing got this error during getting keys. muxer and server are connected
ErrorMessage with args: ERR wrong number of arguments for 'mget' command
I will see what I can find
On 9 May 2014 08:18, Ilya Shvetsov [email protected] wrote:
After some testing got this error during getting keys. muxer and server are connected ''' ErrorMessage with args: ERR wrong number of arguments for 'mget' command '''
— Reply to this email directly or view it on GitHubhttps://github.com/StackExchange/StackExchange.Redis/issues/38#issuecomment-42639677 .
Regards,
Marc
Thank you
Hi, Marc I updated SE.Redis to version 1.0.289.0 now, when i connect to Redis-64 2.8.4 on windows localhost i constantly get this error message
ERR wrong number of arguments for 'mget' command
if i start Redis-64 2.6.12.1 everything works as before
Hire is one more sample, which it seems to me should work, but it does not. May be it will shade some light on what is wrong https://dl.dropboxusercontent.com/u/27459474/StackExchangeTest2.zip
Use case very simple. Start sample, it will show that it does not have connection to Redis. Start Redis. Sample still continues to show that it does not have connection to redis
if you will start redis first and than sample, connection will be established successfully
Expected by me behaviour is: After start of sample it writes that there is not connection After start redis it shold report that connection is established
I believe this is somehow connected to issue we reported here
I've experienced this issue while performing some load testing. I believe that the application attempted to establish a connection after being started. The issue was localized to a single instance of a server farm where all of the servers were configured the same. The application uses multiple threads (.net async) and a single multiplexer.
is there any news on this issue?
I'm also facing a similar issue and I use 1.0.289. I have two instances ConnectionMultiplexers configured to use 127.0.0.1:6379 (abort=false). I started the app with Redis server disconnected, then one of the multiplexers connected but the other didn't. Don't ask why I have two instances for the same server, We use different redis instances, but on our local environments we use only one endpoint..
I have the same problem,I'm trying to configure the system stability, which will behave correctly in the fall of some or all redis servers as well as could reconnect when the server is restored. But I haven't stability result, sometimes my solution work is well , but not always.
I use 3 ubuntu virtual mashines, and use events ConnectionFailed and ConnectionRestored. I noticed that the status IsConneted not always correctly updated, more precisely it can be updated in the other thread.
We want to use Redis for a big project, with big farm servers. But we cannot ensure the reliability of the system.
is there any news about this issue?
i checked last version with both my tests. and it works. This is very good news. But sometimes i see next behavior. Usualy programm gets connected immiadetly, but some times after few seconds and sometimes it notifies about connection restoring second time after long gap
12:14:48,971 INFO Program ConnectionRestored with args: 127.0.0.1:6379 [8]
12:14:48,971 INFO Program ConnectionMultiplexer.IsConnected: True [8]
12:14:48,972 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [8]
12:14:53,986 INFO Program ConnectionRestored with args: 127.0.0.1:6379 [37]
12:14:53,986 INFO Program ConnectionMultiplexer.IsConnected: True [37]
12:14:53,987 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [37]
see program StackExchageTest got two notifications about Connection restored one and five seconds later another one. this gap between notifications can be less. Some times i have only one notifciation that connection is restored, but mostly i have two notifications
12:20:18,119 INFO Program ConnectionRestored with args: 127.0.0.1:6379 [19]
12:20:18,120 INFO Program ConnectionMultiplexer.IsConnected: False [19]
12:20:18,124 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [19]
12:20:19,039 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [66]
12:20:19,041 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [63]
12:20:19,046 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [65]
12:20:19,050 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [19]
12:20:19,054 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [47]
12:20:22,051 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [19]
12:20:22,056 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [47]
12:20:22,555 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [60]
12:20:22,557 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [66]
12:20:22,578 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [65]
12:20:23,018 ERROR Program GetServerList exception:No connection is available to service this operation: KEYS [49]
12:20:23,130 INFO Program ConnectionRestored with args: 127.0.0.1:6379 [63]
12:20:23,130 INFO Program ConnectionMultiplexer.IsConnected: True [63]
12:20:23,130 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [63]
Got NullRef once
12:44:40,634 WARN Program ConnectionFailed with args: SocketFailure on 127.0.0.1:6379/Subscription, input-buffer: 0, outstanding: 0, last-read: 4s ago, last-write: 4s ago, keep-alive: 5s, pending: 0, state: ConnectedEstablished, last-heartbeat: 0s ago, last-mbeat: 0s ago, global: 0s ago [16]
12:44:40,635 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [16]
12:44:40,636 WARN Program ConnectionFailed with args: SocketFailure on 127.0.0.1:6379/Interactive, input-buffer: 0, outstanding: 0, last-read: 0s ago, last-write: 0s ago, keep-alive: 5s, pending: 0, state: ConnectedEstablished, last-heartbeat: 0s ago, last-mbeat: 0s ago, global: 0s ago [16]
12:44:40,637 ERROR Program InternalError with args: System.NullReferenceException: Reference....
в StackExchange.Redis.PhysicalConnection.WriteHeader(RedisCommand command, Int32 arguments) в c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\PhysicalConnection.cs:строка 379
в StackExchange.Redis.Message.CommandKeyMessage.WriteImpl(PhysicalConnection physical) в c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\Message.cs:строка 734
в StackExchange.Redis.PhysicalBridge.WriteMessageToServer(PhysicalConnection connection, Message message) в c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\PhysicalBridge.cs:строка 796 [16]
12:44:40,643 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [16]
12:44:40,644 INFO Program ConnectionRestored with args: 127.0.0.1:6379 [16]
12:44:40,644 INFO Program ConnectionMultiplexer.IsConnected: True [16]
12:44:40,644 INFO Program ConnectionRestored with args: 127.0.0.1:6379 [16]
12:44:40,645 INFO Program ConnectionMultiplexer.IsConnected: True [16]
12:44:40,645 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [16]
but anyway eventually connection is restored. This is good news
Question to other people, are you able to reproduce behavior from this issue? I'm not able, even after exeception connection was restored and in working state
just to be sure that you saw this. I found this null ref in 1.0.297
Got NullRef once
12:44:40,634 WARN Program ConnectionFailed with args: SocketFailure on 127.0.0.1:6379/Subscription, input-buffer: 0, outstanding: 0, last-read: 4s ago, last-write: 4s ago, keep-alive: 5s, pending: 0, state: ConnectedEstablished, last-heartbeat: 0s ago, last-mbeat: 0s ago, global: 0s ago [16]
12:44:40,635 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [16]
12:44:40,636 WARN Program ConnectionFailed with args: SocketFailure on 127.0.0.1:6379/Interactive, input-buffer: 0, outstanding: 0, last-read: 0s ago, last-write: 0s ago, keep-alive: 5s, pending: 0, state: ConnectedEstablished, last-heartbeat: 0s ago, last-mbeat: 0s ago, global: 0s ago [16]
12:44:40,637 ERROR Program InternalError with args: System.NullReferenceException: Reference....
в StackExchange.Redis.PhysicalConnection.WriteHeader(RedisCommand command, Int32 arguments) в c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\PhysicalConnection.cs:строка 379
в StackExchange.Redis.Message.CommandKeyMessage.WriteImpl(PhysicalConnection physical) в c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\Message.cs:строка 734
в StackExchange.Redis.PhysicalBridge.WriteMessageToServer(PhysicalConnection connection, Message message) в c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\PhysicalBridge.cs:строка 796 [16]
12:44:40,643 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [16]
12:44:40,644 INFO Program ConnectionRestored with args: 127.0.0.1:6379 [16]
12:44:40,644 INFO Program ConnectionMultiplexer.IsConnected: True [16]
12:44:40,644 INFO Program ConnectionRestored with args: 127.0.0.1:6379 [16]
12:44:40,645 INFO Program ConnectionMultiplexer.IsConnected: True [16]
12:44:40,645 INFO Program ConfigurationChanged with endpoint: 127.0.0.1:6379 [16]