You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Determining if connection pool was exhausted based on exception #4544
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.
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
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.
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.
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.
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.
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.
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:
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.
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?
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.
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.
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.
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?
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.
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.
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
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.
Activity
[-]Determining if connection poll was exceeded based on exception[/-][+]Determining if connection poll was exhausted based on exception[/+]roji commentedon Jul 5, 2022
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.
marekott commentedon Jul 6, 2022
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.
marekott commentedon Jul 6, 2022
Are there any chances for implementing mentioned #1072?
roji commentedon Jul 6, 2022
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.
marekott commentedon Jul 6, 2022
Let me rephrase that.
TimeoutExceptionis not a custom exception fromNpgsqlso 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 asPostgresExceptionright?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.
roji commentedon Jul 6, 2022
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.
No. Npgsql does not itself make use of the PostgreSQL
statement_timeoutmechanism (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_timeoutyourself manually, e.g. on the connection string; if that value is less than CommandTimeout, you should start getting PostgresExceptions which should be easily identifiable.marekott commentedon Jul 6, 2022
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:
TimeoutException). Lets assume that this query timeouts every time it is used.TimeoutExceptionto be raised. There is a possibility that after retrying this operation it will succeed.If both of this cases are reported as
NpgsqlExceptionwith inner exception of typeTimeoutExceptionit 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?roji commentedon Jul 6, 2022
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.
vonzshik commentedon Jul 6, 2022
That's definitely not how it works. For query timeouts we always throwOperationCancelledException(at the very least starting with Npgsql 5.0), which wraps eitherPostgresException(in case if the cancellation was successful), orTimeoutException(if it was not).Ignore the text above, I was checking the wrong test :(
We do indeed throw
NpgsqlExceptionwith innerTimeoutException.marekott commentedon Jul 7, 2022
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.
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?
roji commentedon Jul 7, 2022
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).
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?
marekott commentedon Jul 8, 2022
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.
roji commentedon Jul 8, 2022
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.
roji commentedon Jul 8, 2022
(if you don't hear back in a week or two, please feel free to ping me here again)
3 remaining items
[-]Determining if connection poll was exhausted based on exception[/-][+]Determining if connection pool was exhausted based on exception[/+]springy76 commentedon Dec 7, 2022
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.