Skip to content

Determining if connection pool was exhausted based on exception #4544

Description

@marekott

Hi,
what I'm trying to achieve is to change my web app to start returning 503 status code (Service Unavailable) when exception related to exceeding connection pool is thrown. Is there a way to unequivocally qualify exception that is thrown in such situation? From what I can see it is NpgsqlException with IsTransient equal true and InnerException as TimeoutException. However I'm not sure if there aren't any other scenarios when exception with such configuration could be thrown but from a different reason. Parsing exception msg is not an approach that I want to follow.

Activity

  1. changed the title [-]Determining if connection poll was exceeded based on exception[/-] [+]Determining if connection poll was exhausted based on exception[/+] on Jul 5, 2022
  2. roji commented on Jul 5, 2022

    @roji
    Member

    There's nothing like this at the moment - you're basically asking for #1072.

    Can I ask why you need to programmatically identify pool exhaustion? I mean, how would your program modify its behavior based on that (as opposed to another kind of timeout)? I'm asking since if the goal is to simply know that pool exhaustion is occurring, then there are other, more appropriate way, e.g. event counters.

  3. marekott commented on Jul 6, 2022

    @marekott
    Author

    Thanks for the answer. We consider pool exhaustion as an transient failure and it makes sens to retry operation during which it occurred because there is a chance than second time it will pass (in contrast to exception thrown because of faulty query that will fail always). In case of other kind of timeouts I believe there are planty of reasons why they may occur and retrying in some scenarios may not have a lot of sense. Taking it into consideration we would like to translate pool exhaustion exception to 503 status code in response from our app instead of 500 we are currently returning. This ways our front-end can inform user that it may be wort retrying this operation before reaching to our support.

  4. marekott commented on Jul 6, 2022

    @marekott
    Author

    Are there any chances for implementing mentioned #1072?

  5. roji commented on Jul 6, 2022

    @roji
    Member

    In case of other kind of timeouts I believe there are planty of reasons why they may occur and retrying in some scenarios may not have a lot of sense.

    Can you provide more detail about this? The usual behavior is to indeed consider timeouts to be transient, and to retry them. Note that NpgsqlException has an IsTransient bool property, and it does return true for timeouts - we added that specifically to support transient retry logic.

  6. marekott commented on Jul 6, 2022

    @marekott
    Author

    Let me rephrase that. TimeoutException is not a custom exception from Npgsql so we can't be sure from where and because of what it will be thrown. Taking it into consideration I won't risk claiming that all timeouts are worth retrying. What I'm sure is that we want to retry exhausted pool. Btw timeout related to long running query will be reported as PostgresException right?

    If you are still interested in #1072 maybe you would accept PR adding code only for exhausted pool? Other codes could be added in the future.

  7. roji commented on Jul 6, 2022

    @roji
    Member

    TimeoutException is not a custom exception from Npgsql so we can't be sure from where and because of what it will be thrown.

    But the TimeoutExceptions thrown from Npgsql are wrapped by NpgsqlException... So if you want to identify those, just catch NpgsqlException and check whether the inner exception is a TimeoutException (or possibly just check IsTransient directly on NpgsqlException if that fits your needs).

    So again, the question is whether you want to distinguish between exhausted pool timeouts and other Npgsql timeouts; if you do, I'm interested in better understanding why.

    Btw timeout related to long running query will be reported as PostgresException right?

    No. Npgsql does not itself make use of the PostgreSQL statement_timeout mechanism (for various reasons); that mechanism raises a PostgresException with a specific code. Npgsql attempts to cancel a query after CommandTimeout, and if the cancellation isn't confirmed after a certain period, breaks the connection. In either case, a TimeoutException is raised.

    Note that you can set statement_timeout yourself manually, e.g. on the connection string; if that value is less than CommandTimeout, you should start getting PostgresExceptions which should be easily identifiable.

  8. marekott commented on Jul 6, 2022

    @marekott
    Author

    So again, the question is whether you want to distinguish between exhausted pool timeouts and other Npgsql timeouts; if you do, I'm interested in better understanding why.

    Ok, so after your explanation with query timeouts it makes me event more sure that I want to distinguish timeouts by their origin. Lets consider 2 timeouts that happened:

    1. Some unoptimized query that take so long to execute that it causes timeout (forced by Npgsql with TimeoutException). Lets assume that this query timeouts every time it is used.
    2. Due to heavy traffic connection pool was exhausted in one moment causing TimeoutException to be raised. There is a possibility that after retrying this operation it will succeed.

    If both of this cases are reported as NpgsqlException with inner exception of type TimeoutException it is impossible to distinguished them. If I can't do that how can I inform my user that he should try again in case of 2 but not in 1?

  9. roji commented on Jul 6, 2022

    @roji
    Member

    The problem is that there's also slow queries which do generally finish, but not always (based on various factors such as factor load). Users typically want to retry those, since they do end up succeeding, no? I'd expect queries which always timeout to be caught at development/testing time, and not make it into production.

    In other words, a timeout from a query isn't necessarily non-transient, do you really want to never retry queries which time out?

    As a side note, pool exhaustion timeouts are thrown from NpgsqlConnection.Open (modulu multiplexing), whereas query timeouts are thrown from NpgsqlCommand.Execute*. This can be used to distinguish between the two cases - though I'm still not really convinced that's a great idea.

  10. vonzshik commented on Jul 6, 2022

    @vonzshik
    Contributor

    If both of this cases are reported as NpgsqlException with inner exception of type TimeoutException it is impossible to distinguished them.

    That's definitely not how it works. For query timeouts we always throw OperationCancelledException (at the very least starting with Npgsql 5.0), which wraps either PostgresException (in case if the cancellation was successful), or TimeoutException (if it was not).

    Ignore the text above, I was checking the wrong test :(
    We do indeed throw NpgsqlException with inner TimeoutException.

  11. marekott commented on Jul 7, 2022

    @marekott
    Author

    In other words, a timeout from a query isn't necessarily non-transient, do you really want to never retry queries which time out?

    We set high enough timeout that if some query is time-outing is has to be really poorly optimized. Retrying it can seriously hit database performance. So yes we would like for now to retry only exhausted pool.

    As a side note, pool exhaustion timeouts are thrown from NpgsqlConnection.Open (modulu multiplexing), whereas query timeouts are thrown from NpgsqlCommand.Execute*. This can be used to distinguish between the two cases - though I'm still not really convinced that's a great idea.

    Ok, thanks for that info. Most of the time we relay on EF Core so it won't help us unfortunately as we are not going to assert stack trace.

    I believe that we now better understand each other. I can see your arguments and will definitely discuss them with my team. What about my previous question?

    If you are still interested in #1072 maybe you would accept PR adding code only for exhausted pool? Other codes could be added in the future.

  12. roji commented on Jul 7, 2022

    @roji
    Member

    Fair enough, thanks for the info and the conversation.

    I do agree that timeouts and transience is a tricky problem... Timeouts can also occur because of network partitions (yet another case), and they're pretty much indistinguishable from a long-running query which doesn't stream results back (modulu maybe TCP keepailves).

    Most of the time we relay on EF Core so it won't help us unfortunately as we are not going to assert stack trace.

    This is something you can do pretty easily with an EF connection/command interceptor. For example, you could set up a connection interceptor that catches exceptions, and if it sees a timeout, re-throws it as some other exception type which you can then identiy in your application where you implement your retry strategy.

    Do you think that could be sufficient for your needs?

  13. marekott commented on Jul 8, 2022

    @marekott
    Author

    This is something you can do pretty easily with an EF connection/command interceptor.

    Thanks, I wasn't aware of them.

    Before answering your question let me give you a little bit of context. Me and my team are responsible for infrastructure part of our application (configuring Npgsql, providing basic repository pattern implementation and many more non business related stuff). We provide our code in form of nuget packages so we don't have any control over code of other developers. We can't for example guarantee that they will not use Dapper (and I know they do) or pure ADO layer where they will open connection manually. However what we are controlling are status codes their web apps will return based on their state. We achieve it via ASP Core middleware's where we are catching all exceptions and translating them to appropriate status codes.

    So answering you question, unfortunately interceptors are not sufficient as the only place that guarantees that all exceptions related to exhausted pool would be translated to 503 status code is our middleware which only receives exception. That's why I'm so interested in those error codes mentioned in #1072.

  14. roji commented on Jul 8, 2022

    @roji
    Member

    Thanks for the extra context, I understand.

    Let us have a quick internal discussion about this; #1072 implies a bit of design thinking before we actually implement. There's also the option of providing this via a specific exception class (e.g. NpgsqlPoolExhaustionException) instead of a code - we need to think about all that a bit.

  15. roji commented on Jul 8, 2022

    @roji
    Member

    (if you don't hear back in a week or two, please feel free to ping me here again)

  16. 3 remaining items

  17. changed the title [-]Determining if connection poll was exhausted based on exception[/-] [+]Determining if connection pool was exhausted based on exception[/+] on Aug 6, 2022
  18. self-assigned this
    on Sep 25, 2022
  19. added this to the 7.0.0 milestone on Sep 25, 2022
  20. modified the milestones: 7.0.0, 8.0.0 on Nov 1, 2022
  21. springy76 commented on Dec 7, 2022

    @springy76

    BTW: Currently the StackTrace property of the TimeoutException for exhausted pool exceptions is always null because it just gets created for the inner exception and isn't an exception which has been thrown before.
    Might help distinguishing them.

  22. modified the milestones: 8.0.0, 9.0.0 on Nov 7, 2023
  23. modified the milestones: 9.0.0, 10.0.0 on Nov 18, 2024
  24. added theissue type on Jun 14, 2025
  25. modified the milestones: 10.0.0, Backlog on Nov 2, 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

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions