Skip to content

Received unexpected backend message DataRow when using Npgsql version 8.0.3 #5803

Open

Description

@sergey-fuflygin

Steps to reproduce

The issue occurred only once in our production environment, and we haven’t been able to reproduce it since. The exception was triggered during the execution of a query using Dapper in our application.

The issue

We encountered an unexpected exception with the message Received unexpected backend message DataRow. Please file a bug. This occurred while using Npgsql version 8.0.3. The error was captured during a high error rate incident in our service.

In addition to the primary error, our database started failing and generated multiple errors at the same time:

  • 40001: Canceling statement due to conflict with recovery
  • Connection reset by peer
  • 57014: Canceling statement due to conflict with recovery
  • 57P03: The database system is starting up
  • Timeout during reading attempt

Exception message:

System.Exception: Received unexpected backend message DataRow. Please file a bug.

Stack trace:

   at Npgsql.Internal.NpgsqlConnector.UnexpectedMessageReceived(BackendMessageCode received)
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(Boolean async, CommandBehavior behavior, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteReader(Boolean async, CommandBehavior behavior, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
   at Dapper.SqlMapper.MultiMapAsync[TFirst,TSecond,TThird,TFourth,TFifth,TSixth,TSeventh,TReturn](IDbConnection cnn, CommandDefinition command, Delegate map, String splitOn) in /_/Dapper/SqlMapper.Async.cs:line 940

Further technical details

  • Npgsql version: 8.0.3
  • PostgreSQL version: 14.9
  • Operating system: Debian 12

Other details about my project setup:

  • We are using Dapper for data access.
  • The exception occurred during high traffic in service.
  • Our database setup includes Amazon Aurora RDS with one writer and multiple reader instances, with Dapper and Npgsql pointing to the reader replicas.

Activity

  1. roji commented on Aug 11, 2024

    @roji
    Member

    @sergey-fuflygin this sort of random protocol corruption under high load is typically the result of an application bug, where the same connection is accidentally used concurrently from multiple threads. I'd suggest carefully reviewing how your databases are managed and making sure no single NpgsqlConnection is ever shared or managed across threads. Inspecting the stack traces of the errors may give you a clue where the problematic sites are.

    Beyond this, you can try reproducing this in a minimal repro, by spinning up many threads and repeatedly executing the suspected workloads until the error occurs. If you manage to do this and are convinced there's nothing wrong with your code, oyu can post that code sample for us to investigate.

  2. sergey-fuflygin commented on Aug 11, 2024

    @sergey-fuflygin
    Author

    @roji, thank you for the feedback.

    I wanted to clarify that our application code follows best practices for managing NpgsqlConnection instances, ensuring they are not shared across threads. Below is a summary of how we handle connections:

    • We create a new NpgsqlConnection instance for each operation using a PostgresConnectionFactory. This ensures that each thread or request gets its own fresh connection.
    • The connection is used locally within the scope of each method and is disposed of after the operation is complete.
    • We do not use any static or globally shared connection instances, which minimizes the risk of thread contention or protocol corruption.

    Here’s a relevant code snippet for context:

        public IDbConnection Get()
        {
            try
            {
                return new NpgsqlConnection(_connectionString);
            }
            catch (Exception ex)
            {
                _loggerAppService.Error($"Cannot establish NpgsqlConnection with connection string {_connectionString}", ex);
                throw;
            }
        }
    
        public async Task<T> ExecuteAsync<T>(Func<IDbConnection, Task<T>> fn, int retryCount = 1)
        {
            using var connection = _connectionFactory.Get();
            return await fn(connection);
        }
    

    The issue occurred during our regular throughput of 80k RPM, which is well within our system’s capacity (it can scale up to 200k RPM without issues). Given that our application is designed to handle connections in a thread-safe manner, we believe the problem might be related to the occasional restart of the read replica. This is indicated by the 57P03: The database system is starting up error.

    I submitted this issue to see if it could be related to specific conditions within the Npgsql library, particularly in scenarios where read replicas are restarting. If there’s anything more we should investigate on our side or any additional insights you could provide, it would be greatly appreciated.

    Thank you again for your guidance.

  3. roji commented on Aug 12, 2024

    @roji
    Member

    /cc @vonzshik @NinoFloris for the read replica restart angle.

    The best way to help with this, is to come up with some sort of repro that we could execute on our side, and see the issue happening. This doesn't happen to be a traditional, 100% reliable repro (usually not possible in these cases), but if there's indeed a bug in Npgsql with regards to read replica restarts, then it should be possible to write a simple console program (with lots of concurrency and looping), run it, and then manually restart the read replica(s) and see the bug occuring.

    Otherwise, without any sort of repro, we have no way of knowing that this isn't some sort of issue in your actual application.

  4. NinoFloris commented on Aug 12, 2024

    @NinoFloris
    Member

    So while researching the issue I came across this SO answer explaining some of the errors seen here: https://stackoverflow.com/questions/14592436/postgresql-error-canceling-statement-due-to-conflict-with-recovery

    The 40001 error seems to have been a long running query that went over the default WAL apply timeout of 30s coming from max_standby_streaming_delay. All the later errors seem to be transient due to the following shutdown and restart.

    What's not quite clear to me is why we didn't expect a 'DataRow'... As it seems the actual server action was just a cancellation of a running query, how could that generate a DataRow message?

    We unfortunately have a few places where we throw this error, and without line numbers it's difficult to know which one was the culprit.

    It seems valuable enough to improve these Npgsql errors by adding some more details about their origin.

    Regardless it's not unthinkable we have some issue here in Npgsql - these error conditions are so varied, and it's difficult to exercise all of them in tests - but without knowing what batch of queries was sent, whether they were prepared etc., and ideally which line caused this exception we don't have much to go on, unfortunately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions