Skip to content

Map timeout and cancellation SQLSTATEs to transient - #750

Closed
dreamstar-enterprises wants to merge 1 commit into
pgjdbc:mainfrom
dreamstar-enterprises:gh-739
Closed

dreamstar-enterprises wants to merge 1 commit into
pgjdbc:mainfrom
dreamstar-enterprises:gh-739

Conversation

@dreamstar-enterprises

Copy link
Copy Markdown

Make sure that:

  • You have read the contribution guidelines.
  • You have created a feature request first to discuss your contribution intent. Please reference the feature request ticket number in the pull request.
  • You use the code formatters provided here and have them applied to your changes. Don't submit any formatting related changes.
  • You submit test cases (unit or integration tests) that back your changes.

Issue description

Resolves #739.

  • 25P04 → R2dbcTimeoutException
  • 55P03, 57014 → R2dbcTransientResourceException

Previously all three fell through to R2dbcNonTransientResourceException.

New Public APIs

None. The new classes are package-private, like the existing ones.

Additional context

Behaviour change: in Spring, 55P03 and 57014 move from DataAccessResourceFailureException to TransientDataAccessResourceException, and 25P04 to QueryTimeoutException. Neither is a subclass of the old type, so existing catch blocks for it stop matching. Suggest main only.

25P04 (transaction_timeout) now maps to R2dbcTimeoutException.
55P03 (lock_not_available) and 57014 (query_canceled) now map to
R2dbcTransientResourceException rather than falling through to
R2dbcNonTransientResourceException.

