Skip to content

Host Failover and TargetServerType support - #3434

Closed
mintsoft wants to merge 20 commits into
npgsql:mainfrom
mintsoft:failover-advanced-multiplexed
Closed

mintsoft wants to merge 20 commits into
npgsql:mainfrom
mintsoft:failover-advanced-multiplexed

Conversation

@mintsoft

@mintsoft mintsoft commented Dec 31, 2020 •

Copy link
Copy Markdown
Contributor

Replaces: https://github.com/npgsql/npgsql/pull/2778/files and #3098 after I couldn't get a clean history

Steps towards fixing: #732

Brief history of changes:

  • I've extended the connectionString mechanism to include the TargetServerType and Host to be a CSV of hostnames (similiar to the JDBC implementation)
  • The npgsqlConnector now detects the type of server it's connected to and retains it on the connector
  • The KeepAlive mechanism I've replaced with something that is updating the "Primary/Secondary" status of a connector and aborts the connection if it changes to an inappropriate type
  • The connection pooling will invalidate the connection when returned to the Pool in the situation where it is now not appropriate for the requested connection
  • The closing and reopening has been isolated to the Connector for now and I've introduced a ConnectedHost concept to differentiate from the Host which comes from the settings (i.e. Host actually represents PG1,PG2,PG3 etc)

I'm doing all my testing currently with Multiplexing disabled. As there's no KeepAlives in Multiplexing, I'm not sure how to piece all this together yet; however I think it should "just work" as it stands, except for the server-promotion scenario which really requires something to update the status of the server (i.e. keepalives),

Suggested improvements for the next version:

  • I'd like the connections to multiple hosts to actually happen in parallel so we don't have to incur the ConnectionTimeout cost when the first host in the CSV is completely inaccessible.
  • I'd like to not have to kill off connections and actually pool them in a different bucket (i.e. it's not unreasonable to have an application with the same connectionstring except for TargetServerType being primary in some cases and Secondary in others; I'd like to be able to move connections between the Pools as the server moves around without disconnecting/reconnecting. I started implementing a PoolKey concept to start looking at that, however it's not strictly required for the current implementation and I've removed it again)
  • I think, if a connection is constantly reused, it would never run the KeepAlive or similar and would therefore never update the connection status. I think I might need to tack something on to the NpsqlConnector.Reset method, but not 100% if this required yet.
  • Need to come up with a mechanism for tests. I've got a console application & some VM's that I'm using to develop/test this however I think it'd be pretty key to get the basics into the CI even if orchestrating failovers etc is out of scope.

@mintsoft
mintsoft marked this pull request as draft December 31, 2020 22:06
…connectionString in all situations, previously it would never use the pool
…d we should close the connection as this is no longer the "right" connection
…we should abandon this connection if we're looking for a secondary and actually get a master to force a reconnection
@mintsoft
mintsoft marked this pull request as ready for review January 1, 2021 14:02
@mintsoft mintsoft changed the title DRAFT: Failover advanced multiplexed Host Failover and TargetServerType support Jan 1, 2021
@mintsoft

mintsoft commented Jan 2, 2021

Copy link
Copy Markdown
Contributor Author

I think this is probably ready for some feedback regarding approach etc. I've tried to implement this with the smallest number of changes required to slice in the functionality before undertaking any more major work

@roji

roji commented Jan 6, 2021

Copy link
Copy Markdown
Member

@mintsoft thank you for keeping at this and not getting discouraged, I would have liked for us to do this earlier. I do think proper multi-host failover is a great feature to have on our roadmap for 6.0.

I'm currently back from vacation and dealing with a lot of backlog and semi-urgent things; in a few weeks I should get around to giving this some serious attention.

@mintsoft

mintsoft commented Jan 7, 2021

Copy link
Copy Markdown
Contributor Author

@roji Coolio, that's no problem; life is like that :)

@ecobisi ecobisi mentioned this pull request Mar 12, 2021
4 tasks done

@vonzshik vonzshik left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I've done a general review, and it looks promising.

// used to update state/perf counter).
if (connector.ClearCounter < _clearCounter || connector.IsBroken)

