Skip to content

Memory Leak on NpgsqlDataSource with password provider #6272

Closed as duplicate

Description

@NikitaCh

There appears to be a memory leak when using EF + NpgsqlDataSource with password provider.

Versions:
Npgsql.EntityFrameworkCore.PostgreSQL - 9.0.4
Npgsql - 9.0.3

Opening it here because it seems to be the issue directly with NpgsqlDataSource, likely with MetricReporter

Image Image

Reproducible example attached - MemoryLeak.zip (includes simple docker-compose with postgres for comfort)

Relevant code breakdown:

AppDbContext.cs

internal class AppDbContext : DbContext
{
    public DbSet<SomeModel> SomeModels { get; set; }

    public DbSet<SomeOtherModel> SomeOtherModels { get; set; }

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<SomeModel>(b =>
        {
            b.HasKey(e => e.Id);
            b.OwnsOne(e => e.JsonModel).ToJson();
        });

        modelBuilder.Entity<SomeOtherModel>(b =>
        {
            b.HasKey(e => e.Id);
        });

        base.OnModelCreating(modelBuilder);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql(@"User ID=postgres;Server=localhost;Port=5433;Database=postgres_db;Pooling=true;", sqlOptions =>
        {
            sqlOptions.EnableRetryOnFailure(maxRetryCount: 3);
            sqlOptions.ConfigureDataSource(dsBuilder =>
            {
                dsBuilder.ConnectionStringBuilder.Host = "localhost";
                dsBuilder.Name = "postgres_db";
                dsBuilder.UsePasswordProvider(_ => Guid.NewGuid().ToString(), (_, _) => ValueTask.FromResult(Guid.NewGuid().ToString()));
            });
        });
        optionsBuilder.UseSnakeCaseNamingConvention();
        base.OnConfiguring(optionsBuilder);
    }
}

Program.cs

using MemoryLeak;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddDbContext<AppDbContext>();

var app = builder.Build();

for(var i = 0; i < 1_000_000; ++i)
{
    using var scope = app.Services.CreateScope();
    var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    await dbContext.Database.CanConnectAsync();

    if (i % 100 == 0)
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        Console.WriteLine($"Iteration: {i}");
        await Task.Delay(3000);
    }
}

From what I can understand, it seems like there is some cache based on ConnectionString, giving the fact that password provider changes the connection string (in this example all the time) - the cache grows indefinitely.

As soon as you change the password provider to return some constant string - everything goes to normal
(For example - dsBuilder.UsePasswordProvider(_ => "constant", (_, _) => ValueTask.FromResult("string"));) :
Image

This is a critical issue, because it is a requirement for a lot of applications to use for example IAM Authorization to connect to RDS - hence use of RDSAuthTokenGenerator for password generation. The application memory grows "indefinitely" in this scenario. The rate of growth seems to be dependent on model size.

Thanks for the help.

Activity

  1. NikitaCh commented on Oct 27, 2025

    @NikitaCh
    Author

    After further investigation, the issue can potentially be actually in efcore.pg where there is exactly that - a cache based on ConnectionString

    I have opened an issue there, would like this to say open for a feedback

  2. NikitaCh commented on Oct 28, 2025

    @NikitaCh
    Author

    After further investigation, the issue can potentially be actually in efcore.pg where there is exactly that - a cache based on ConnectionString

    I have opened an issue there, would like this to say open for a feedback

    After further research and debugging, I do believe the issue is still in this package, particularly in the way DataSource Pool is setup here

  3. roji commented on Oct 28, 2025

    @roji
    Member

    Thanks @NikitaCh, we're looking into this (and thanks @vonzshik for the investigation). It seems that the issue is on the EFCore.PG side, so I'll close this in favor of npgsql/efcore.pg#3646.

  4. NikitaCh commented on Oct 28, 2025

    @NikitaCh
    Author

    Thanks @roji , I would also like to highlight that this issue happens also if you provide the instance of NpgsqlDataSource to UseNpgsql, not only if you use builder.

    So when I was debugging more I saw a constant copy/creation of the instance here

    Hence my comment

    After further research and debugging, I do believe the issue is still in this package, particularly in the way DataSource Pool is setup here

    Just FYI

  5. roji commented on Oct 28, 2025

    @roji
    Member

    @NikitaCh if you believe there's an issue in Npgsql itself (as opposed to EFCore.PG), can you put together a minimal code sample that shows - without using EFCore.PG?

  6. NikitaCh commented on Oct 28, 2025

    @NikitaCh
    Author

    @NikitaCh if you believe there's an issue in Npgsql itself (as opposed to EFCore.PG), can you put together a minimal code sample that shows - without using EFCore.PG?

    @roji, indeed, you are right. This is only partially reproducible with npgsql only in case of quite atypical use like below. In which case the pool keeps growing, but it sooner or later resolves into a complete error on too many connections, so definitely EFCore.PG doesn't just do that 😄

    Though still, maybe, up to discussion, I guess - if password changes but it is the same server and user (and other options), shouldn't the pool be released of "older" versions?

    for (var i = 0; i < 1_000_000; ++i)
    {
        using var connection = new NpgsqlConnection();
        connection.ConnectionString = $"User ID=postgres;Server=localhost;Port=5433;Database=postgres_db;Pooling=true;Password={Guid.NewGuid()}";
        connection.Open();
    
        await using var command = connection.CreateCommand();
        command.CommandText = "SELECT 1";
    
        var success = await command.ExecuteScalarAsync();
    
        if (i % 100 == 0)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            Console.WriteLine($"Iteration: {i}");
            await Task.Delay(3000);
        }
        connection.Close();
    }
    
  7. roji commented on Oct 29, 2025

    @roji
    Member

    @NikitaCh yeah, the above scenario is well-known: you're asking for an infinite number of connection pools to be opened; even if you close the connection, the point of a pool is to keep the physical connection around after it's closed.

    Unfortunately, even if you disable pooling, the internal objects needed for bookkeeping (internal NpgsqlDataSource) still stay around forever. We have #3387 tracking allowing the users to get rid of these via explicit APIs (ClearPool/ClearAllPools), and we could also have a feature where an empty (or non-pooling) data source gets purged after a while.

    But ultimately, creating a connection like this - with a connection string - is now a legacy way to do things; the recommended way is for the user to first create an NpgsqlDataSource and get connections from there. Once that's done, the user is in control of the exact lifetime, and can dispose of the data source when it's no longer needed.

    This makes it IMHO quite a bit less important to fix up the legacy mode to not leak the internal structures - simply switch over to using NpgsqlDataSource if you have this issue. We haven't seen a lot of people running into this, but if we do we can always do work to make it better.

  8. NikitaCh commented on Oct 29, 2025

    @NikitaCh
    Author

    @roji I agree, especially if it is well-known and documented. And yes, as I mentioned - it is quite atypical use nowadays
    Thank you!

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