Skip to content

Data source keeps connections in the pool if it can't find a suitable host #5807

Description

@jernejg

Hey 👋
This is more of an question than an issue, but I am interested in your opinion.

Steps to reproduce

Request a specific server type

NpgsqlDataSource readerWriterDataSource
    = new NpgsqlDataSourceBuilder("Host=host")
        .BuildMultiHost()
        .WithTargetSession(TargetSessionAttributes.ReadWrite);

The issue

Current behaviour

When the host above is downgraded (becomes a read replica) and npgsql raises NpgsqlException("No suitable host was found.") or NpgsqlException("Unable to connect to a suitable host. Check inner exception for more details.") when attempting to create a connection, the physical connections already cached by the data source remain in the pool.

Expected behaviour

  1. If the pooled connection cannot satisfy the target session attribute requirement anymore, isn't it more appropriate to close it rather than keep it around?
  2. If the above behaviour is not acceptable, what if we throw a more specific exception, like NoSuitableHostFoundException. This would give a more explicit signal that we need to dispose and re-initialise the data source (to clear the pool)?

Further technical details

Npgsql version: latest
PostgreSQL version: any
Operating system: any

Other details about my project setup:

I am trying to use the functionality of a NpgsqlMultiHostDataSource to support failover scenarios, out of the box, where the host is behind a proxy. Because of the above issue, the data source won't attempt to open a new physical connection after the host starts pointing to the new writer.

At the moment the way to solve this is by having a thread safe way of re-initialising the data source:

  • after reactively catching a PostgresException with Routine=PreventCommandIfReadOnly when attempting a write or
  • before creating a connection, by writing my own implementation similar to UpdateDatabaseState, to detect when the role of the host changes.

