StackExchange.Redis icon indicating copy to clipboard operation
StackExchange.Redis copied to clipboard

Safely reinitialising the multiplexer after network failure

Open tapmantwo opened this issue 8 years ago • 1 comments

We identified that if we receive RedisConnectionException with failure types of SocketFailure or SocketClosed, the multiplexer no longer works and we need to reinstantiate it.

This is tricky, because we could be in the middle of servicing many requests, and we want a singleton instance. As such, we've wrapped the calling code in a critical section, and tried to determine whether the connection has happened by another caller by looking at the IsConnected property.

A bit like this (we've taken some Lazy type optimisations out for clarity);

            if (_connection != null &&_connection.IsConnected) return;

            lock (_lock)
            {

                if (_connection == null || _connection.IsConnected == false)
                {
                    _connection?.Dispose();
                    _connection = return ConnectionMultiplexer.Connect(_options);
                }                
            }

However, we are still getting race conditions - which is if the lock is released and the next caller enters and makes the IsConnected check whilst the multiplexer is 'Connecting'.

There doesn't seem to be a way to directly determine that the servers are actually not yet connected. I note in PhysicalBridge.State has the following values Connecting, ConnectedEstablishing and ConnectedEstablished.

Is it feasible for us to find out these states, so we can change our logic to somthing like;

            if (_connection != null &&_connection.IsConnected) return;

            lock (_lock)
            {

                if (_connection == null || (_connection.IsConnected == false || _connection.IsConnecting == false))
                {
                    _connection?.Dispose();
                    _connection = return ConnectionMultiplexer.Connect(_options);
                }                
            }

I'm happy to submit a PR for a IsConnecting method or similar on ConnectionMultiplexer, or take advice on better options :)

Thanks

Richard

tapmantwo avatar Feb 19 '18 16:02 tapmantwo

Added in #803, thanks again for the contribution!

NickCraver avatar May 27 '18 21:05 NickCraver