[resolves #739]
@mp911de mp911de added the type: enhancement A general enhancement label Sep 21, 2026
@mp911de

mp911de commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator

Thanks a lot. Looking at the overall exception mapping, we seem to have quite a mismatch between what the error label says (this was the primary guide we used during mapping) and how the server behaves. For example, 25P04 transaction_timeout says it is a timeout and the natural instinct of a timeout exception seems plausible. However, 25P04 is a fatal response resulting in connection termination hence a transient exception (like R2dbcTimeoutException) is not correct.

I think the entire mapping requires a larger revision that we can only ship with a new minor release because we would change behavior quite significantly in terms of exceptions.

Here's a collection of other exception mapping cases:

  • Add PostgresqlNonTransientException extends R2dbcNonTransientException (SPI base is abstract, same pattern as PostgresqlTransientException). Make it the default.
  • Reserve NonTransientResource for external failures: classes 08, 53, 58, F0, HV, XX and the fatal 57 codes.
  • Class switch becomes the primary table. Specific-code switch keeps only overrides.

Changes

SQLSTATE Current Proposed Reason
0A feature_not_supported NonTransientResource BadGrammar statement shape not valid on this server
34, 3B, 3D, 3F NonTransientResource BadGrammar undefined cursor / savepoint / database / schema, same flavor as 42P01
54 program_limit_exceeded NonTransientResource BadGrammar too many columns / arguments is a property of the statement
44 with_check_option_violation NonTransientResource DataIntegrityViolation integrity class per SQL standard
0L invalid_grantor, 0P invalid_role_specification NonTransientResource PermissionDenied authorization semantics
53300 too_many_connections NonTransientResource TransientResource retry later succeeds. Connect-time R2dbcException passes through cannotConnect unwrapped, so pools see it
57P03 cannot_connect_now NonTransientResource TransientResource server starting up / in recovery
55006 object_in_use NonTransientResource TransientResource drop while in use, retry later
57014 query_canceled TransientResource Timeout statement_timeout is the dominant source; driver's own setStatementTimeout maps to it. Client cancel / pg_cancel_backend share the code, message text is localized so cannot discriminate
40P01 deadlock_detected (whole class 40) Transient Rollback SPI Javadoc for R2dbcRollbackException names deadlock explicitly. Spring: ConcurrencyFailureException instead of uncategorized. Drop 40000/40001 special cases
09, 0B, 0F, 0Z, 10, 20, 24, 25 (except 25P04), 2B, 2D, 2F, 38, 39, 55 (rest), P0 NonTransientResource NonTransient (plain) program / state errors, not resource failures
  • Class 22: Flip to DataIntegrity(from BadGrammar) to align with JDBC behavior? With bind parameters, these are mostly data concerns and not so much static SQL. This is another occurence where context actually decides over the problem category.
  • Class 26 invalid_sql_statement_name: Mostly a pgbouncer issue but can also happen on server cache out of sync. Right now, it's classified as BadGrammar but fixing SQL is likely not going to help. NonTransientResource?

The somewhat fuzzy nature (also 57014/55P03) where either context of the localized message governs the exception nature makes it really difficult to come up with a proper mapping and arguing about which problem bucket to assign an exception to works in either direction.

So coming back to your initial proposal, it likely makes sense to be pragmatic and consider the most common cause for error codes instead of trying to be right but still making the wrong choice because in most cases, a different exception class would be the better choice.

@dreamstar-enterprises

Copy link
Copy Markdown
Author

Hi Mark,

Ok, it sounds sensible to do a closer examination running up to a minor release.

I don't have much experience with the details of the driver - the mapping of states was something I picked up when
trying to write a downstream error handler to return an appropriate Http Status.

If it helps, this is what I ended up doing, in a Kotlin/Spring WebFlux.

Initial Mapping

The exception type alone wasn't enough to decide a status, so I read the SQLSTATE first, then fall back to the
type, through the extension function ex.httpStatus():

val status = when {
    // a plpgsql RAISE EXCEPTION with no ERRCODE of its own
    sqlState == "P0001" -> null
    // internal_error
    sqlState == "XX000" -> HttpStatus.INTERNAL_SERVER_ERROR
    // no_data_found
    sqlState == "P0002" -> HttpStatus.NOT_FOUND
    // statement_timeout, lock_timeout, idle_in_transaction_session_timeout, transaction_timeout
    sqlState in setOf("57014", "55P03", "25P03", "25P04") -> HttpStatus.GATEWAY_TIMEOUT
    // class 08, connection_exception
    sqlState?.startsWith("08") == true -> HttpStatus.SERVICE_UNAVAILABLE
    // class 40, transaction_rollback
    sqlState?.startsWith("40") == true -> HttpStatus.CONFLICT
    // class 53, insufficient_resources
    sqlState?.startsWith("53") == true -> HttpStatus.SERVICE_UNAVAILABLE
    // anything else: decided by the exception type Spring gave it (see the type mapping further below)
    else -> ex.httpStatus()
}

Points

P0001 returns null because it carries no classification, and one of my later call site falls back to 400, or 404 for a
fetch by id. XX000 and P0002 are custom states raised by my own SQL functions.

Class 40: 40001 and 40000 reach me as CannotAcquireLockException and
PessimisticLockingFailureException, which I answer 409 for. Every other code in the class, including 40P01 deadlock_detected, takes the plain R2dbcTransient branch which I believe reache me as UncategorizedR2dbcException, which I answer 500 for. That's why I have startsWith("40") above: without it a deadlock woulc come back as 500. Mapping the whole class to Rollback would let me delete the line above, so I can fall back on the secondary mapping below.

Secondary Mapping

This is how a SQLSTATE reach me, which I read off r2dbc-postgresql 1.1.1 ExceptionFactory and spring-r2dbc
7.0.1 ConnectionFactoryUtils.convertR2dbcException. The right-hand column is what any revision would move:

  PG SQLSTATE class/code    ->  r2dbc-postgresql R2dbcException  ->  Spring DataAccessException
  ----------------------------------------------------------------------------------------------
  23505                     ->  R2dbcDataIntegrityViolation      ->  DuplicateKeyException
  class 21 / 23 / 27        ->  R2dbcDataIntegrityViolation      ->  DataIntegrityViolationException
  class 08                  ->  R2dbcNonTransientResource        ->  DataAccessResourceFailureException
  42501, 28000, 28P01, "28" ->  R2dbcPermissionDenied            ->  PermissionDeniedDataAccessException
  class 03 / 22 / 26 / 42   ->  R2dbcBadGrammar                  ->  BadSqlGrammarException
  40001                     ->  R2dbcRollback                    ->  CannotAcquireLockException
  40000                     ->  R2dbcRollback                    ->  PessimisticLockingFailureException
  class 40 (e.g. 40P01)     ->  R2dbcTransient (plain)           ->  UncategorizedR2dbcException
  08006 (request queue)     ->  R2dbcTransientResource           ->  TransientDataAccessResourceException
  ANYTHING ELSE (default)   ->  R2dbcNonTransientResource        ->  DataAccessResourceFailureException
  ----------------------------------------------------------------------------------------------
  no SQLSTATE: the connection layer raises this, not the server
  (pool or query timeout)   ->  R2dbcTimeout                     ->  QueryTimeoutException
  ----------------------------------------------------------------------------------------------
  no driver hop: Spring Data raises this itself when a fetch expecting one row gets none
  (empty result)            ->  --                               ->  EmptyResultDataAccessException

The ANYTHING ELSE row is where a PostgresqlNonTransientException default sort of helps me: everything unclassified arrives as a resource failure, which I answer 400 for (see below), so an unmapped server error reads as the caller's mistake.

My type fallback is:

internal fun DataAccessException.httpStatus(): HttpStatus = when (this) {
    is DuplicateKeyException -> HttpStatus.CONFLICT
    is DataIntegrityViolationException -> HttpStatus.CONFLICT
    is PermissionDeniedDataAccessException -> HttpStatus.FORBIDDEN
    is TransientDataAccessResourceException -> HttpStatus.SERVICE_UNAVAILABLE
    is DataAccessResourceFailureException -> HttpStatus.BAD_REQUEST
    is CannotAcquireLockException -> HttpStatus.CONFLICT
    is PessimisticLockingFailureException -> HttpStatus.CONFLICT
    is QueryTimeoutException -> HttpStatus.SERVICE_UNAVAILABLE
    // the query itself is wrong: my fault, not the caller's
    is BadSqlGrammarException -> HttpStatus.INTERNAL_SERVER_ERROR
    is UncategorizedR2dbcException -> HttpStatus.INTERNAL_SERVER_ERROR
    is EmptyResultDataAccessException -> HttpStatus.NOT_FOUND
    else -> HttpStatus.BAD_REQUEST
}

Points

To some of the other points:

Class 22 to DataIntegrity would help. A class 22 failure on a bind parameter is the caller's data, but as
BadGrammar it reaches me as bad SQL, which I answer 500 for.

25P04: agreed it is not transient, though I still return 504, so the caller knows the work ran out of time
even if nothing can be retried in place.

57014: treated as a timeout here too, on the same reasoning that statement_timeout dominates.

Class 26: I am not entirely sure NonTransientResource helps. It arrives as DataAccessResourceFailureException,
which I answer 400 for, so a pooler hiccup blames the caller, while BadGrammar blames me with a 500. Since it
usually clears on reconnect, maybe TransientResource (503)?

Of course I can change my own mapping to suit.

Happy to help / support however I can.

Thank you,

-S

@dreamstar-enterprises dreamstar-enterprises closed this by deleting the head repository Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: enhancement A general enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

R2dbcTimeoutException is never produced, so timeouts are indistinguishable from other non-transient failures

2 participants