Skip to content

CanConnectAsync does not correctly dispose connection when pooling is active #1812

Closed

Description

@frabe1579

CanConnectasync is called from health checks regularly inside container in a kubernetes cluster, but its use can reach max connections for client.

The problem is reproducible in localhost and in my staging environment.

I've created a test console app (.net 5.0) to reproduce the issue:

using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace NpgsqlTests
{
  static class Program
  {
    static async Task Main(string[] args) {

      var pooling = true;

      var services = new ServiceCollection();
      services.AddDbContext<TestDbContext>(o => {
        o.UseNpgsql($"Host=localhost;Database=npgsqltests;Username=postgres;Password=postgres;Pooling={pooling}");
      });

      using var provider = services.BuildServiceProvider();

      await CreateDatabase(provider);

      await TestQueries(provider);

      await TestCanConnect(provider);
    }

    private static async Task TestCanConnect(ServiceProvider provider) {
      Console.WriteLine("Start connections.");
      for (int i = 0; i < 200; i++) {
        await Task.Delay(100);
        Console.Write($"Connection {i}...");
        var scope = provider.CreateScope();
        var dbContext = scope.ServiceProvider.GetRequiredService<TestDbContext>();
        await dbContext.Database.CanConnectAsync();
        Console.WriteLine(" Done.");
      }
    }

    private static async Task TestQueries(ServiceProvider provider) {
      Console.WriteLine("Start queries.");
      for (int i = 0; i < 200; i++) {
        await Task.Delay(100);
        Console.Write($"Query {i}...");
        var scope = provider.CreateScope();
        var dbContext = scope.ServiceProvider.GetRequiredService<TestDbContext>();
        dbContext.Entities.Add(new TestEntity());
        await dbContext.SaveChangesAsync();
        var c = await dbContext.Entities.CountAsync();
        Console.WriteLine(" Done.");
      }
    }

    private static async Task CreateDatabase(ServiceProvider provider) {
      using (var scope = provider.CreateScope()) {
        var dbContext = scope.ServiceProvider.GetRequiredService<TestDbContext>();
        await dbContext.Database.EnsureCreatedAsync();
      }
    }
  }

  public class TestDbContext : DbContext
  {
    public DbSet<TestEntity> Entities { get; set; }

    public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) {
    }
  }

  public class TestEntity
  {
    public int Id { get; set; }
    public string Text { get; set; }
  }
}

The project has two dependencies:

  <ItemGroup>
    <PackageReference Include="Npgsql" Version="5.0.4" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.5" />
  </ItemGroup>

When var pooling = true, the method TestCanConnect stucks after 100 calls of CanConnectAsync.
I see all the connection in idle state when querying pg_stat_activity.

When var pooling = false, everything runs without problems, and pg_stat_activity is almost empty.

The method TestQueries is used to ensure that usual queries are executed without problems; in fact, it runs successfully regardless of the value of pooling.

I think the problem is in disposal of the connection when connection pooling is temporarily disabled inside CanConnectAsync.

Activity

  1. roji commented on Apr 17, 2021

    @roji
    Member

    Thanks for the repro, I can indeed see an issue - will investigate.

  2. added a commit that references this issue on Apr 17, 2021
    436c926
  3. self-assigned this
    on Apr 17, 2021
  4. added this to the 5.0.6 milestone on Apr 17, 2021
  5. roji commented on Apr 17, 2021

    @roji
    Member

    @frabe1579 I've submitted #1813 to fix this - there's indeed a connection leak in NpgsqlDatabaseCreator.Exists - thanks! For reference, a more complete fix for the source issue is tracked by #1814.

  6. added 2 commits that reference this issue on Apr 17, 2021
    1d28c41
    4213899
  7. taspeotis commented on Apr 19, 2021

    @taspeotis

    We're seeing this too. Am I right in that it was introduced here and it's as simple as downgrading to 5.0.4 to avoid it until 5.0.6 comes out?

    Thanks in advance.

  8. roji commented on Apr 19, 2021

    @roji
    Member

    @taspeotis yes, that's correct.

  9. prcdpr commented on Apr 20, 2021

    @prcdpr

    Hey, wouldn't it make sense to unlist 5.0.5 from NuGet until it's fixed? It broke my app due to connection pool exhaustion and that version is not usable at least in my case.

  10. frabe1579 commented on Apr 21, 2021

    @frabe1579
    Author

    Currently I use 5.0.5 with a custom health check, and the problem disappeared. So i think it's not necessary to unlist.

  11. roji commented on Apr 21, 2021

    @roji
    Member

    FYI I've just released 5.0.5.1 which contains the fix - can you please check and confirm?

  12. modified the milestones: 5.0.6, 5.0.5.1 on Apr 21, 2021
  13. prcdpr commented on Apr 22, 2021

    @prcdpr

    In my case 5.0.5.1 works correctly

  14. frabe1579 commented on Apr 22, 2021

    @frabe1579
    Author

    @roji I've tested 5.0.5.1 in my staging environment, using original health check for ef core, and everything goes well, no more connection exhaustion.

    Thank you very much!

  15. roji commented on Apr 22, 2021

    @roji
    Member

    Thanks for your feedback, and sorry this bug occurred in the first place...

  16. marked hundreds of Idle connections #1823 as a duplicate of this issue on Apr 1, 2025
  17. added theissue type on Jun 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions