Skip to content

Further improvements to multiple hosts #3613

Open

Description

@vonzshik

The multiple hosts feature was originally implemented in #732. We have the possible following improvements in mind:

  • Update cluster state with KeepAlive (requires more discussion)
    • @roji: I think given that keepalive is opt-in only and doesn't support executing commands in the failed transaction state, and that PG14 pushes async notifications on state changes, we don't really need to do this.
  • Add support for multiple hosts with multiplexing
  • Add support for multiple hosts without pooling
  • Preliminarily update the cluster's state on connector's return (once per expiration cycle), useful with postgresql < 14.0
  • Add a queue for idle connectors (instead of renting from every pool)
  • Add a loop for connecting during failover #5769
    • @roji: for clarity, this is specifically the case where the primary has gone down and a secondary hasn't yet been fully promoted. In this state - when there's no primary at all - we can attempt to wait for a while until a primary appears rather than throw immediately. This would probably involve repeatedly polling secondary states with the assumption that one of them will become the primary.
  • Related/similar: when all hosts are down, we probably shouldn't wait for hostCheckSeconds before retrying again
  • Consider connecting to multiple hosts in parallel instead of sequentially #3610

Activity

  1. added this to the vNext milestone on Mar 21, 2021
  2. self-assigned this
    on Apr 4, 2021
  3. roji commented on Oct 5, 2021

    @roji
    Member

    @vonzshik are you planning to work on anything here for 6.0.0? I think what we have is probably more than good enough, we can always improve in 7.0 based on user feedback.

  4. changed the title [-]List of QOL changes for the multiple hosts feature[/-] [+]Further improvements to multiple hosts[/+] on Oct 5, 2021
  5. vonzshik commented on Oct 6, 2021

    @vonzshik
    ContributorAuthor

    @roji at the very least we should add an API to allow users to manage cluster state cache themselves (it shouldn't be that hard + it can be used as a workaround for some possible bugs).

  6. roji commented on Oct 6, 2021

    @roji
    Member

    Created issue specifically for manual cluster state control (#4018), and will backlog the rest (this issue).

  7. modified the milestones: 6.0.0, Backlog on Oct 6, 2021
  8. JulianRooze commented on Apr 8, 2025

    @JulianRooze

    @roji For multiple hosts + multiplexing, I assume this is not as simple as changing this line to settings.Multiplexing ? new MultiplexingDataSource? 🙂

  9. vonzshik commented on Apr 8, 2025

    @vonzshik
    ContributorAuthor

    @JulianRooze nope, there is also the part where we write each query to multiplexing data source. I'm pretty sure we're going to get InvalidCastException here since it's NpgsqlMultiHostDataSource and not MultiplexingDataSource.

    // The connection isn't bound to a connector - it's multiplexing time.
    var dataSource = (MultiplexingDataSource)conn.NpgsqlDataSource;

  10. JulianRooze commented on Apr 9, 2025

    @JulianRooze

    @vonzshik I see, something like this?

    https://github.com/npgsql/npgsql/compare/main...JulianRooze:npgsql:multi-host-multiplex?expand=1

    Not proposing this as an actual change, just to get a feeling for the size of the change.

  11. vonzshik commented on Apr 9, 2025

    @vonzshik
    ContributorAuthor

    @JulianRooze the main problem is that at no point we're actually going to refresh the state for each child pool (because currently it's done only on Open).

  12. kvisscher commented on May 2, 2025

    @kvisscher

    @vonzshik would you be able to suggest the way to detect the connection state from an application perspective? I'd like to use multiplexing as well in combination with multiple nodes, manually changing the connection from the application then seems like to best way forward for now?

  13. vonzshik commented on May 3, 2025

    @vonzshik
    ContributorAuthor

    Hmm, while it's definitely not trivial, it might be doable? There are two main problems: the first one is to determine whether the server is primary/standy, while the second is to mark offline servers as inaccessible.

    The first problem is a problem with multiplexing due to the way NpgsqlConnection.Open works: while the first call will actually open a physical connection and check access, that's not true for the next calls.
    One way to work around this is by starting a transaction. In that case, you'll get a physical connection from the pool, and because we do not send anything to postgres until the first query, it should be very fast to do per each Open.
    Then, you have to check whether the server is primary or standby/readonly. This should be doable via NpgsqlConnection.PostgresParamerers, default_transaction_read_only and in_hot_standby. Every 10 (for example) seconds you instead should send a query to get the actual values from the database.

    internal async ValueTask<DatabaseState> QueryDatabaseState(
    NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken = default)
    {
    using var batch = CreateBatch();
    batch.BatchCommands.Add(new NpgsqlBatchCommand("select pg_is_in_recovery()"));
    batch.BatchCommands.Add(new NpgsqlBatchCommand("SHOW default_transaction_read_only"));
    batch.Timeout = (int)timeout.CheckAndGetTimeLeft().TotalSeconds;
    var reader = async ? await batch.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false) : batch.ExecuteReader();
    try
    {
    if (async)
    {
    await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
    _isHotStandBy = reader.GetBoolean(0);
    await reader.NextResultAsync(cancellationToken).ConfigureAwait(false);
    await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
    }
    else
    {
    reader.Read();
    _isHotStandBy = reader.GetBoolean(0);
    reader.NextResult();
    reader.Read();
    }
    _isTransactionReadOnly = reader.GetString(0) != "off";
    var databaseState = UpdateDatabaseState();
    Debug.Assert(databaseState.HasValue);
    return databaseState.Value;
    }
    finally
    {
    if (async)
    await reader.DisposeAsync().ConfigureAwait(false);
    else
    reader.Dispose();
    }
    }

    For the second problem, the main issue is that you can only track errors by wrapping every single query in try/catch. Though, it might be not important since by working around the first problem you will either get errors there, or you'll get a connection to a readonly server.

  14. added theissue type on Jun 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions