Lau
Lau

Reputation: 31

How to gracefully handle a postgres restart in npgsql?

I have a ASP.NET Core application with npgsql that is setup to retry when a database connection fails:

services.AddDbContext<DatabaseContext>(
    opt => opt.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"),
        (options) =>
        {
            options.EnableRetryOnFailure(10);
        })
);

However, when i restart the database during a request, it will first throw an exception

Exception thrown: 'Npgsql.PostgresException' in System.Private.CoreLib.dll: '57P01: terminating connection due to administrator command'

That propogates into my code and causes an exception without any retries.

Looking into the documentation for npgsql it seems like some exceptions are marked as IsTransient, and that means they will be retried, but this one is not. I assume there's a reason for that, but I'd still like to be able to restart the postgres database without interrupting requests by simply having them retry after a while. I could create try catches around all the requests and check for this particular exception, but that seems like a clunky solution.

How do I handle this situation gracefully?

npgsql package used: <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.10" />

Upvotes: 1

Views: 926

Answers (1)

Lau
Lau

Reputation: 31

Managed to find an answer myself, you can add the error code in the EnableRetryOnFailure

services.AddDbContext<DatabaseContext>(
    opt => opt.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"),
        (options) =>
        {
            options.EnableRetryOnFailure(10, TimeSpan.FromSeconds(30), new string[] { "57P01" });
        })
);

Now the only question that remains is if that is a good idea or not.

Upvotes: 2

Related Questions