if (connector.ClearCounter < _clearCounter || connector.IsBroken || connector.IsAppropriateFor(connector.Settings.TargetServerType) == false)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure, in which case we might attempt to return the connector to the pool, but its not broken and doesn't have the appropriate server type?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yes, the server can change type at any point during the connection lifetime; so just because you initially connected to a standby, doesn't mean it will remain one over time so without verifying this when being handed back to the pool you end up with a 'poisoned' connection pool for a given connectionstring

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It definitely can change, but wouldn't KeepAlive in this case just break the connection?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it should. I have no idea why this is here. I'll take it out and retest my scenario's in-case there's something critical

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the server can also change type right after this check, so it's an inherent race condition situation.

But see my more general thoughts about mixed vs. per-ip pooling.

Comment thread src/Npgsql/NpgsqlConnector.cs Resolved
Comment thread src/Npgsql/PoolManager.cs Resolved
WritePregenerated(PregeneratedMessages.KeepAlive);
Flush();
SkipUntil(BackendMessageCode.ReadyForQuery);
UpdateServerPrimaryStatus();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here we have quite a few problems:

  1. UpdateServerPrimaryStatus sends a query, which might break a connection if we're in a failed transaction (see KeepAlive breaks the connection, if the ping is send during a broken transaction #3511). We should probably check whether we're in a transaction.
  2. We probably should send the default KeepAlive query if the TargetServerType is any.
  3. I think we have to call PoolManager.Clear, so every currently open connection will be closed.
  4. If there is a high load, KeepAlive might never get to be performed.

Comment thread src/Npgsql/NpgsqlConnector.cs Resolved
Comment thread src/Npgsql/NpgsqlConnector.cs Outdated
var columnCount = ReadBuffer.ReadInt16();
var lengthOfBooleanColumn = ReadBuffer.ReadInt32();
var resultSetBuffer = new byte[lengthOfBooleanColumn];
ReadBuffer.ReadBytes(resultSetBuffer, 0, lengthOfBooleanColumn);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This look pretty hardcore - we probably should rewrite this to a higher-level API (do not yet have any ideas on how it should look).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, absolutely, I wasn't able to find a way of running an actual query and getting a result set with the objects I had in the state they're in working; any suggestions as to how to actually make this not filth, much appreciated!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my proposal about checking this alongside sending DISCARD ALL when the connection is taken out of the pool.

await RawOpen(timeout, async, cancellationToken);
var potentialHosts = Settings.Host!.Split(',');
var hostIndex = 0;
while(ConnectedHost == null && hostIndex < potentialHosts.Length)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if we move the host checking to the NpgsqlConnection.Open and the pool? That way, we can cache the host on the pool (so every new open connection will just connect to the same host).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I can take a look at that. I think that's actually necessary to achieve something I want to in the "next version" anyway:

