Skip to content

Simple Hostname Failover - #2771

Closed
mintsoft wants to merge 1 commit into
npgsql:devfrom
mintsoft:pr-1764-redo
Closed

mintsoft wants to merge 1 commit into
npgsql:devfrom
mintsoft:pr-1764-redo

Conversation

@mintsoft

@mintsoft mintsoft commented Dec 27, 2019 •

Copy link
Copy Markdown
Contributor

Hiya @roji ,

I'm stealing bits from: #1764 and playing around with the best way to get this to all blend together. I'm super-keen to get this functionality in as it'll make our failover handling so much smoother than it is currently!

This is the basic extension to the host connection so that it now supports Host=PG1,PG2 functionality in the same way as it previously supported mulitple IP addresses returned from an A record.

Thanks!
Rob

Test application is here: https://github.com/mintsoft/npgsqlTester/blob/master/Program.cs

@mintsoft mintsoft changed the title WIP: Multiple hosts in connection string Simple Hostname Failover Dec 28, 2019
@mintsoft

mintsoft commented Dec 28, 2019 •

Copy link
Copy Markdown
Contributor Author

I've thrown all that away now and switched to the simplest connection failover implementation I could come up with. It works with both the pooled and non-pooled connection paths.

@mintsoft

Copy link
Copy Markdown
Contributor Author

@roji Apologies for cluttering up things, I think I've got the bones of the pool-based implementation discussed in #732 in another branch. I'm struggling with 1 thing to get the primary/secondary detection working reliably.

Basically I have only an NpgsqlConnector (called npgsqlConnector) and need to run a query and get a result (I can't find anywhere that actually does this without resorting to an NpgsqlConnection & Command, when I try that, it causes NRE's in other bits of the code).

npgsqlConnector.WriteQuery("SELECT pg_is_in_recovery()");
npgsqlConnector.Flush();

var columnMessage = npgsqlConnector.ReadMessage();
var rowMessage = npgsqlConnector.ReadMessage() as DataRowMessage;

This does seem to actually work, I can see from PG that it runs the query.
But how do I read the result set?

Everything I've tried (adding a connection, setting .Connector; newing up an NpgsqlDataReader) throws a NRE the next time that the connector is used so I'm clearly abusing the state somehow but I just can't see it. If you point me to towards an example of that happening somewhere else that I've missed I'd be very grateful :)

@mintsoft

mintsoft commented Jan 1, 2020

Copy link
Copy Markdown
Contributor Author

I think I've got something that works in the end, but it seems like I'm doing piles of work I shouldn't really be:

npgsqlConnector.StartUserAction();
npgsqlConnector.WriteQuery("SELECT pg_is_in_recovery()");
npgsqlConnector.Flush();
                
var columnsMsg = npgsqlConnector.ReadMessage();
var rowMsg = (DataRowMessage)(npgsqlConnector.ReadMessage());
                
var columnCount = npgsqlConnector.ReadBuffer.ReadInt16();
var lengthOfColumnValue = npgsqlConnector.ReadBuffer.ReadInt32();
var buffer = new byte[lengthOfColumnValue];
npgsqlConnector.ReadBuffer.ReadBytes(buffer, 0, lengthOfColumnValue);

returnStatus = buffer[0] == 'f' ? ServerType.Primary : ServerType.Secondary;
                
npgsqlConnector.SkipUntil(BackendMessageCode.ReadyForQuery);
npgsqlConnector.EndUserAction();

@roji

roji commented Jan 2, 2020

Copy link
Copy Markdown
Member

@mintsoft I think you haven't pushed your implementation proposal so I can't really see what your doing. But you're right that the way things are currently set up, in order to run a command and get a reader you need an NpgsqlConnection - a connector is not enough. This is because a lot of the execution and reading logic is spread around NpgsqlCommand (which requires an NpgsqlConnection) and NpgsqlDataReader.

The question is, when exactly do you intend to send the primary/secondary query? If it's at physical connection open, then you should already have an NpgsqlConnection associated to the connector, and can execute on that. That would be very similar to how we perform type loading the first time we connect to a server - we simply execute a command on the connection, as if we were a normal user.

