Library

Volume 5 · Master Q&A Bank

Notebook
Sign in

Section 14

Coding & Technical Depth Questions

837 words · about 4 min

Q1. Explain how async/await works under the hood, and describe a real deadlock you’ve debugged. The compiler generates a state machine (IAsyncStateMachine); each await captures the current SynchronizationContext and registers a continuation, resuming from the saved state once the awaited task completes. Classic deadlock: a controller action calls an async method with .Result, blocking the request thread while the continuation needs that same thread’s captured context to resume — permanent deadlock. Fix: go async all the way, ban .Result/.Wait() via a Roslyn analyzer, and use ConfigureAwait(false) in library code that doesn’t need the original context.

Q2. Explain a captive dependency bug: injecting a Scoped service into a Singleton. The Singleton captures the Scoped instance (e.g., a DbContext) once at construction and holds it for the app’s entire lifetime — the change tracker accumulates tracked entities indefinitely, causing memory growth and stale data served from what should have been a per-request instance. Fix: never inject the scoped dependency directly into a singleton; inject IServiceScopeFactory and create a new scope per operation instead.

Q3. IEnumerable vs. IQueryable in EF Core — how does the wrong choice cause a production incident? IQueryable builds an expression tree that translates to SQL and applies filters at the database. IEnumerable evaluates in memory. A repository method that returns IEnumerable while wrapping an IQueryable silently forces the entire table into memory before any .Where() is applied by the caller — a real-world version of this loaded 500K rows instead of 50 because .ToList() ran before the filter. Fix: audit repository methods to keep filtering as IQueryable all the way to the final materialization point.

Q4. Design a rate limiter — walk through the algorithm and where you’d apply it. Token bucket: a bucket refills at a fixed rate up to a capacity; each request consumes a token, and requests are rejected when the bucket is empty — naturally allows short bursts up to capacity. Sliding window log/counter is more precise (no burst-at-boundary artifact) but costs more memory/compute. Apply it as ASP.NET Core middleware backed by a ConcurrentDictionary (single instance) or Redis (distributed, multi-instance) keyed by client/user/IP, with per-tenant or per-API-key limits configurable independently.

Q5. Implement a thread-safe singleton in C# — and why is Lazy<T> preferred over manual double-checked locking? Lazy<T> (private static readonly Lazy<T> _instance = new(() => new T());) handles thread-safe, on-demand initialization correctly out of the box, including exception caching behavior you can configure. Hand-rolled double-checked locking is easy to get subtly wrong (memory visibility issues without volatile, or missing the second null check inside the lock) — there’s no good reason to write it by hand in modern C# when Lazy<T> exists.

Q6. How do you parse a multi-million-row CSV in C# without loading it all into memory? Stream it: StreamReader reading line-by-line rather than File.ReadAllLines, IAsyncEnumerable<T> with await foreach so the caller can process rows as they arrive rather than materializing a full list, and Span<T>/ReadOnlySpan<T> for zero-allocation field parsing within each line. For bulk database writes downstream, batch into SqlBulkCopy rather than row-by-row SaveChanges.

Q7. Explain the CAP theorem with a concrete system design implication. Consistency, Availability, Partition tolerance — pick two, since partition tolerance is generally non-negotiable in a real distributed system. Practical split in one platform: the claims/financial database is CP (a decision can’t be based on inconsistent claim data — brief unavailability during a partition is acceptable), while a RAG knowledge base or a live dashboard is AP (serving a decision with a shade of staleness beats being unavailable). Naming which subsystem is CP vs. AP and why is what separates a real answer from reciting the theorem.

Q8. How does Kafka achieve exactly-once semantics, and why does it matter for financial data? Idempotent producer (broker deduplicates by sequence number), transactional producer (atomic writes across partitions), and a consumer configured for read_committed that only sees committed messages — combined, the producer writes atomically, the consumer processes and commits its offset within the same transaction. This matters directly for claims/payment processing, where duplicate processing means incorrect billing, not just a logged warning.

Q9. Explain the thundering herd problem and how you solve it in a caching layer. When a hot cache key expires, many concurrent requests can all try to rebuild it simultaneously, hammering the origin. Solutions: a stampede lock so only one request rebuilds while others wait for the result, stale-while-revalidate (serve the stale value while a background refresh happens), pre-warming the cache before TTL expiry, and jittered TTLs so keys don’t all expire in synchronized lockstep.

Q10. How would you diagnose a query that suddenly went from 50ms to 5 seconds? Check whether the execution plan changed (parameter sniffing is a classic cause of plan regression), check for stale statistics, check for blocking/deadlocks in the active-request DMVs, check whether the underlying table simply grew significantly, and check for a newly-missing index. If it’s parameter sniffing specifically, OPTIMIZE FOR UNKNOWN or a targeted RECOMPILE hint is the fix rather than rewriting the query.