Skip to content

Include Transient Fault Detection (IsTransient Property) #1495

Closed

Description

@odiernod

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

  1. roji commented on Mar 17, 2017

    @roji
    Member

    (have fixed the code sample formatting, you can read up on GFM's support for syntax highlighting)

    Thanks, a few comments:

    • I think transient detection should also occur on NpgsqlException, not just on PostgresException (i.e. virtual property overridden by PGException). For NpgsqlException we can check if the inner exception is IOException.
    • I don't think a retry strategy belongs inside Npgsql (although it does belong in EF Core). Npgsql should only provide an IsTransient() property, which strategies in a high-level layer can use to test on.
  2. odiernod commented on Mar 17, 2017

    @odiernod
    Author

    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)"

  3. roji commented on Mar 17, 2017

    @roji
    Member

    I'm OK with the rename.

    Do you want to submit a PR adding IsTransient?

  4. odiernod commented on Mar 17, 2017

    @odiernod
    Author

    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?

  5. changed the title [-]Incorporate Transient Fault Handling[/-] [+]Include Transient Fault Detection (IsTransient Property)[/+] on Mar 17, 2017
  6. roji commented on Mar 19, 2017

    @roji
    Member

    Some thoughts...

    • I'd probably include all class 57 errors as transient
    • I think all class 55 errors are non-transient, and are triggered by a programming error
    • I'm not sure about the class 08 errors, some definitely sound transient.

    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!

  7. odiernod commented on Mar 20, 2017

    @odiernod
    Author

    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.

  8. omatrot commented on Mar 20, 2017

    @omatrot

    From my experience, the most important transient error is the one with code 40001 (transaction serialization failure).

  9. roji commented on Mar 20, 2017

    @roji
    Member

    @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?

  10. omatrot commented on Mar 20, 2017

    @omatrot

    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.

  11. odiernod commented on Mar 20, 2017

    @odiernod
    Author

    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.

  12. omatrot commented on Mar 20, 2017

    @omatrot

    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.

  13. roji commented on Mar 20, 2017

    @roji
    Member

    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.

  14. 4 remaining items

  15. odiernod commented on May 23, 2017

    @odiernod
    Author
  16. roji commented on May 23, 2017

    @roji
    Member

    This week is great, I'll wait for your PR.

  17. odiernod commented on May 23, 2017

    @odiernod
    Author
  18. odiernod commented on May 28, 2017

    @odiernod
    Author
  19. roji commented on May 28, 2017

    @roji
    Member

    @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 doing git pull upstream dev into 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.

  20. odiernod commented on May 28, 2017

    @odiernod
    Author
  21. roji commented on May 28, 2017

    @roji
    Member

    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.

  22. roji commented on May 30, 2017

    @roji
    Member

    @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.

  23. odiernod commented on May 30, 2017

    @odiernod
    Author
  24. added this to the 3.2.3 milestone on May 31, 2017
  25. added a commit that references this issue on May 31, 2017
    fc6b00b
  26. roji commented on May 31, 2017

    @roji
    Member

    @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!

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

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions