Object Pool in .NET 10: Microsoft.Extensions.ObjectPool (policies, IResettable, MaximumRetained), ArrayPool<T>.Shared, AddDbContextPool, ADO.NET connection pooling, reset and use-after-return bugs, why pooling can be slower than gen0 allocation, and measuring with BenchmarkDotNet and dotnet-counters.
Object Pool keeps reusable objects so callers rent and return them instead of allocating. In .NET it helps when objects are expensive to create or are large (connections, big buffers, arrays over 85 KB that land on the LOH), or when churn is extreme.
ObjectPool<T> (Microsoft.Extensions.ObjectPool): a policy creates and resets objects, IResettable exists from .NET 8, and it retains ProcessorCount * 2 objects by default.ArrayPool<T>.Shared: Rent can return a bigger array than you asked for, and you must never touch it after Return.AddDbContextPool resets EF state but not your own fields. Connection pooling is automatic per connection string.Pooling can be slower: a gen0 allocation is a pointer bump, while a pool adds synchronisation, reset cost and long-lived objects. Bad resets leak data between users. Prove the benefit with BenchmarkDotNet and dotnet-counters before adopting a pool.
"An object pool keeps a set of reusable instances: you rent one, use it, and return it, instead of allocating a new one each time. In .NET the GC makes small allocations very cheap. A gen0 allocation is basically a pointer bump, and short-lived objects die young for almost nothing. So a pool only wins when the object is expensive to create or to collect. Database connections and sockets cost a network round trip. Large buffers over 85 KB go on the large object heap and are only collected in gen2. Heavily reused builders and serialiser buffers are the other common case.
The framework already pools the important things. Connection pooling in SqlClient is automatic per exact connection string, with a default maximum of 100.
ArrayPool<T>.Sharedpools arrays.Rent(n)gives you at least n elements, often more, and once youReturnit you must never touch it again.AddDbContextPoolreusesDbContextinstances and resets EF's change tracker, but not fields you added yourself. For my own types there'sObjectPool<T>in Microsoft.Extensions.ObjectPool, with a policy that creates and resets objects. From .NET 8 an object can implementIResettable.TryReset. For example, at [company] we had [a PDF rendering service] where I pooled [large render buffers]: allocation rate dropped from [~800 MB/s] to [~60 MB/s], and p99 latency fell from [450 ms] to [180 ms] because gen2 collections almost disappeared. [I also measured a second pool, for small DTOs, which was 15% slower than plain allocation, so we removed it.]The mistake I see is pooling by default. A pool adds synchronisation, reset work, and objects that live into gen2, where every write to them from young objects costs card-marking. And the bugs are nasty. A reset that misses one field leaks one user's data to the next request, and use-after-return corrupts someone else's response. I only pool what a benchmark and production counters say is worth pooling."
| Pool | What it pools | Key behaviour | Classic failure |
|---|---|---|---|
| SqlClient connection pool | Physical DB connections | Per exact connection string, Max Pool Size=100 default |
Leaked connections β "Timeout expired β¦ obtaining a connection from the pool" |
ArrayPool<T>.Shared |
Arrays | Thread-local + per-core buckets; Rent may return larger |
Use-after-return, assuming .Length, not clearing secrets |
ObjectPool<T> |
Your objects | Policy Create/Return; retains ProcessorCount * 2 by default |
Incomplete reset, unbounded size retained |
AddDbContextPool<T> |
DbContext instances |
Default pool size 1024; EF state reset per lease | Custom fields not reset, scoped services in constructor |
IHttpClientFactory |
HttpMessageHandlers |
Rotated every 2 minutes by default | Capturing a client forever defeats rotation |
RecyclableMemoryStream |
MemoryStream buffers |
Library from Microsoft.IO | Forgetting to dispose returns nothing |
| Helps | Hurts |
|---|---|
| Creation costs I/O or a handshake | Small objects that die in gen0 |
| Large arrays (LOH, > 85 KB) | Objects with complex state that is hard to reset |
| Very high churn with measurable GC pause time | Low traffic: pooled objects just occupy gen2 |
| Fixed-size, uniform objects | Objects whose size varies wildly (pool keeps the biggest) |
A document conversion service rented 1 MB buffers with new byte[1_048_576] per page. Under 300 pages per second, gen2 collections ran every few seconds, and p99 sat at about 900 ms. Moving to ArrayPool<byte>.Shared (with clearArray: true because pages held customer data) cut the allocation rate by about 90% and brought p99 down to around 250 ms. A follow-up review found one path that used the buffer after returning it; an analyser rule and a code-review checklist now cover that.
Checks senior-level performance judgement: understanding the GC well enough to know when pooling helps, and the correctness risks it brings.
Green flags
Rent length, clearArray, pooled DbContext fields).Red flags
Client ββGet()βββΆ ObjectPool<T> ββempty?βββΆ Policy.Create()
β β²
βββReturn(obj)ββββββ Policy.Return(obj): reset; true = keep, false = drop
(drop also when pool already holds MaximumRetained)
The pool is not a resource limit by default: Get() creates a new instance when the pool is empty. It caps how many idle objects are retained, not how many exist.
DefaultObjectPool<T> keeps one item in a fast field for the common single-item case and the rest in a lock-free structure, using Interlocked operations. DefaultObjectPoolProvider.MaximumRetained defaults to Environment.ProcessorCount * 2. DefaultPooledObjectPolicy<T> uses new T() and, from .NET 8, calls IResettable.TryReset() on return if the type implements it. StringBuilderPooledObjectPolicy clears the builder and refuses to keep builders whose capacity exceeds MaximumRetainedCapacity (4 KB by default), so one huge report doesn't pin megabytes forever. Objects you forget to return are simply garbage collected, so there's no leak, but also no benefit.
ArrayPool<T>.SharedArrays are grouped into power-of-two size buckets. Rent(1000) returns a 1,024-element array, and a previously used larger one is possible. The shared pool uses per-thread and per-core caches to minimise contention. Return(array, clearArray: false) is the default for speed, so data from the previous renter remains. Always clear arrays that held personal or secret data (APP 11 in the Privacy Act requires reasonable steps to protect personal information). Requests larger than the biggest bucket are allocated normally and dropped on return.
DbContext poolingAddDbContextPool<AppDbContext>(o => ..., poolSize: 1024) registers a pool. Each request leases an instance; on return EF calls its internal reset, clearing the change tracker, restoring default options and detaching entities. Constraints:
DbContextOptions<T>; scoped services (current tenant) can't be injected.public int TenantId { get; set; }) are not reset automatically.AddPooledDbContextFactory and set state after CreateDbContext(), or override reset behaviour carefully.The gain is modest. It skips context construction and service resolution, which matters in very high-throughput APIs (thousands of requests per second), and is negligible elsewhere.
SqlClient keeps a pool per exact connection string and Windows identity. Open() takes an idle connection or creates one up to Max Pool Size (100); beyond that callers wait up to Connect Timeout, then get "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool." The usual cause is not disposing connections or readers, or long transactions under load, not a pool that is too small. Building connection strings dynamically (per user) fragments the pool.
Interlocked operations and cache-line contention across cores.[MemoryDiagnoser], and [ThreadingDiagnoser] or a multithreaded benchmark to include contention.dotnet-counters monitor --counters System.Runtime: allocation rate, gen0/gen1/gen2 counts, % time in GC, heap size; plus p95/p99 latency.new StringBuilder() vs ObjectPool<StringBuilder> for building a 200-character string, single-threaded and with 16 threads.new byte[200_000] vs ArrayPool<byte>.Shared.Rent(200_000) and watch gen2 counts.TenantId field to a pooled DbContext, set it in one request and observe it in the next.A policy-based pool with safe reset, ArrayPool with try/finally, and pooled DbContext registration:
namespace Rendering;
using System.Buffers;
using Microsoft.Extensions.ObjectPool;
public sealed class RenderContext : IResettable
{
public byte[] Scratch { get; } = new byte[256 * 1024]; // LOH-sized: worth pooling
public List<string> Warnings { get; } = [];
public Guid? CustomerId { get; set; }
public bool TryReset()
{
Warnings.Clear();
CustomerId = null; // forgetting this leaks one customer's ID to the next request
Array.Clear(Scratch); // the buffer held customer data
return Warnings.Capacity <= 1_000; // don't retain an object that grew too big
}
}
public sealed class PageRenderer(ObjectPool<RenderContext> pool)
{
public async Task<int> RenderAsync(Stream input, Guid customerId, CancellationToken ct)
{
RenderContext ctx = pool.Get();
try
{
ctx.CustomerId = customerId;
return await input.ReadAsync(ctx.Scratch, ct);
}
finally
{
pool.Return(ctx); // DefaultPooledObjectPolicy calls TryReset (.NET 8+)
}
}
public static async Task<long> ChecksumAsync(Stream s, CancellationToken ct)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(81_920); // may be larger than requested
try
{
long sum = 0;
int read;
while ((read = await s.ReadAsync(buffer.AsMemory(0, 81_920), ct)) > 0) // use the requested length, not buffer.Length
for (int i = 0; i < read; i++) sum += buffer[i];
return sum;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer, clearArray: true); // never touch buffer after this line
}
}
}
// Program.cs
builder.Services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
builder.Services.AddSingleton(sp => sp.GetRequiredService<ObjectPoolProvider>().Create<RenderContext>());
builder.Services.AddScoped<PageRenderer>();
// Pooled DbContext: the constructor may only take DbContextOptions<T>; no custom per-request fields
builder.Services.AddDbContextPool<AppDbContext>(
o => o.UseSqlServer(builder.Configuration.GetConnectionString("Main")),
poolSize: 1024);
// Prove it before adopting
[MemoryDiagnoser]
public class PoolBenchmarks
{
private readonly ObjectPool<RenderContext> _pool = new DefaultObjectPoolProvider().Create<RenderContext>();
[Benchmark(Baseline = true)] public int Allocate() => new RenderContext().Scratch.Length;
[Benchmark] public int Pooled()
{
RenderContext c = _pool.Get();
try { return c.Scratch.Length; } finally { _pool.Return(c); }
}
}
finally as the last use, and null out local references.TryReset), and test that a returned object is indistinguishable from a new one.ArrayPool.Rent(n) returns exactly n elements. Why it is wrong: It often returns more; code that uses buffer.Length processes stale bytes. Instead: Track the requested length or slice with AsSpan(0, n).Return(buffer, clearArray: true) for sensitive data.DbContext or injecting scoped services into it. Why it is wrong: The constructor runs once and custom fields aren't reset, so tenant state leaks across requests. Instead: Use AddPooledDbContextFactory and set state per lease, or don't pool.Max Pool Size to fix pool timeouts. Why it is wrong: The usual cause is leaked connections or long transactions, so a bigger pool delays the failure. Instead: Find undisposed connections and readers (using/await using) and long-running queries.StringBuilder or MemoryStream. Why it is wrong: The pool retains the largest instances, pinning memory forever. Instead: Reject oversized objects in the policy, or use RecyclableMemoryStream.The .NET GC is very good at short-lived objects, so pooling is an optimisation with a correctness cost. I treat every pool as security-sensitive code, because the failure mode of a bad reset is one customer's data in another customer's response. I start with the framework pools: connection pooling, ArrayPool<T>.Shared, IHttpClientFactory and, only for very high throughput, AddDbContextPool. I add a custom ObjectPool<T> only with a benchmark and production counters behind it.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Plain allocation | Small, short-lived objects | Gen0 GCs (cheap) | LOH arrays, expensive construction |
ArrayPool<T>.Shared |
Temporary buffers, especially > 85 KB | Lifetime discipline | Buffers that escape the method or are stored |
ObjectPool<T> |
Expensive-to-build reusable objects | Reset logic, contention | Objects with complex or varying state |
AddDbContextPool |
Thousands of requests per second | No custom state, limited constructor | Per-tenant context state |
| Caching instead | Immutable, shareable results | Memory | Mutable per-use objects |
My evidence bar: a BenchmarkDotNet run showing time and allocation gains under concurrency, then a load test where p99 latency or CPU improves. Allocation rate alone isn't enough; I've seen pools cut allocations by 90% and make p99 worse because of contention.
Pooling bugs are lifetime bugs: the pool gives a returned array to the next renter, so any code still using it reads or writes someone else's data. The usual causes are use after return (returning in finally while an async continuation, a queued Memory<T> or a lazy enumerable still uses the array), double return (two renters then share one array), treating array.Length as the data length (Rent returns an array at least as large as requested, with old contents), not clearing buffers that held secrets (Return(array, clearArray: true)), and returning arrays not rented from that pool. To debug: reproduce under concurrency, add canaries or a poisoning wrapper pool in tests that fills returned arrays with a marker and detects double returns, trace System.Buffers.ArrayPoolEventSource events, and review every rent for a single owner and a single return in finally.
Each thread allocates from its own allocation context, a small chunk of gen 0 where new is just a pointer bump plus zeroing; when it runs out, the thread asks the GC for another chunk, and when the gen 0 budget is used up, a gen 0 GC runs. The GC is generational because most objects die young: gen 0 collections are cheap, survivors are promoted to gen 1 and then gen 2, which is collected rarely (and mostly in the background). Objects of 85,000 bytes or more go to the large object heap (LOH), which is collected only with gen 2 and isn't compacted by default, so it can fragment. Pinned objects can't be moved, which blocks compaction; the pinned object heap (.NET 5+) keeps long-lived pinned buffers separate. In hot paths I reduce the allocation rate rather than tuning the GC.
How to tell it (STAR)
**S:** At [company] a customer found another customer's account number on their invoice from our rendering service, which produced [~300] documents per second. **T:** I had to stop it, work out how many documents were affected and make sure it couldn't recur. **A:** The only shared state between documents was our object pool. A field added in a later change wasn't being reset, so under load a reused context carried the previous customer's account number. I switched pooling off within [an hour], then moved all reset logic into `TryReset`, cleared buffers on return, and added a reflection test that fails if any field isn't reset. **R:** We identified [N] affected documents for the breach assessment. Re-enabling the fixed pool kept the [~40%] GC reduction, and the test has caught [two] unreset fields in later changes.
Last updated 18 Nov 2026.