[Bug]: First builder access synchronously waits for Docker discovery and can starve the thread pool
Maintainers usually reply within 1 day
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 25/100
- Issue type
- Bug
- Clarity
- Needs clarification
- Activity status
- Active
- Tech stack
- csharp, docker
- Domain
- backend, infrastructure, testing-qa
Research direction
Start with NetworkBuilder.cs, AbstractBuilder.cs, TestcontainersSettings.cs, and DockerEndpointAuthenticationProvider.cs, then run the standalone capped-pool reproduction. Trace static initialization, endpoint-provider selection, and IsAvailable() before comparing the proposed asynchronous discovery directions. Done means an agreed supported approach plus regression coverage for shared discovery, endpoint selection, cancellation, failures, and non-blocking callers.
Written by the indexing model from the issue text.
Description
What happened?
The first new NetworkBuilder() in a process performs Docker endpoint discovery through TestcontainersSettings static initialization. Discovery queues asynchronous work to the thread pool and synchronously waits for its result. Other threads accessing the same type must wait for static initialization to finish.
This creates a dependency on an additional available pool worker while the calling workers are blocked. Under concurrent first access, the CLR's type-initialization synchronization can amplify the blocking. I would like to discuss a supported asynchronous discovery path before proposing a change to the builder API.
This investigation follows TUnit #6904, which reports startup delays when Testcontainers is first used in the synchronous prefix of a fixture initializer. TUnit also has its own separate Lazy<Task> contention problem. The reproduction below uses the real Testcontainers package without TUnit or any shared fixture.
Source evidence
The following links are pinned to develop commit aabb0b0affab69516081eb8f3f241611d25dcc6f:
NetworkBuilderconstructor callsInit().AbstractBuilder.Init()readsTestcontainersSettings.OS.DockerEndpointAuthConfig.TestcontainersSettingsselects the first applicable and available provider during static initialization.IsAvailable()callsTaskFactory.StartNew(async ... PingAsync ...).Unwrap().ConfigureAwait(false).GetAwaiter().GetResult(); that factory usesTaskScheduler.Default.
The last two files have identical content in the tested 4.15.0 package's source commit, 37352559c0af87d5c7eeaced1accc2d21e3a4e69.
Minimal reproduction without TUnit
This is intentionally a capped-pool scheduling diagnostic, not a benchmark of normal Docker startup. Run each mode in a fresh process. The limit applies only to that process.
All four pool workers reach a starting gate before any builder is constructed. After construction returns or throws, the harness deliberately keeps that worker occupied too. Thus a worker cannot accidentally become available and start the queued discovery operation. The main thread takes a snapshot after two seconds and exits the process without releasing the workers.
Save this as repro.cs and use .NET SDK 10:
dotnet run --file repro.cs -- --control
dotnet run --file repro.cs
Complete reproduction
#:package [email protected]
#:property NuGetAudit=false
using System;
using System.Threading;
using DotNet.Testcontainers.Builders;
const int workers = 4;
bool control = Array.IndexOf(args, "--control") >= 0;
ThreadPool.GetMinThreads(out _, out int minIo);
ThreadPool.GetMaxThreads(out _, out int maxIo);
if (!ThreadPool.SetMinThreads(workers, minIo) ||
!ThreadPool.SetMaxThreads(workers, maxIo))
{
Console.WriteLine("Unable to configure the diagnostic worker limit.");
return 2;
}
using var ready = new CountdownEvent(workers);
using var start = new ManualResetEventSlim(false);
using var holdWorkers = new ManualResetEventSlim(false);
int entered = 0;
int completed = 0;
int failed = 0;
for (int i = 0; i < workers; i++)
{
ThreadPool.QueueUserWorkItem(_ =>
{
ready.Signal();
start.Wait();
Interlocked.Increment(ref entered);
try
{
if (control)
{
_ = new object();
}
else
{
_ = new NetworkBuilder();
}
Interlocked.Increment(ref completed);
}
catch (Exception exception)
{
Interlocked.Increment(ref failed);
Console.WriteLine("Constructor exception type: " + exception.GetType().FullName);
}
finally
{
// Keep all four workers occupied even if construction returns or throws.
// This prevents a queued Docker probe from starting during the diagnostic.
holdWorkers.Wait();
}
});
}
if (!ready.Wait(TimeSpan.FromSeconds(10)))
{
Console.WriteLine("Workers did not reach the starting gate.");
Environment.Exit(2);
}
start.Set();
Thread.Sleep(TimeSpan.FromSeconds(2)); // The main thread is not a pool worker.
ThreadPool.GetAvailableThreads(out int available, out _);
ThreadPool.GetMaxThreads(out int actualMax, out _);
Console.WriteLine($"Mode: {(control ? "control" : "NetworkBuilder")}");
Console.WriteLine($"Maximum workers: {actualMax}");
Console.WriteLine($"Entered: {Volatile.Read(ref entered)}");
Console.WriteLine($"Constructors completed: {Volatile.Read(ref completed)}");
Console.WriteLine($"Constructors failed: {Volatile.Read(ref failed)}");
Console.WriteLine($"Available workers: {available}");
Console.WriteLine($"Pending pool work items: {ThreadPool.PendingWorkItemCount}");
// Exit without releasing workers: no Docker probe or resource creation is needed.
Environment.Exit(0);
return 0;
Observed output:
Mode: control
Maximum workers: 4
Entered: 4
Constructors completed: 4
Constructors failed: 0
Available workers: 0
Pending pool work items: 0
Mode: NetworkBuilder
Maximum workers: 4
Entered: 4
Constructors completed: 0
Constructors failed: 0
Available workers: 0
Pending pool work items: 1
The output establishes lack of constructor progress during the observation interval. The queued-work counter alone does not identify the callback; the source above explains the dependency on the same exhausted pool. The control completes its constructors under the same harness.
With the normal, uncapped pool, the runtime can inject more workers. This diagnostic does not claim that ordinary runs deadlock, or establish a particular delay with default settings.
Testcontainers version
4.15.0, using the published NuGet package already present in the local package cache.
Using the latest Testcontainers version?
Yes. The reproduction was run against 4.15.0, confirmed as the latest stable GitHub release when this report was prepared. The relevant implementation was also checked on develop at the commit linked above; this report does not claim a build or test run of that checkout.
Host OS / architecture / .NET version
Windows, OS version 10.0.26200, x64. .NET SDK 10.0.401, runtime 10.0.12.
Docker version / Docker info
Not collected. The diagnostic keeps all pool workers occupied and exits without allowing the queued probe to start. It does not call Build(), StartAsync(), or create Docker resources. No real Docker startup measurements are claimed.
Expected behavior and design questions
A supported asynchronous initialization path should allow concurrent callers to await shared Docker discovery without blocking one worker per caller, and discovery should not run while holding CLR type-initialization synchronization.
Would either of these directions fit the project?
- An explicit asynchronous discovery/initialization API. Callers could await it once before constructing builders. This could preserve synchronous builder behavior for existing callers, but it would only help callers that opt in. It introduces a public initialization step and shared state whose cancellation and failure semantics need to be defined.
- Resolve the default endpoint at an existing asynchronous resource operation, such as container
StartAsync()or network/volumeCreateAsync(). This would avoid network discovery during builder construction, but requires representing an unresolved default endpoint and reconsidering whenBuild()validates Docker availability.
These are alternatives for discussion, not a request to implement both. In particular, current Validate() can fail during Build() and aggregate discovery exceptions. Moving that failure to an asynchronous operation changes observable behavior.
Any agreed approach should account for provider priority, explicit endpoint overrides, useful diagnostics, cancellation of an individual waiter, and whether failed discovery is cached or can be retried. #1562 discusses a related first-probe/retry problem, but not this scheduling dependency.
Alternatives and validation scope
Warming up Testcontainers before parallel work can avoid concurrent first access, but still performs synchronous discovery and may contact Docker in a run that does not otherwise need it. Fixing TUnit's separate initialization lock helps its shared-fixture scenario; it does not remove Testcontainers' static initialization dependency.
Adding another Task.Run around discovery would still leave a synchronous wait and a dependency on pool capacity.
If an asynchronous path is agreed, a useful regression check would gate discovery completion, start several callers, and verify that waiting callers return incomplete tasks without synchronously occupying their calling threads, while shared discovery starts only once. Compatibility checks should cover endpoint selection and the agreed error/cancellation behavior.
Only the standalone reproduction above was built and run here. The Testcontainers repository test suite and real-Docker scenarios were not run.
- Dominant language
- C#
- Stars
- 4.4k
- Forks
- 366
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 19
Getting set up
Starts the project's dev container in your browser, under your own GitHub account.
- Ships a Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from testcontainers/testcontainers-dotnet
-
[Bug]: Container with port binding that exits during startup throws TimeoutException after 15 s instead of ContainerNotRunningExceptionPossibly taken @seragAhmed claimed this 16 days ago. Openbug
Difficulty 3/5 1-2 days Newbie friendliness 72/100
testcontainers/testcontainers-dotnet#1819 · 1 comment ·
Maintainers usually reply within 1 day
-
[Enhancement]: Add .NET MiniStack moduleMay be free again A pull request for this issue was closed without being merged. Openenhancement module
Difficulty 4/5 3-5 days Newbie friendliness 24/100
testcontainers/testcontainers-dotnet#1804 ·
Maintainers usually reply within 1 day
-
[Enhancement]: Support for TUnitPossibly taken @zcsizmadia claimed this 77 days ago. Openenhancement module
Difficulty 4/5 3-5 days Newbie friendliness 48/100
testcontainers/testcontainers-dotnet#1766 · 2 comments · 1 reaction ·
Maintainers usually reply within 1 day
-
[Enhancement]: DuckDB nuget packagePossibly taken @rosian22 claimed this 84 days ago. Openenhancement module
Difficulty 3/5 1-2 days Newbie friendliness 72/100
testcontainers/testcontainers-dotnet#1749 · 1 comment ·
Maintainers usually reply within 1 day
-
bug
Difficulty 4/5 3-5 days Newbie friendliness 45/100
testcontainers/testcontainers-dotnet#1562 · 1 comment ·
Maintainers usually reply within 1 day
All issues in testcontainers/testcontainers-dotnet
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
Forrest-Technologies/drover#1374 ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
Maintainers usually reply within 1 day
-
good first issue help wanted
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
erkamyaman/rust-anything#1381 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
arastella625/DAORework#280 ·
Maintainers usually reply within 1 day