question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

CanConnectAsync does not correctly dispose connection when pooling is active

See original GitHub issue

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.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:10 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
rojicommented, Apr 22, 2021

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

1reaction
frabe1579commented, Apr 22, 2021

@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!

Read more comments on GitHub >

github_iconTop Results From Across the Web

.net - Will SqlConnection's Dispose Method Interfere with ...
If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose....
Read more >
SQL Server Connection Pooling - ADO.NET
Connections are released back into the pool when they are closed or disposed. When a SqlConnection object is requested, it is obtained from...
Read more >
ADO.NET Connection Pooling with C# Code Examples ...
This tutorial describes how reusing pooled connections, instead of creating new connections, can improve .NET application performance.
Read more >
c# - Creating database connections - Do it once or for each ...
Always just dispose. It's more secure, and FAST. Do not worry about the overhead of the getting a connection from the pool--it is...
Read more >
Connection Pooling — SQLAlchemy 2.0 Documentation
“Invalidation” means that a particular DBAPI connection is removed from the pool and discarded. The . close() method is called on this connection...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found