Repository navigation
Description
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
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"));) :

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
NikitaCh commentedon Oct 27, 2025
After further investigation, the issue can potentially be actually in efcore.pg where there is exactly that - a cache based on
ConnectionStringI have opened an issue there, would like this to say open for a feedback
NikitaCh commentedon Oct 28, 2025
After further research and debugging, I do believe the issue is still in this package, particularly in the way DataSource Pool is setup here
roji commentedon Oct 28, 2025
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.
NikitaCh commentedon Oct 28, 2025
Thanks @roji , I would also like to highlight that this issue happens also if you provide the instance of
NpgsqlDataSourcetoUseNpgsql, 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
Just FYI
roji commentedon Oct 28, 2025
@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?
NikitaCh commentedon Oct 28, 2025
@roji, indeed, you are right. This is only partially reproducible with
npgsqlonly 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 definitelyEFCore.PGdoesn'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?
roji commentedon Oct 29, 2025
@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.
NikitaCh commentedon Oct 29, 2025
@roji I agree, especially if it is well-known and documented. And yes, as I mentioned - it is quite atypical use nowadays
Thank you!