Repository navigation
Description
When programming systems with resiliency in mind it is good to have a strategy which allows you to determine which faults are transient you can decide whether or not to retry them.
An option would be to add an IsTransient property onto the PostgresException for those that are defining retry policies, having it implement the logic in the PostgresDatabaseTransientErrorDetectionStrategy method below. Also, I may have misclassified some error codes, so please double check my assumptions as well.
Using Polly, here is an example of a RetryPolicy I defined loosely following the best practices laid out by the SQLTransientErrorDetectionStrategy in Microsoft's Transient Fault Handling Application Block:
https://social.technet.microsoft.com/wiki/contents/articles/18665.cloud-service-fundamentals-data-access-layer-transient-fault-handling.aspx
I don't know why the first portion of my code sample won't format. I apologize for that.
public static Policy PostresTransientFaultPolicy
{
get
{
return postgresTransientPolicy ?? (postgresTransientPolicy = Policy.Handle<Exception>( PostgresDatabaseTransientErrorDetectionStrategy())
.WaitAndRetryAsync(
retryCount: 10,
sleepDurationProvider: retryAttempt => ExponentialBackoff(retryAttempt, 1.4),
onRetry: (exception, span) => Log.Warning(exception, "Postgres Retry Failure: "))
.WrapAsync(
Policy.Handle<Exception>( PostgresDatabaseTransientErrorDetectionStrategy())
.AdvancedCircuitBreakerAsync(
failureThreshold:.4,
samplingDuration: TimeSpan.FromSeconds(30),
minimumThroughput: 20,
durationOfBreak: TimeSpan.FromSeconds(30),
onBreak: (ex, timeSpan, context) => Log.Warning(ex, "Postres Circuit Breaker Broken: "),
onReset: (context) => Log.Warning("Postres Circuit Breaker Reset: "),
onHalfOpen: () => Log.Warning("Postres Circuit Breaker Half Open: ")
)));
}
}
private static TimeSpan ExponentialBackoff(int retryAttempt, double exponent)
{
return TimeSpan.FromSeconds(Math.Pow(retryAttempt, exponent));
}
private static Func<Exception, bool> PostgresDatabaseTransientErrorDetectionStrategy()
{
return (ex) =>
{
//if it is not a postgres exception we must assume it will be transient
if (ex.GetType() != typeof(PostgresException))
return true;
var pgex = ex as PostgresException;
switch (pgex.SqlState)
{ //Assumed Transient Errors
case "53000": //insufficient_resources
case "53100": //disk_full
case "53200": //out_of_memory
case "53300": //too_many_connections
case "53400": //configuration_limit_exceeded
case "57P03": //cannot_connect_now
case "58000": //system_error
case "58030": //io_error
//These next few I am not sure whether they should be treated as transient or not, but I am guessing so
case "55P03": //lock_not_available
case "55006": //object_in_use
case "55000": //object_not_in_prerequisite_state
case "08000": //connection_exception
case "08003": //connection_does_not_exist
case "08006": //connection_failure
case "08001": //sqlclient_unable_to_establish_sqlconnection
case "08004": //sqlserver_rejected_establishment_of_sqlconnection
case "08007": //transaction_resolution_unknown
return true;
}
return false;
};
}
Activity
roji commentedon Mar 17, 2017
(have fixed the code sample formatting, you can read up on GFM's support for syntax highlighting)
Thanks, a few comments:
IsTransient()property, which strategies in a high-level layer can use to test on.odiernod commentedon Mar 17, 2017
I concur, I mainly included the retry policy for reference.
If you are fine with it I could rename the issue "Include Transient Fault Detection (IsTransient Property)"
roji commentedon Mar 17, 2017
I'm OK with the rename.
Do you want to submit a PR adding IsTransient?
odiernod commentedon Mar 17, 2017
I'll see if I can get to it over the weekend. Do you think I cherry picked the correct error codes in my PostgresDatabaseTransientErrorDetectionStrategy method?
[-]Incorporate Transient Fault Handling[/-][+]Include Transient Fault Detection (IsTransient Property)[/+]roji commentedon Mar 19, 2017
Some thoughts...
I'd really recommend you send your final list to the PostgreSQL hackers list to have it properly confirmed by the gurus - if/when you do please post a link to the conversation here.
Finally, don't forget to implement the check on NpgsqlException as well.
And thanks for looking into this!
odiernod commentedon Mar 20, 2017
I sent a request to the Postgresql hackers email list. I'll incorporate any response I get into the pull request, which I'll hold off for a little bit until I get some sort of response from the pg gurus. I can also link the resulting conversation to their archive when it gets posted.
I have incorporated your suggestions about checking for an inner IO exception in the NpgsqlException, thanks for that.
omatrot commentedon Mar 20, 2017
From my experience, the most important transient error is the one with code 40001 (transaction serialization failure).
roji commentedon Mar 20, 2017
@omatrot interesting, any idea when that happens? Is that some sort of actual I/O error when writing to disk? Does retrying the same thing succeed?
omatrot commentedon Mar 20, 2017
You could learn more on the PostgreSQL wiki.
Serializable Snapshot Isolation
Unless you're writing an accounting application (I was !), you probably don't really care.
odiernod commentedon Mar 20, 2017
I also heard from the postgres hackers group that 40001 should be included as a transient code. One caveat they listed is that if within a transaction the entire transaction may need to be retried in that case, not simply that particular query. The rest of the guidance I received was useful, but not immediately applicable. Some of the codes for example, such as insufficient_resources or out_of_memory can be thrown for different reasons, so they might work with a blind retry, but they might actually require admin intervention.
Based on the feedback I've received so far I think we'll have to decide moving forward if we want "optimistic retrys" -> retry everything that at least has a possibility of working a second time, or if we want to reserve IsTransient only for errors where retrying is more than likely to actually help.
omatrot commentedon Mar 20, 2017
Yes the entire transaction should be retried in that particular case.
I think that this is up to the client code to decide what to do. In our case, we retry the whole transaction several times with a delay that is increasing automatically on each failure. Retrying too fast may continue to fail, we encountered it. Especially when dealing with prepared transactions, because of the delay of MSDTC between PREPARE/COMMIT.
roji commentedon Mar 20, 2017
Thanks for digging into this and querying on the hackers list (please post the link here).
First, this issue is only about adding an IsTransient property, and not implementing an execution retry strategy (i.e. with backoffs etc). IsTransient would definitely be usable in user code for implementing such a strategy, though.
Second, I tend to agree with the "optimistic" approach - if there's a chance that a blind retry would succeed, then we should treat the error as transient. If an error always means that admin intervention is necessary, then it's not transient in our sense (since an automatic blind retry would always fail). Even if there's a good chance that some error requires admin intervention, there still doesn't seem to be a big disadvantage to blindly retrying it - at the very worse we'll have tried twice/thrice.
4 remaining items
odiernod commentedon May 23, 2017
roji commentedon May 23, 2017
This week is great, I'll wait for your PR.
odiernod commentedon May 23, 2017
odiernod commentedon May 28, 2017
roji commentedon May 28, 2017
@odiernod, you're supposed to fork the npgsql repo on github, and then clone it locally on your machine. At this point your local repo has "origin", which points to your own fork on github. You then add the real npgsql repo as upstream (
git remote add upstream [email protected]:npgsql/npgsql.git). From this point, you can sync up with the latest upstream by doinggit pull upstream devinto your local dev and rebasing your branches on it. When you want to submit a PR, push your branch to your own github fork (git push origin my-branch) and open a PR on the github website.Hope this helps, if you still need help let me know.
odiernod commentedon May 28, 2017
roji commentedon May 28, 2017
Well, it seems you're using ssh rather than https (which is fine), and that you probably didn't set your github account properly with your public key... Read the github docs on how that works.
roji commentedon May 30, 2017
@odiernod, any update? If you're having issues with github/PRs you can just post your code and I'll commit it in your name... I'd like to get 3.2.3 out soon.
odiernod commentedon May 30, 2017
Add IsTransient on exceptions
roji commentedon May 31, 2017
@odiernod thanks, I've committed your code after some minor changes. No worries about the github process, the important thing was the work done on identifying which error codes are transient, the discussion on the pghackers list, etc. Thanks for your contribution!