📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

When does the Object Pool pattern help in .NET, and when does it make things slower? Explain ObjectPool<T>, ArrayPool<T>, DbContext pooling and connection pooling, the bugs that come from resetting pooled objects badly, and how you would prove a pool is worth it.

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.

Senior Theory Advanced arraypool design-patterns ef-core gc object-pool performance

🎯 Key points

  • Object Pool keeps reusable instances so callers rent and return them instead of allocating; it pays off when creation is expensive (sockets, large buffers, LOH arrays) or churn is very high
  • Microsoft.Extensions.ObjectPool: ObjectPool<T>.Get/Return, IPooledObjectPolicy<T> (Create, Return(bool) to reset or reject), IResettable.TryReset (.NET 8+), MaximumRetained default ProcessorCount * 2
  • A pool caps idle objects retained, not objects created: under a burst Get() keeps creating, and extras are dropped on return, so it is not a concurrency limit
  • ArrayPool<T>.Shared.Rent(n) returns an array of at least n (often larger); Return(array, clearArray) and never touch it again; sensitive data must be cleared
  • AddDbContextPool<T> (default pool size 1024) resets EF's own state (change tracker, options) per lease, but not fields you add; constructor runs once, so no scoped services in it
  • ADO.NET connection pooling is per exact connection string (Max Pool Size 100 by default); leaked connections cause 'Timeout expired... obtaining a connection from the pool'
  • Gen0 allocation is a pointer bump; a pool adds Interlocked synchronisation and cross-core contention, reset work and keeps objects alive into gen2 (card-marking cost), so pooling small cheap objects is often slower
  • Prove it: BenchmarkDotNet with MemoryDiagnoser under concurrency, then dotnet-counters (allocation rate, gen0/gen2 counts, % time in GC) and p99 latency under load; test that a returned object equals a fresh one

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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>.Shared pools arrays. Rent(n) gives you at least n elements, often more, and once you Return it you must never touch it again. AddDbContextPool reuses DbContext instances and resets EF's change tracker, but not fields you added yourself. For my own types there's ObjectPool<T> in Microsoft.Extensions.ObjectPool, with a policy that creates and resets objects. From .NET 8 an object can implement IResettable.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."


Pools in .NET

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

When a pool helps vs hurts

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)

Production example

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.

πŸ” What the interviewer is checking

Checks senior-level performance judgement: understanding the GC well enough to know when pooling helps, and the correctness risks it brings.

Green flags

  • Explains why gen0 allocation is cheap and pooling can be slower.
  • Knows the framework pools and their specific gotchas (Rent length, clearArray, pooled DbContext fields).
  • Treats reset bugs as data-leak risks.
  • Proposes BenchmarkDotNet plus production counters and p99 latency as evidence.

Red flags

  • "Pooling always improves performance."
  • Uses pooled objects after return or ignores reset.
  • Fixes connection-pool timeouts by raising Max Pool Size.

πŸ“š Learn in depth

1. Structure

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.

2. Microsoft.Extensions.ObjectPool internals

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.

3. ArrayPool<T>.Shared

Arrays 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.

4. DbContext pooling

AddDbContextPool<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:

  • The constructor runs once per pooled instance, so it can only take DbContextOptions<T>; scoped services (current tenant) can't be injected.
  • Fields you add (public int TenantId { get; set; }) are not reset automatically.
  • For per-tenant state, use 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.

5. Connection pooling

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.

6. Why pooling can be slower

  • Allocation is cheap: gen0 allocation is a bump of a per-thread pointer; collecting dead gen0 objects costs nothing per object.
  • Pools cost synchronisation: Interlocked operations and cache-line contention across cores.
  • Pooled objects get old: they survive into gen2. When a gen2 object references newly allocated objects, the GC's write barrier marks cards, and gen0 collections must scan those cards.
  • Reset cost: clearing a large array or a complex object can cost more than allocating a fresh one.

7. Measuring

  1. Micro: BenchmarkDotNet with [MemoryDiagnoser], and [ThreadingDiagnoser] or a multithreaded benchmark to include contention.
  2. Macro: load test (k6, Azure Load Testing) while watching dotnet-counters monitor --counters System.Runtime: allocation rate, gen0/gen1/gen2 counts, % time in GC, heap size; plus p95/p99 latency.
  3. Decide on p99 latency and CPU, not on allocations alone.

Try it yourself

  1. Benchmark new StringBuilder() vs ObjectPool<StringBuilder> for building a 200-character string, single-threaded and with 16 threads.
  2. Benchmark new byte[200_000] vs ArrayPool<byte>.Shared.Rent(200_000) and watch gen2 counts.
  3. Add a TenantId field to a pooled DbContext, set it in one request and observe it in the next.
  4. Write a unit test that rents a buffer, returns it, and asserts no code path uses it afterwards (wrap with a guard type in Debug builds).

πŸ’» Code

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); }
    }
}

⚠ Common mistakes

  • Mistake: Pooling small, cheap objects (DTOs, short lists). Why it is wrong: Gen0 allocation is cheaper than the pool's synchronisation and reset, and pooled objects age into gen2. Instead: Allocate normally; pool only what benchmarks show is expensive.
  • Mistake: Using a rented array or pooled object after returning it. Why it is wrong: Another request may already own it, so you corrupt or leak their data. Instead: Return in finally as the last use, and null out local references.
  • Mistake: A reset that misses a field (user ID, tenant, flags). Why it is wrong: The next renter inherits the previous user's state, which is a data leak. Instead: Reset every field in one place (TryReset), and test that a returned object is indistinguishable from a new one.
  • Mistake: Assuming 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).
  • Mistake: Returning buffers that held personal or secret data without clearing. Why it is wrong: The next renter can read it, and it could reach a response or a log. Instead: Return(buffer, clearArray: true) for sensitive data.
  • Mistake: Adding per-request fields to a pooled 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.
  • Mistake: Raising 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.
  • Mistake: Pooling objects whose size varies widely, like 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.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions use-after-return or clearArray Why: Checks debugging of ArrayPool misuse in production
    How to answer

    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.

  2. When: Candidate says gen0 allocation is a pointer bump or mentions the LOH Why: Checks heap allocation internals, generations and the LOH
    How to answer

    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.

πŸ›  Real-world problems: how you handle them

Pooled render context leaked one customer's ID into another's PDF
Situation
A document rendering service on .NET [10] in Azure Australia East producing [~300] invoices per second for [a utilities retailer]. A custom `ObjectPool<RenderContext>` had been added to reduce GC pressure.
Signals
A customer reported an invoice footer showing another customer's account number. Application Insights showed no errors. The issue appeared only under load and in [~0.02%] of documents.
Investigation
Reviewed the pooled type: `CustomerAccount` was added in a later change but not cleared in the policy's `Return`. Reproduced with a test that rents, sets the account, returns, rents again and asserts the account is null. It failed. Also checked `ArrayPool` usage: buffers were returned without `clearArray`.
Resolution
Immediate: disabled pooling via configuration (allocation-based fallback), accepting [~15%] higher CPU. Real fix: moved reset into `IResettable.TryReset` covering every field, cleared buffers on return, and added a test that compares a returned object with a fresh one using reflection. Ran a Notifiable Data Breaches assessment for the affected documents.
Prevention
A reflection-based test fails if a new field isn't reset; pooled types must implement `IResettable`; `clearArray: true` for any buffer holding personal data; a review checklist item for any change to pooled types.

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.

↩ Usually asked after

More in Creational Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me