I'd like to not have to kill off connections and actually pool them in a different bucket (i.e. it's not unreasonable to have an application with the same connectionstring except for TargetServerType being primary in some cases and Secondary in others; I'd like to be able to move connections between the Pools as the server moves around without disconnecting/reconnecting. I started implementing a PoolKey concept to start looking at that, however it's not strictly required for the current implementation and I've removed it again)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, only 'take a look', as I would like to also hear @roji's opinion on this (and I would feel really bad if you will spend to much time on something we haven't decided yet 🤣).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll leave this till last and probably whack any changes into another branch off this one anyway so I've got this implementation for reference/safety

@vonzshik

Copy link
Copy Markdown
Contributor

Ouch, that's definitely not what I've intendent 🤣

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I finally got around to rereading all the previous discussions, and giving this a review. Thanks for being so patient @mintsoft - I think this is a good moment to iterate and push this feature through, I can commit to spending the time necessary for this in the coming weeks. If I'm needed for coding as well, I can do that (though no objection with you continuing work here, or @vonzshik!).

I'd like to not have to kill off connections and actually pool them in a different bucket (i.e. it's not unreasonable to have an application with the same connectionstring except for TargetServerType being primary in some cases and Secondary in others; I'd like to be able to move connections between the Pools as the server moves around without disconnecting/reconnecting. I started implementing a PoolKey concept to start looking at that, however it's not strictly required for the current implementation and I've removed it again)

Yeah, this is the where this PR is currently lacking - and also where the complexity is. I've gone over previous discussions on the pooling (i.e. this one we had), and I have some new thoughts.

  • I think our previous discussion was a bit in the wrong direction, since we were discussing possibly pooling by server type (primary/secondary). Since servers change types, that doesn't seem like a good starting point (we'd have to move connections across pools, etc)
  • The two options in my mind, are mixed pooling (where connections to all hosts are in the same, single pool), and pooling-per-server, where each pool only has connections to a single server/port combination. I'm currently leaning strongly towards the latter.
  • Pooling-per-host is how our pooling already works (mixed pooling would be new and break some existing assumptions).
  • I think that the multi-host functionality could be implemented outside the pooling with very little changes. Mixed pooling is likely to be considerably more invasive, and our pooling logic is already quite complex.
  • With mixed pooling, we'll need to continuously rent out connections and then immediately return them if they don't correspond to what we're looking for (primary/secondary). With pooling-per-host this doesn't happen.
  • Pooling-per-host could allow us to introduce a connection string syntax which allows specifying MaxPoolSize per host, instead of a single aggregate value. This may be useful in some cases, not sure.
  • From an implementation standpoint:
    • TargetServerType would not be part of the cache key (this can be done quite easily in NpgsqlConnection.GetPoolAndSettings)
    • The multi-host logic could live in a new type, which which references the pools of the individual hosts.
    • It could expose the same interface as our current pool (e.g. we could make Rent virtual), so it would be a pool-of-pools, if you will (MultipleHostsPool).
    • When Rent is called on it, it first attempts to get idle connections out of all the host pools with the right type (primary/secondary). If that loop didn't yield any idle connection, if can attempt to go into the "longer" open path, which opens a physical connection (or waits).

The KeepAlive mechanism I've replaced with something that is updating the "Primary/Secondary" status of a connector and aborts the connection if it changes to an inappropriate type
[...]
I think, if a connection is constantly reused, it would never run the KeepAlive or similar and would therefore never update the connection status. I think I might need to tack something on to the NpsqlConnector.Reset method, but not 100% if this required yet.

  • The latter is a good point. Note that we've recently changed the keepalive to not send SELECT 1, but to send a protocol Sync message instead (#3512) - this is because it's not possible to SELECT anything when we're in the failed transaction state. Also, keepalive is currently an opt-in feature, which not everyone wants to use.
  • However, the NpgsqlConnector.Reset is the right direction: when a connection is returned to the pool, we already "prepend" a DISCARD ALL to reset its state for when it's next used. This isn't executed right away (which would mean an extra roundtrip), but rather sent with the first command when the connection is next used. We could append the primary/secondary check to this DISCARD ALL, so that we'd check every time a pooled connection is opened - and with very little overhead. This would work less well for applications with long-lived connections - but experience shows these are relatively rare.
  • We'd also check when opening a new physical connection, as your PR already does (though we could eliminate the extra roundtrip). This would also provide some sampling when not using pooling at all.
  • Multiplexing does present a challenge here; there's neither keepalives nor DISCARD ALL - connections aren't actually taken out of the pool. I'd completely scope it out for now, and validate on the connection string that multiplexing isn't on with multiple hosts.
  • Note that there's still this unmerged patch which was about having PG push state changes. This would obviously be ideal and replace the current mechanism, at some point we should try pushing for this again.

I'd like the connections to multiple hosts to actually happen in parallel so we don't have to incur the ConnectionTimeout cost when the first host in the CSV is completely inaccessible.

This is about this discussion, right?

I'm still not sure exactly what I think about this - it would basically create lots of extra physical connection load on all servers, all the time, in order to avoid hanging on timeout when one of them crashes. Some thoughts:

  • IIRC neither libpq nor JDBC do this in parallel. It's worth following up to understand the reasoning there and if there have been discussions around it.
  • In a normal application using pooling, physical connection is a relatively rare event, so maybe the extra load of parallelizing isn't so bad.
  • Without parallelization, if we track server status (up/down) just as we track primary/secondary, we could avoid servers we know to be down, so the timeout hang would only affect attempts right after the crash. We could periodically try to ping that server - in the background so as not to block new connection attempts.
  • This could in theory be a connection string flag, though I really hate those and it would be difficult for users to understand when to use it etc.
  • We can also put off this question for now until we make progress with the rest (or not).