Activity

  1. vonzshik commented on Aug 16, 2024

    @vonzshik
    Contributor

    Because of the above issue, the data source won't attempt to open a new physical connection after the host starts pointing to the new writer.

    That shouldn't work like that. We have a connection string parameter Host Recheck Seconds which dictates for how long we cache the state of the host. After it's elapsed, we consider the host as having an 'unknown' state and recheck whether it's primary/standby. In addition, whenever a host crashes/throws an error (which is what usually happens on role change) we also clear the cached state.
    This should also answer why we do not close the connection even though it's not the one we want: every 10 seconds we recheck whether the host is primary/standy and it's faster to send a single query compared to opening a new connection.

  2. jernejg commented on Aug 16, 2024

    @jernejg
    Author

    Hey thank you for the quick reply

    Because of the above issue, the data source won't attempt to open a new physical connection after the host starts pointing to the new writer.

    What I'm trying to say is that, because 1 connection was pooled, the data source did not detect that the proxy is pointing to a new host.

    This is the scenario:

    1. proxyHost is pointing to hostA (writer)
    2. We initialise a new multi data source pointing to the proxy NpgsqlDataSourceBuilder("Host=proxyHost")
    3. We open a new connection, data source pools the connection to hostA
    4. Failover happens, hostA becomes a reader
    5. We point the proxyHost to the new writer hostB
    6. Data source correctly detected that hostA is now a reader, but because of the pooled connection it doesn't know proxyHost is now pointing to a different host (hostB).
  3. vonzshik commented on Aug 16, 2024

    @vonzshik
    Contributor

    Data source correctly detected that hostA is now a reader, but because of the pooled connection it doesn't know proxyHost is now pointing to a different host (hostB)

    The timeline should be:

    1. proxyHost points to hostA (writer). We cache that for 10 seconds (depends on Host Recheck Seconds connection string parameter).
    2. At some point hostA becomes reader. In at most 10 seconds we realize that proxyHost is a reader and mark it accordingly.
    3. As some later point proxyHost is redirected to hostB (writer). Again, in at most 10 seconds we should clear the state for proxyHost and recheck whether it's still a reader.
  4. jernejg commented on Aug 16, 2024

    @jernejg
    Author

    Ok thanks, this was not the behaviour I saw in my tests. Let me re-check.

  5. jernejg commented on Aug 21, 2024

    @jernejg
    Author

    Hey, just realised that there is no proxy involved. It is only a DNS update.
    And that is why the new writer is not picked up. After the DNS change, npgsql will just keep using the cached connection to the old writer to ping for state.

    I understand that the point of using multi host data source is to actually initialise with multiple hosts, let me try to explain on our specific use case.

    We are using Postgres with AWS Aurora, which allows you to connect in 2 different ways:

    1. Connect to the cluster (single hostname which always points to the writer - my scenario above). If the pooled connections would be closed after npgsql detects a role downgrade then I get out of the box support for failovers (DNS updates).
    2. Connect to individual instances. Ideal solution, but takes a lot more effort. Before initialising a multi host datasource I would need an additional layer of complexity on top of npgsql that would know how to query Aurora infrastructure and extract the current writer/reader instance names and then re-initialise the multi data source on every change.

    The 2. approach is the correct one, it also minimises downtime due to the DNS delay (it takes extra time for the cluster endpoint from 1. to start pointing to the new writer)...but the price is a lot of extra complexity.

    The approach from 1. would be out of the box, no extra code, but additional 1 minute of downtime after a failover.

  6. vonzshik commented on Aug 22, 2024

    @vonzshik
    Contributor

    Connect to the cluster (single hostname which always points to the writer - my scenario above). If the pooled connections would be closed after npgsql detects a role downgrade then I get out of the box support for failovers (DNS updates).

    Yeah, that's probably not going to work.

    1. OS caches DNS records, so even if you did update DNS and npgsql closed pooled connection, it's quite likely we'll still open a connection to the previous host (because dns resolve will return cached IP).
    2. Let's say that we did detect role downgrade and then closed the connection. Depending on how fast the next request is it's very possible that DNS update still didn't happen yet, so we'll still connect to the standby. At this point, do we treat as standby-standby (role is stable), so we should keep the connection? Or should we still drop it? Should we do it forever?

    One way you can work around this is by using connection string parameter Connection Lifetime. The way it works is if a connection is open for more then X seconds, then it's going to be closed on return to the pool. So for example you can set it to 60 seconds to guarantee that at the most after 60 seconds your app will create a new connection (this doesn't solve the issue with cached dns records and obviously it means that even if there is no role switch you connections are going to be recreated every 60 seconds).

  7. NinoFloris commented on Nov 11, 2024

    @NinoFloris
    Member

    @vonzshik if you think there's nothing to improve we can close the issue.

  8. vonzshik commented on Nov 12, 2024

    @vonzshik
    Contributor

    With #5903 we've made a bit easier to clear a data source if it's required (so users do not have to recreate it from scratch), that leaves throwing a different exception whenever we can't find a suitable host.
    That's probably something we can take a look at as differentiating exceptions by their messages is not ideal.
    For now putting this for npgsql 10, given that it should be an easy change.

  9. added this to the 10.0.0 milestone on Nov 12, 2024
  10. added theissue type on Jun 14, 2025
  11. modified the milestones: 10.0.0, 11.0.0 on Nov 2, 2025
  12. matteocontrini commented on Mar 16, 2026

    @matteocontrini

    I'm seeing a similar issue. As @jernejg mentioned, when using managed database providers like AWS RDS and all Aiven-based ones (Aiven, OVHcloud, UpCloud, Exoscale, etc.), failover happens by swapping the primary IP in the DNS.

    In my case (UpCloud), the DNS entry has a TTL of 15 seconds. When failover/switchover happens, including during weekly maintenance updates or version upgrades, Npgsql currently fails either with Npgsql.PostgresException (0x80004005): 57P01: terminating connection due to administrator command or Npgsql.NpgsqlException (0x80004005): Exception while reading from stream ---> System.IO.EndOfStreamException: Attempted to read past the end of the stream. when executing commands (these are the inner exceptions of EF Core exceptions).

    I unfortunately don't have recent logs at hand so I can't say whether this situation recovers because of a process crash that re-creates connections from scratch after a new DNS lookup, or if Npgsql self-heals after a while. I know for sure that at every failover/switchover scenarios I experience a couple of minutes of downtime.

    I'm not sure if this is a reasonable expectation, but an ideal solution would be to have a way to configure Npgsql to re-query the DNS on connection failures and keep trying for a configurable amount of time (e.g. 15+ seconds, greater than the DNS TTL).

    For the record, here's an example of what you'd see in the DNS for a primary instance:

    ❯ dig public-test-bouncer-qpedcoiyabzq.db.upclouddatabases.com @ns-487.awsdns-60.com.
    
    ; <<>> DiG 9.20.20 <<>> public-test-bouncer-qpedcoiyabzq.db.upclouddatabases.com @ns-487.awsdns-60.com.
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 24483
    ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 1
    ;; WARNING: recursion requested but not available
    
    ;; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 4096
    ;; QUESTION SECTION:
    ;public-test-bouncer-qpedcoiyabzq.db.upclouddatabases.com. IN A
    
    ;; ANSWER SECTION:
    public-test-bouncer-qpedcoiyabzq.db.upclouddatabases.com. 15 IN	A 94.237.82.247
    
    ;; AUTHORITY SECTION:
    db.upclouddatabases.com. 172800	IN	NS	ns-1270.awsdns-30.org.
    db.upclouddatabases.com. 172800	IN	NS	ns-1764.awsdns-28.co.uk.
    db.upclouddatabases.com. 172800	IN	NS	ns-487.awsdns-60.com.
    db.upclouddatabases.com. 172800	IN	NS	ns-562.awsdns-06.net.
    
    ;; Query time: 25 msec
    ;; SERVER: 205.251.193.231#53(ns-487.awsdns-60.com.) (UDP)
    ;; WHEN: Mon Mar 16 16:24:00 CET 2026
    ;; MSG SIZE  rcvd: 238
    

    And here's the same for replicas:

    ❯ dig public-replica-test-bouncer-qpedcoiyabzq.db.upclouddatabases.com @ns-487.awsdns-60.com.
    
    ; <<>> DiG 9.20.20 <<>> public-replica-test-bouncer-qpedcoiyabzq.db.upclouddatabases.com @ns-487.awsdns-60.com.
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 30501
    ;; flags: qr aa rd; QUERY: 1, ANSWER: 2, AUTHORITY: 4, ADDITIONAL: 1
    ;; WARNING: recursion requested but not available
    
    ;; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 4096
    ;; QUESTION SECTION:
    ;public-replica-test-bouncer-qpedcoiyabzq.db.upclouddatabases.com. IN A
    
    ;; ANSWER SECTION:
    public-replica-test-bouncer-qpedcoiyabzq.db.upclouddatabases.com. 15 IN	A 212.147.231.130
    public-replica-test-bouncer-qpedcoiyabzq.db.upclouddatabases.com. 15 IN	A 94.237.98.193
    
    ;; AUTHORITY SECTION:
    db.upclouddatabases.com. 172800	IN	NS	ns-1270.awsdns-30.org.
    db.upclouddatabases.com. 172800	IN	NS	ns-1764.awsdns-28.co.uk.
    db.upclouddatabases.com. 172800	IN	NS	ns-487.awsdns-60.com.
    db.upclouddatabases.com. 172800	IN	NS	ns-562.awsdns-06.net.
    
    ;; Query time: 26 msec
    ;; SERVER: 205.251.193.231#53(ns-487.awsdns-60.com.) (UDP)
    ;; WHEN: Mon Mar 16 16:25:06 CET 2026
    ;; MSG SIZE  rcvd: 262
    

    Thanks!

  13. modified the milestones: 11.0.0, 12.0.0 on Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions