Skip to content

Fail-over, how can i use it? #5157

Closed as not planned
Closed as not planned

Description

@seriouz

I have a cluster with three Nodes: Master, Standby and Witness controlled via Repmgr.
The syncing and fail-over works from the clusters stand point. When i kill the master the standby is elected as the new master and when the machine comes back it is the new standby. All good.

But now i want to setup EF Core to make use of this cluster.

I have this configuration:

var connString = "Host=server1:6430,server2:6431;Host Recheck Seconds=5;" +
                "Username=user;Password=password;Database=database;" +
                "Target Session Attributes=read-write;Tcp Keepalive=true";

Now when i kill the server1 i get the following error, but i thought that EF Core would switch to the other server:

Npgsql.NpgsqlException (0x80004005): Unable to connect to a suitable host. Check inner exception for more details.
 ---> System.AggregateException: One or more errors occurred. (Failed to connect to server1:6430)
 ---> Npgsql.NpgsqlException (0x80004005): Failed to connect to server1:6430
 ---> System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.

Here is the test app:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;

using var context = new AppDbContext();

var pendingMigrations = context.Database.GetPendingMigrations();
if (pendingMigrations.ToList().Count > 0)
{
    await context.Database.MigrateAsync();
}

for (var i = 0; i < 100000000; i++)
{
    try
    {
        var newTest = new Test
        {
            Username = $"u{i}",
            Age = Random.Shared.Next(10, 100),
        };
        context.Tests.Add(newTest);
        await context.SaveChangesAsync();
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message);
        // context.Database.OpenConnection();
    }

    var test = await context.Tests.ToListAsync();
    Console.WriteLine(JsonSerializer.Serialize(test.Last()));

    await Task.Delay(TimeSpan.FromSeconds(1));
}

public class AppDbContext : DbContext
{
    public DbSet<Test> Tests { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        var connString =
            "Host=server1:6430,server2:6431;Host Recheck Seconds=5;" +
            "Username=user;Password=password;Database=database;" +
            "Target Session Attributes=read-write;Tcp Keepalive=true";
        options.UseNpgsql(connString, o => 
        {
        }).UseLowerCaseNamingConvention();
    }
}

[Table("test")]
public class Test
{
    [Key]
    public int Id { get; set; }
    public string Username { get; set; } = string.Empty;
    public int? Age { get; set; } = 0;
}

Activity

  1. transferred this issue fromnpgsql/efcore.pgon Jul 16, 2023
  2. vonzshik commented on Jul 17, 2023

    @vonzshik
    Contributor

    From what I remember, failover isn't instantaneous, so the issue you're probably encountering is:

    1. Primary is killed, repmgr begins to make sure standby is up to date
    2. While opening a connection the first host is dead, but the second host it still a standby, so you get an exception (and the fact that the second host is a standby is cached for 5 seconds)
    3. Eventually the standby is promoted to primary
  3. NinoFloris commented on Mar 12, 2024

    @NinoFloris
    Member

    @vonzshik you're saying we correctly update the primary state to offline during Break() but we don't consider the next host in the list a primary yet so it fails our stateValidator check until its state is expired? Shouldn't we clear out (or mark them as ignored) all alternative host states when a host goes offline?

  4. vonzshik commented on Mar 13, 2024

    @vonzshik
    Contributor

    @vonzshik you're saying we correctly update the primary state to offline during Break() but we don't consider the next host in the list a primary yet so it fails our stateValidator check until its state is expired?

    It's not really us considering it as primary (it kinda is but it's not the main problem), but the next host itself is still a standby. Failover and promotion are asynchronous by design, it can take multiple seconds for a standby to be promoted to a primary, while the previous primary is already down. Even if we do clear the state of all the hosts it's not really going to help much since all we're going to get are standy's until one of them is eventually promoted.

  5. NinoFloris commented on Jun 27, 2024

    @NinoFloris
    Member

    I was aware of the delay on the server side, however what surprises me is that it looks like we're not waiting at all for hot standby's to get promoted.

    What seems to be lacking for the expected failover support is that once we have determined no host matches we don't wait a 'Math.Max(connection timeout, Host Recheck Seconds)' period of time to determine whether some next host might become a candidate.

    Today we try the primary - it succeeds the state check but fails with a socket error - then we try the standby host, we either have a cached database state and skip this host due to it not being a primary (likely) or we immediately open/take an idle connection, read pg_is_in_recovery() and default_transaction_read_only and determine it's not suitable if promotion hasn't occurred yet. Both of these checks can be completed within a second, leaving almost no time for promotion to actually take place.

    This seems to miss a lot of cases where failover is in progress. We should try to improve our handling here.

  6. NinoFloris commented on Jun 27, 2024

    @NinoFloris
    Member

    OK so I've found our old tracking issue where this particular problem is described in a TODO as well: #5157 (comment)

    I've converted it to an issue #5769 and will close this one.

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