If you're looking to also execute this query when the connection is idle in the pool (like a keepalive), things are a bit more complicated. I may do a refactor soon, for other purposes, which would more cleanly separate things and allow commands and readers to be executed on bare connectors, but that's not how things work at the moment.

Either way, before going forward with more implementation, could you write up a small design with exactly what you intend to implement here? Nothing formal, just a quick description we can use to make sure we're aligned etc.

@mintsoft

mintsoft commented Jan 3, 2020

Copy link
Copy Markdown
Contributor Author

@roji Yeah that's basically what seemed to come out of it with enough fighting!

What I'm building up is based on what we've discussed in #732. Basically I'm going to aim for TargetServerType=Primary or Secondary for now. I want to change it so that a Connector is maintained as the physical connection to the backend and associated with a ConnectionPool. However I think the ConnectionPool will need to be tweaked somewhat so that we have something along the lines of PoolManager.For(connectionString, serverType); which will actually wrap the existing connection pools as is; then I'll slot in another "cache" or state system (ServerStateManager or something) to maintain the known state of a given postgresql server (Probably a concurrent dictionary of server+port -> "State" which would be Primary,Secondary,Down) which the PoolManager will use to choose the correct pool.

I'm planning to have the ServerStateManager get updated on every new backend connection and every Keepalive (this is what I was fighting with reading from a Connector for, the query has gone from SELECT NULL to SELECT pg_is_in_recovery()). If this is updated by every instance and access to the pools is controlled through this, then I figure that the first connection to find out that a server has been promoted or crashed or something can update the global state and we can switch other consumers to use the other pool asap.

This feels like it's also better for handling of "down" servers as previously, withoutkeepalives, if you restart the physical postgresql server the client application would need to run and experience n errors (n being the number of pooled connections) before it would retry (at least that's my experience under 3.x); under this implementation it'd be able to invalidate all those connections at once.

My only concern is going to be the pooling performance as there might be a hit caused by the state sharing through 1 concurrentdictionary; however I'll try and do some benchmarking to see if it has any measurable effect.

I think I'm reasonably close to getting this implementation working (i.e. functional but rough) and I'll open another PR to see what you think. I'm not really sold on any part of the implementation detail at all currently so I'm happy to rewrite it entirely if you disagree with anything.

@roji

roji commented Jan 4, 2020

Copy link
Copy Markdown
Member

However I think the ConnectionPool will need to be tweaked somewhat so that we have something along the lines of PoolManager.For(connectionString, serverType); which will actually wrap the existing connection pools as is; then I'll slot in another "cache" or state system (ServerStateManager or something) to maintain the known state of a given postgresql server (Probably a concurrent dictionary of server+port -> "State" which would be Primary,Secondary,Down) which the PoolManager will use to choose the correct pool.

Hmm, interesting... do you mean you intend to keep a separate pool for each specific host (as things are now), and then some sort of added layer above that dispatches to primaries/secondaries? This could be a good way to approach this. But does this mean that the same pool is shared for the following two connection strings:

  1. Host=x;Database=bla;Username=bla;Password=bla, and
  2. Host=x,y;Database=bla;Username=bla;Password=bla

In other words, if we decompose a connection string with multiple hosts to multiple one-host connection strings (and therefore also pools), we end up sharing this way. I'm not sure whether this is good or bad, but it's definitely somewhat unexpected - currently any change in the connection string implies a different pool.

Instead of an additional cache (implying an additional lookup), the up/down/primary/secondary information could simply be stored on

This feels like it's also better for handling of "down" servers as previously, withoutkeepalives, if you restart the physical postgresql server the client application would need to run and experience n errors (n being the number of pooled connections) before it would retry (at least that's my experience under 3.x); under this implementation it'd be able to invalidate all those connections at once.