The closing and reopening has been isolated to the Connector for now and I've introduced a ConnectedHost concept to differentiate from the Host which comes from the settings (i.e. Host actually represents PG1,PG2,PG3 etc)

I think that NpgsqlConnector.Host should always represent the (single) Host it's connected to - it seems problematic for this property to sometimes have one host, and sometimes multiple. In the current code, Host is already assumed to contain just one host in various places (see AuthenticateGSS, GetPassword on NpgsqlConnector), so this PR probably breaks those.

Need to come up with a mechanism for tests. I've got a console application & some VM's that I'm using to develop/test this however I think it'd be pretty key to get the basics into the CI even if orchestrating failovers etc is out of scope.

Indeed, this is super important. The very basic multiple hosts feature can probably be tested with localhost and 127.0.0.1, but this isn't sufficient. It should probably also be possible to run two PG instances on two different ports in our CI, and test with that. But setting up an actual primary/secondary setup and playing around with it in a reliable way sounds scary. Let's discuss this again when we're further down the line with the implementation.

// used to update state/perf counter).
if (connector.ClearCounter < _clearCounter || connector.IsBroken)

if (connector.ClearCounter < _clearCounter || connector.IsBroken || connector.IsAppropriateFor(connector.Settings.TargetServerType) == false)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the server can also change type right after this check, so it's an inherent race condition situation.

But see my more general thoughts about mixed vs. per-ip pooling.

Comment thread src/Npgsql/NpgsqlConnector.cs Outdated
var columnCount = ReadBuffer.ReadInt16();
var lengthOfBooleanColumn = ReadBuffer.ReadInt32();
var resultSetBuffer = new byte[lengthOfBooleanColumn];
ReadBuffer.ReadBytes(resultSetBuffer, 0, lengthOfBooleanColumn);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my proposal about checking this alongside sending DISCARD ALL when the connection is taken out of the pool.


await LoadDatabaseInfo(forceReload: false, timeout, async, cancellationToken);
await LoadDatabaseInfo(forceReload: false, timeout, async, cancellationToken);
UpdateServerPrimaryStatus();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may be able to append this after the last authentication message, to avoid an additional roundtrip. Though this isn't critical for now.

@roji

roji commented Mar 14, 2021

Copy link
Copy Markdown
Member

Two small additional notes.

The pool-per-host approach would mean that MaxPoolSize is applied to each host separately; so if MaxPoolSize is 100 and there are 2 hosts, this connection string could cause 200 total physical connections to be created. With the mixed pooling approach, the MaxPoolSize applies to all hosts together; however, since in the worse case a single host may still get all the connections (because the others are down or because of randomness), one must still configure all hosts accordingly and assume the worst.

I actually think that the pool-per-host behavior makes more sense in the real world. In general, I can't see a need for users to define a maximum for all connections across all servers; the point of MaxPoolSize is to be able to configure PostgreSQL max_connections correctly in a predictable way. So I think what users actually need is to be able to say "100 maximum connections for each PG server".

Regarding testing, instead of messing around with two actual PostgreSQL instances and trying to get to a reliable primary/secondary setup (with failover!), we should probably just test this using the PG mock infrastructure that we already have. That would allow us to easily simulate failover scenarios etc. The possible downside is that we're not testing against real PG - so there may be some behavioral difference between the mock and real PG - but I think that's quite minor, and some thorough manual testing against real PG should be enough.

@roji

roji commented Mar 20, 2021

Copy link
Copy Markdown
Member

@mintsoft could you please send me an email (my email address is on my github profile)? There's something I'd like to ask.

@roji

roji commented Mar 21, 2021

Copy link
Copy Markdown
Member

As discussed offline with @mintsoft, am closing this in favor of #3607 which is based on this and continues further.

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.

3 participants