radoll
radoll

Reputation: 21

Why would npgsql be throwing two different errors for timing out?

I have an ASP.NET Core Web API using EF Core. I'm trying to implement timeout middleware as shown here:

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
    int commandTimeoutInSeconds;

    if (context.Request.Path.StartsWithSegments("/shorterTimeout"))
    {
        commandTimeoutInSeconds = _appConfig.shorterTimeout;
    }
    else
    {
        var conn = new NpgsqlConnectionStringBuilder(_appConfig.ConnectionString);

        if (conn.TryGetValue("Command Timeout", out object? commandTimeout))
        {
            commandTimeoutInSeconds = Convert.ToInt32(commandTimeout);
        }
        else
        {
            // assume a default of 30
            commandTimeoutInSeconds = defaultCommandTimeoutInSeconds;
        }
    }

    var dbContext = context.RequestServices.GetRequiredService<ApplicationContext>();

    dbContext.Database.SetCommandTimeout(commandTimeoutInSeconds);

    await next(context);
}

This appears to work as expected. The API routes time out as I would expect, except for some routes, I get an NpgsqlException that says

Timeout during reading attempt

but then on other routes, I get this same exception back, but as the inner exception for an

InvalidOperationException: an exception has been raised that is likely due to a transient failure

Does anyone know why this might be?

I tried a few things. I tried adjusting the queries tripping the exceptions to see if their complexity played a part. I saw no evidence that that would be the case. I did some digging to see if maybe EF Core automatically retries queries to see if that was it, but there's nothing in our codebase to suggest that we're enabling that behavior, nor does it seem like that behavior is enabled by default.

Upvotes: 2

Views: 77

Answers (0)

Related Questions