If I understand you correctly, you're saying that since you'd be grouping all connections to a given server together, a failure on one of them would allow you to immediately invalidate all them. That's indeed an interesting idea, although I'm not completely convinced - some failures would still bubble out as connections are handed out just as the first failure(s) are being thrown. So this would reduce the failures from n to some smaller number, but not eliminate them - this seems to have limited value (i.e. user code still has to deal with them with some retry mechanism etc).

More generally, I'm now looking at some pretty radical changes to the connection pool, for simplicity and perf reasons (multiplexing), so I'm hoping you're not doing too much work that's tied to the current design. I can also look into making an NpgsqlConnector autonomous, i.e. so that you can execute commands on it directly without an NpgsqlConnection, and get a reader (for the keepalive).

@mintsoft

mintsoft commented Jan 4, 2020

Copy link
Copy Markdown
Contributor Author

@roji

Hmm, interesting... do you mean you intend to keep a separate pool for each specific host (as things are now), and then some sort of added layer above that dispatches to primaries/secondaries? This could be a good way to approach this. But does this mean that the same pool is shared for the following two connection strings:

That wasn't going to be the intention (although it might have ended up like that if I think about it); it was more that there would be multiple pools everywhere where there is currently 1 (one for primary, one for secondary)

So this would reduce the failures from n to some smaller number, but not eliminate them - this seems to have limited value (i.e. user code still has to deal with them with some retry mechanism etc).

True, except in the case where you have connectionpooling but low query frequency. It would permit the keepalives to quietly move the connection pools from broken connections to working ones without the application tier noticing.

More generally, I'm now looking at some pretty radical changes to the connection pool, for simplicity and perf reasons (multiplexing), so I'm hoping you're not doing too much work that's tied to the current design. I can also look into making an NpgsqlConnector autonomous, i.e. so that you can execute commands on it directly without an NpgsqlConnection, and get a reader (for the keepalive).

That sounds interesting, I've had a few stabs at attacking the ConnectionPool and not really found a path I like with any of them so far. I'll push up what I've got into a different branch as it's currently "working", however there's still an unsolved problem of the pool getting poisoned with the wrong type of connections in failover scenarios, however I've not had to change the pool itself in this implementation and see what you think the best way of kicking it about is?

@roji

roji commented Jan 5, 2020

Copy link
Copy Markdown
Member

So this would reduce the failures from n to some smaller number, but not eliminate them - this seems to have limited value (i.e. user code still has to deal with them with some retry mechanism etc).

True, except in the case where you have connectionpooling but low query frequency. It would permit the keepalives to quietly move the connection pools from broken connections to working ones without the application tier noticing.

In general, IMHO changes which reduce error frequency but don't eliminate them are problematic; one could even say they make the situation worse by masking the real issue (which is the application not dealing failure, e.g. by using a retry strategy). In other words, an error that happens 100% of cases is usually preferable to one that happens in 10%, as it makes sure it is fixed or handled properly.

If you're able to proceed without touching the pool (for now), that's good - as I'm actively working on it (a PR maybe land this week, changing the pool in a significant way). I'll try to find time to review your PR, although realistically that may take some time.

@mintsoft

mintsoft commented Jan 5, 2020

Copy link
Copy Markdown
Contributor Author

In general, IMHO changes which reduce error frequency but don't eliminate them are problematic; one could even say they make the situation worse by masking the real issue (which is the application not dealing failure, e.g. by using a retry strategy). In other words, an error that happens 100% of cases is usually preferable to one that happens in 10%, as it makes sure it is fixed or handled properly.

That's fair enough, for me the most important thing is that it recovers at some point without requiring recycling or restarting however that doesn't mean it has to be implemented as I've mentioned to achieve that.

If you're able to proceed without touching the pool (for now), that's good - as I'm actively working on it (a PR maybe land this week, changing the pool in a significant way). I'll try to find time to review your PR, although realistically that may take some time.

That's fine, The PR is here for now: #2778 like I said, I've not yet solved the problem of it undergoing the flow: everything is working -> primary dies -> secondary is promoted -> everything is working. I've not had to touch the pool at all in this implementation as-is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants