Skip to content

Database-agnostic way to detect transient database errors #34817

Closed

Description

@roji

Provider tracking issues

This new API has been merged, following are tracking issues for implementation in the different providers:

Summary

A recurring theme for database programming has been building automated retry policies, but System.Data doesn't currently allow database drivers to expose whether a database error can be expected to be transient or not. This leads to database-specific logic for detecting transient exceptions being built again and again outside of the driver.

API Proposal

class DbException
{
    public virtual bool IsTransient => false;
}

Notes

  • IsTransient should be optimistic, i.e. return true in all cases where a simple retry of the operation - without any other change - may be successful. We prefer to err on the side of transience, since the downside is only a few extra retries.
  • In at least some cases, if an operation transiently fails within a transaction, the entire transaction must be rolled back and retried (including all previous operations). This would be out of scope of this proposal: DbException would only inform the consumers that the exception is transient, but the actual handling (rolling back, reissuing previous commands) would be the consumer's responsibility.

Resources and examples

Old notes on SupportsTransienceDetection (removed from proposal)

  • SupportsTransienceDetection can be used to signal that IsTransient has been implemented by a driver, and can be expected to be true where relevant. Note that in general it should be fine to just check IsTransient directly, as it would default to false in any case.
  • It's a bit problematic for to be on DbException:
    • This makes it hard to do a simple check on startup (one needs an actual DbException instance thrown from the driver).
    • This feature flag would ideally be in a general metadata/feature discovery facility (see ADO.NET metadata/feature/capability discovery API #28763), but we don't have that at the moment.
    • We could put this flag on DbProviderFactory, but that would turn it into a general place for feature flags as opposed to a factory (current flags such as CanCreateDataAdapter are about factory methods on the type, so much more appropriate).
    • As the problem isn't very acute, having this property on DbException is probably OK.

/cc @David-Engel @cheenamalhotra @bgrainger @bricelam @ajcvickers @stephentoub @terrajobst @mgravell @FransBouma

Edit history

Date Modification
2020-04-10 API proposal
2020-04-18 Removed SupportsTransienceDetection

Activity

  1. added
    api-suggestion
    on Apr 10, 2020
  2. self-assigned this
    on Apr 10, 2020
  3. added
    untriaged
    on Apr 10, 2020
  4. FransBouma commented on Apr 10, 2020

    @FransBouma
    Contributor

    Is SupportsTransienceDetection really necessary? All I'm interested in as a consumer of the exception is whether it's a transient error. Now I have a list of transient error codes per database in my transient error recovery strategy classes and that's not very flexible (if error codes are added I have to maintain this list plus I have to look up these codes for all databases supported). So I just want to know 'is this exception a transient error?' If so, use the strategy, if not, throw the exception further up like a normal exception.

    If IsTransient is false, whether that's because it's not a transient error or because the driver/ado.net provider doesn't support this, the net end result is the same: the recovery strategy is bypassed and the exception is rethrown as a normal exception.

    Perhaps I'm overlooking a use case tho :)

  5. roji commented on Apr 10, 2020

    @roji
    MemberAuthor

    You're right that it's not terribly useful (i.e. "Note that in general it should be fine to just check IsTransient directly, as it would default to false in any case.").

    The main case I had in mind was to be able to surface that information to a user, or possibly to fail at startup if transience isn't supported by a provider. I'm not sure how relevant that really is, if people think it's useless we can also drop it.

  6. FransBouma commented on Apr 10, 2020

    @FransBouma
    Contributor

    Ah now I understand it. :) Not sure how that information can be used in a practical way however: a recovery strategy of some sort has to be implemented regardless: a re-entrant aware system that can deal with retrying the commands in a given form, and if that strategy is built around 'IsTransient' it will simply bubble up all exceptions (as they're never 'transient') which is effectively the same as having code checking SupportsTransienceDetection and switching based on that between no recovery strategy and a recovery strategy. Except perhaps a tiny performance gain in the 'no recovery strategy' scenario perhaps.

  7. roji commented on Apr 10, 2020

    @roji
    MemberAuthor

    [...] and switching based on that between no recovery strategy and a recovery strategy. Except perhaps a tiny performance gain in the 'no recovery strategy' scenario perhaps.

    Yeah, I wouldn't really expect anyone to switch on SupportsTransienceDetectionfor recovery/no-recovery (and I definitely don't think there's any real perf to be gained). But in theory someone could try to do something at a higher level if they know there's no transience detection. I admit I don't really have a compelling use-case - it's more a general idea of allowing consumers to know whether it's been implemented or not, for any reason they might have.

    I'm definitely open to removing this - let's see what other people think.

  8. saurabh500 commented on Apr 10, 2020

    @saurabh500
    Contributor

    While working on SqlClient, I realized that the classification of Transient errors is a combination of recommendations offered by the database and the nature of the customer workload and the customer's own understanding of their infrastructure running the applications and databases.

    A driver can classify an error as transient, if it is recommended. And such recommendations are usually made for a very small subset of errors. At least this is what my observation is, while interacting with SqlClient customers.

    For many other errors, it is the application that decides whether it should be transient or not.

    Consider SqlConnection.Open() in SqlClient, it retries on a bunch of errors while connecting to Azure SQL DB. But those errors are returned by the server. However there are many cases in which customers want to retry on networking specific errors, which may be caused by broken connections or caused by failure in TCP paths.
    Some customers want to have retries on such errors and some customers want to detect these ASAP and have no retries.

    Similar arguments go for Command Execution where the customers want to retry on some errors and fail fast on some errors. E.g. Deadlock is a problem that some customer applications want to retry on, because in their workload it is transient and for some customer applications, deadlocks need investigation.

    Basically the known transient errors in SqlClient are much fewer and this proposal makes more sense with a mechanism via which the customers can tell us if they want a particular error to be treated as transient and retried on, vs errors that we fail fast with.

    Otherwise the client's may not be authoritatively able to classify errors as transient and in case of client considering errors as transient may be undesirable.

    One of the asks from a few customers of SqlClient is to be able to specify what errors the applications want to consider transient and have the client retry internally on those errors.

    I wonder if the above situations apply for other drivers, they probably might.

    An API ecosystem where customers have the ability to specify what errors should be treated transient would be lot more powerful.

  9. roji commented on Apr 10, 2020

    @roji
    MemberAuthor

    Thanks for these thoughts @saurabh500.

    One of the asks from a few customers of SqlClient is to be able to specify what errors the applications want to consider transient and have the client retry internally on those errors.

    I think there may be a bit of confusion here between the transient retrying implemented inside of SqlClient, and external retrying implemented outside of any specific driver, and which would leverage the proposed IsTransient property. Anything happening inside SqlClient is specific to that driver, and although you could add an API to make its retry mechanism more flexible, I don't think that would be applicable for a database-agnostic approach. Npgsql (as well as most other drivers AFAIK) doesn't consider retrying to be within its scope of responsibility and doesn't contain any logic internally for doing so - NpgsqlConnection.Open (almost) always immediately throws if any I/O error occurs. The user is expected to handle retrying according to their needs (typically using something like Polly), which obviates any need for an API to tell the driver what to retry and what not to retry. The proposed IsTransient property is meant to help with writing such an external retrying strategy.

    It definitely makes sense that different customers may have different needs around retrying, and around which errors should be classified as transient. From a database-agnostic perspective, doing anything here would require some sort of database-agnostic classification/categorization system: networking errors, transaction deadlock errors, etc. If such a classification existed, driver users would be able to react differently to types of errors in a database-agnostic way. However, I'm skeptical of whether such a system can work; as I wrote in dotnet/SqlClient#518 (comment), database errors and error codes in general seem very divergent across databases, and I'd be very wary for us to go into the business of standardizing database error categories for the purpose of transience.

    (As a aside note, the standard SQLSTATE is precisely an attempt to categorize database errors in a database-agnostic way (although SQLSTATE isn't really concerned with transience as a first-level concept). As I wrote in dotnet/SqlClient#518 (comment), I'm not aware of this being implemented in SQL Server, for example.)

    Some further thoughts:

    • There is one definition of transience which seems clear and unambiguous to me, regardless of specific customer needs - whether retrying the same operation may succeed without doing any other change. Under this definition, all network errors are transient, as are any locking issues which could disappear on a second attempt.
    • It seems to me that this definition has enough value for the general/default case; at the end of the day, consumers are always free to ignore the proposed IsTransient property and define whatever retry policy they want. However, if in the typical case customers really do need to configure and tweak exactly which error type they want to retry, then I guess there's little value in this proposal and a non-agnostic approach is the only possibility (as today). It would be good to see what others think about this.

    Let me know what you think or if I've misunderstood your points.

  10. saurabh500 commented on Apr 10, 2020

    @saurabh500
    Contributor

    I am not asking for ADO.Net base classes to be database aware or to categorize errors. That would not be desirable and may not serve all databases and their ways of categorizing errors.
    I should have not used too many references to SqlClient in my explanation :)

    For a driver to say whether DbException.IsTransient should be set true or false is prior knowledge. So a driver knows that there are errors that are transient since those errors are documented. It is only for those errors that the driver can definitely set IsTransient to true. For all other errors, there should be a way for the consumer of ado.net driver to add to the list of transient errors.

    If the customer can feed in any more errors codes that they want to consider transient, then the driver can set the IsTransient property to true for those additional errors along with the errors it knows about and any transient error handling framework like Polly can simply retry since the information is plumbed into the exception from the driver.

    Does this make sense?

  11. saurabh500 commented on Apr 10, 2020

    @saurabh500
    Contributor

    I had a chat with Shay:

    The fundamental problem is that every driver / database has errors which need to be interpreted differently, they may be in different formats, an error code may be overloaded with lot more information than just being a code.

    Hence providing a DB agnostic way of getting these errors from the ADO.Net layer, may not satisfy all providers.

    The recommendation would be to have the driver expose a mechanism (say via Connection String) to take in a list of errors that the driver user wants to consider transient. Then the driver can simply make use of DbException.IsTransient to express that the error is to be considered transient.

    Basically the mechanism of ingestion of the custom error will be dependent on the driver and ADO.Net DbException will provide a way for the driver to express if the error is transient or not.

  12. saurabh500 commented on Apr 10, 2020

    @saurabh500
    Contributor

    @roji, I hope this captures the discussion. Please add to it if I missed anything.

  13. 38 remaining items

  14. terrajobst commented on Jun 30, 2020

    @terrajobst
    Contributor

    Video

    • Makes sense as proposed.
    namespace System.Data.Common
    {
        public partial class DbException
        {
            public virtual bool IsTransient => false;
        }
    }
  15. added a commit that references this issue on Jul 12, 2020
    4de88bd
  16. added a commit that references this issue on Jul 12, 2020
    1b8d1dc
  17. bgrainger commented on Jul 12, 2020

    @bgrainger
    Contributor

    Now I have a list of transient error codes per database in my transient error recovery strategy classes and that's not very flexible (if error codes are added I have to maintain this list plus I have to look up these codes for all databases supported).

    @FransBouma Would you be willing to share the list of MySQL error codes you consider to be transient for MySQL? I think MySqlConnector could adopt them, instead of coming up with a different list (that you'd have to augment because you couldn't trust that IsTransient is sufficient for your needs).

    mysql-net/MySqlConnector#849

  18. FransBouma commented on Jul 13, 2020

    @FransBouma
    Contributor

    @bgrainger
    I don't have such a list, we only ship a transient error recovery class for SQL Server with boilerplate code for users if they want to add support for their database for that.
    Basically any error that doesn't kill the transaction / connection is usable for transient error recovery, however to figure out which ones that are is a painful process with some databases.

  19. roji commented on Jul 13, 2020

    @roji
    MemberAuthor

    Basically any error that doesn't kill the transaction / connection is usable for transient error recovery [...]

    I tend to be a bit more conservative on this, e.g. a unique constraint violation isn't something I'd consider transient, since the exact same operation would in principle produce the same failure (even if the same operation but with a different ID would succeed). The way I'm thinking about this is for the development of automatic retry strategies (Polly, EF Core, LLBLGen Pro).

    It's indeed a good idea for us to end up with the same concept of transience across providers (that's the whole point of the feature), so let's continue having this conversation.

  20. FransBouma commented on Jul 13, 2020

    @FransBouma
    Contributor

    Doesn't a UC violation terminate the transaction? For SQL Server we use these:

    switch(Convert.ToInt32(errorNumber))
    {
    	// Time out. 
    	case -2:
    	// DBNETLIB Error Code: 20
    	// The instance of SQL Server you attempted to connect to does not support encryption.
    	case 20:
    	// SQL Error Code: 64
    	// A connection was successfully established with the server, but then an error occurred during the login process. 
    	// (provider: TCP Provider, error: 0 - The specified network name is no longer available.) 
    	case 64:
    	// SQL Error Code: 233
    	// The client was unable to establish a connection because of an error during connection initialization process before login. 
    	// Possible causes include the following: the client tried to connect to an unsupported version of SQL Server; the server was too busy 
    	// to accept new connections; or there was a resource limitation (insufficient memory or maximum allowed connections) on the server. 
    	// (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)
    	case 233:
    	// SQL Error Code: 1205
    	// Dead lock situation. 
    	case 1205:
    	// SQL Error Code: 10053
    	// A transport-level error has occurred when receiving results from the server.
    	// An established connection was aborted by the software in your host machine.
    	case 10053:
    	// SQL Error Code: 10054
    	// A transport-level error has occurred when sending the request to the server. 
    	// (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)
    	case 10054:
    	// SQL Error Code: 10060
    	// A network-related or instance-specific error occurred while establishing a connection to SQL Server. 
    	// The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server 
    	// is configured to allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed 
    	// because the connected party did not properly respond after a period of time, or established connection failed 
    	// because connected host has failed to respond.)"}
    	case 10060:
    	// SQL Error Code: 10928
    	// Resource ID: %d. The %s limit for the database is %d and has been reached. For more information,
    	case 10928:
    	// SQL Error Code: 10929
    	// Resource ID: %d. The %s minimum guarantee is %d, maximum limit is %d and the current usage for the database is %d.
    	// However, the server is currently too busy to support requests greater than %d for this database.
    	case 10929:
    	// SQL Error Code: 40197
    	// The service has encountered an error processing your request. Please try again.
    	case 40197:
    	// SQL Error Code: 40143
    	// The service has encountered an error processing your request. Please try again.
    	case 40143:
    	// SQL Error Code: 40501
    	// The service is currently busy. Retry the request after 10 seconds.
    	case 40501:
    	// SQL Error Code: 40613
    	// Database XXXX on server YYYY is not currently available. Please retry the connection later. If the problem persists, contact customer 
    	// support, and provide them the session tracing ID of ZZZZZ.
    	case 40613:
    		return true;
    

    so basically everything related to creating a connection and keeping it alive. SQL Server documentation is pretty good on this, but I found other database documentation pretty vague on which errors do and which don't terminate a transaction for instance.

  21. roji commented on Jul 13, 2020

    @roji
    MemberAuthor

    The PG logic is pretty simple (and somewhat extreme) - any error puts the ongoing transaction in a failed state, and you can't do anything aside from rolling the transaction back (or rolling back to a savepoint).

    But I'm not sure that IsTransient should mean the same thing as "does it terminate the transaction"... I was only thinking of this as an indication that a retry may be successful (even if that retry involves rolling back the transaction and replaying statements). In other words, I'd expect an ORM/retry policy to check this flag, and if it's true, roll back the ongoing transaction (if any) and re-attempt.

    It's true that an error may be transient but not cause transaction termination, and so rolling back the entire transaction to retry may be overkill (it could be possible to just retry the latest command). That doesn't seem terribly important to me as transient exceptions aren't supposed to be that common for it to matter (am I wrong?).

    Does this make sense to everyone? Am I missing something?

  22. KalleOlaviNiemitalo commented on Jul 13, 2020

    @KalleOlaviNiemitalo

    Our application also needs to know whether a different command on a new database connection could succeed, or the entire database or server is down. The application currently recognizes error codes for this purpose but we could perhaps make it instead check which method threw the exception.

  23. roji commented on Jul 13, 2020

    @roji
    MemberAuthor

    @KalleOlaviNiemitalo detecting that the database/server is down is notoriously difficult (e.g. a network issue could indicate the server is down (or not)), am curious what you're current logic for this is...

    But either way this seems to be orthogonal (and so out of scope) for this feature, which is only about identifying transient errors - or do you see things otherwise?

  24. KalleOlaviNiemitalo commented on Jul 13, 2020

    @KalleOlaviNiemitalo

    @roji Our application does not need to distinguish between a network issue, the server being down, and the database being down. It needs to know that those errors do not depend on the database commands that it was running in the transaction.

    I agree that such a feature is not in scope for this issue, but I mentioned it as an example of difficulty in migrating to DbException.IsTransient from application-side recognition of error numbers.

  25. FransBouma commented on Jul 13, 2020

    @FransBouma
    Contributor

    The PG logic is pretty simple (and somewhat extreme) - any error puts the ongoing transaction in a failed state, and you can't do anything aside from rolling the transaction back (or rolling back to a savepoint).

    But I'm not sure that IsTransient should mean the same thing as "does it terminate the transaction"... I was only thinking of this as an indication that a retry may be successful (even if that retry involves rolling back the transaction and replaying statements). In other words, I'd expect an ORM/retry policy to check this flag, and if it's true, roll back the ongoing transaction (if any) and re-attempt.

    It's true that an error may be transient but not cause transaction termination, and so rolling back the entire transaction to retry may be overkill (it could be possible to just retry the latest command). That doesn't seem terribly important to me as transient exceptions aren't supposed to be that common for it to matter (am I wrong?).

    Does this make sense to everyone? Am I missing something?

    I think what you describe is very sensible and in practice it likely leads to redoing the whole transaction again anyway, but I think the key difference with e.g. a UC violation in the middle of a transaction is that the error is outside of the scope of the data, i.e. there's nothing to 'correct' on the client / app side; the only thing it can do is retry the whole unit of work.

    An error in the data, violating a UC, an FK, retrying the same Unit of work will lead to the same error, as the error is inside the scope of the data.

    Would that help determining when the IsTransient flag should be set or not?

  26. roji commented on Jul 13, 2020

    @roji
    MemberAuthor

    @ KalleOlaviNiemitalo

    I agree that such a feature is not in scope for this issue, but I mentioned it as an example of difficulty in migrating to DbException.IsTransient from application-side recognition of error numbers.

    Yeah, IsTransient unfortunately won't solve everything requiring applications to look at provider-specific error numbers. Note that there's SqlState which is also being added to DbException (#35601), which could also help (e.g. for recognizing unique constraint violations across databases).

    @FransBouma

    An error in the data, violating a UC, an FK, retrying the same Unit of work will lead to the same error, as the error is inside the scope of the data.

    There could conceivably be some variation here across products... If retrying the UoW means retrying the exact same statements (with the same ID values), then yeah, the same error should be reproduced; that's why I think that UC/FK violations shouldn't be treated as transient. But it's possible that for some ORM, retrying would also mean generating new IDs, in which case the UC/FK violations would no longer occur.

    I do think that in the general case data issues shouldn't be treated as transient - am interested in any other views though.

  27. ghost locked as resolved and limited conversation to collaborators on Dec 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Data

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions