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

πŸ“š .NET Interview Questions

1325 questions for senior .NET engineer interviews, each with a 30-second answer, the full answer, a deep dive, the follow-ups interviewers ask next, and real-world production problems.

Phase 8 — Design Patterns

The GoF creational, structural and behavioural patterns and the enterprise patterns used in modern .NET 10 services, with the judgement to know when a pattern helps and when it is ceremony.

  1. What is CQRS? Explain separating commands and queries into different models, the levels from separate handlers on one database to separate read stores updated by events, how it relates to CQS and to MediatR, how you handle eventual consistency in the UI, and when CQRS is overkill.

    CQRS (Command Query Responsibility Segregation): CQS (Meyer) vs CQRS (Young), separate write model (aggregates, invariants) and read model (projections/DTOs), levels from handlers on one database to a synchronous denormalised table to a separate read store fed by events, eventual consistency and read-your-writes in the UI, relationship to MediatR and event sourcing, and when CQRS is overkill.

    Mid-Level Theory Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  2. What is the transactional outbox pattern? Explain the dual-write problem when an order is saved to SQL Server and an event published to Azure Service Bus, how to write the outbox row in the same EF Core transaction, how a relay publishes and marks messages, why delivery is at-least-once, and what the pattern costs to operate.

    Transactional outbox: the dual-write problem (DB commit and broker publish can't be atomic; distributed transactions aren't an option with Azure SQL and Service Bus), writing an OutboxMessages row in the same EF Core SaveChanges/transaction, a relay BackgroundService polling with UPDLOCK/READPAST, publishing with MessageId = outbox id, marking ProcessedAt, at-least-once delivery and consumer idempotency, ordering, CDC as an alternative, library options (MassTransit v9 commercial, NServiceBus, Wolverine, CAP), and operational costs.

    Senior Theory Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  3. Implement an idempotent consumer (the inbox pattern) for Azure Service Bus messages in .NET 10: a dedup table with a unique key on message id and consumer, recording the message and applying the business change in one EF Core transaction, handling two copies of the same message arriving concurrently, and cleaning up old rows.

    Inbox / idempotent consumer in .NET 10: why at-least-once delivery (outbox resends, peek-lock redelivery, lock expiry) causes duplicates, an InboxMessages table with a composite primary key (MessageId, Consumer), inserting the inbox row first and applying the business change in the same EF Core transaction inside an execution strategy, treating SQL errors 2627/2601 as 'already processed', how the key lock serialises concurrent duplicates, completing vs abandoning Service Bus messages, retention-based cleanup with ExecuteDeleteAsync, natural idempotency as an alternative, and tests.

    Senior Coding Enterprise Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  4. Design a saga for an order-payment flow across orders, stock and payment services. Compare orchestration and choreography, explain compensating actions and why they aren't rollbacks, how a MassTransit state machine (or a hand-rolled orchestrator) persists saga state, and how you handle timeouts, duplicates and late replies.

    Saga pattern for a distributed order-payment flow: why there's no distributed transaction, orchestration (central state machine) vs choreography (services react to events), compensating actions as semantic undo (release stock, refund) rather than rollback, pivot transactions, MassTransit state machine with EF Core saga repository and optimistic concurrency (v9 commercial, v8 Apache 2.0), scheduled timeouts, idempotent steps, late replies after cancellation, observability, and alternatives (NServiceBus, Wolverine, Durable Functions).

    Senior Architecture Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  5. Explain the Retry pattern for transient faults in .NET 10: exponential backoff with jitter, which failures to retry and which never to retry, why retries need idempotency, how retry storms and retry amplification across layers happen, and how Polly v8 and Microsoft.Extensions.Http.Resilience implement it.

    Retry pattern: transient vs permanent faults (5xx, 408, 429 with Retry-After, timeouts vs 400/401/404/409), exponential backoff with jitter (Polly's decorrelated jitter), retrying only idempotent operations (DisableForUnsafeHttpMethods, idempotency keys), retry storms and multiplicative amplification across layers, retry budgets, Polly v8 ResiliencePipeline and RetryStrategyOptions, HttpRetryStrategyOptions defaults in AddStandardResilienceHandler, EF Core EnableRetryOnFailure, and telemetry.

    Mid-Level Theory Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  6. How does the circuit breaker pattern work? Explain the closed, open and half-open states, failure-ratio thresholds, minimum throughput, sampling and break duration, why it sits inside the retry and outside the per-attempt timeout, what AddStandardResilienceHandler configures by default, and how you choose a fallback.

    Circuit breaker pattern: closed/open/half-open state machine, Polly v8 CircuitBreakerStrategyOptions (FailureRatio 0.1, MinimumThroughput 100, SamplingDuration 30 s, BreakDuration 5 s, ShouldHandle, OnOpened/OnHalfOpened), BrokenCircuitException, ordering in AddStandardResilienceHandler (rate limiter, total timeout, retry, breaker, attempt timeout) and its validation rules, per-instance vs per-authority breakers (SelectPipelineByAuthority), low-traffic pitfalls, fallbacks and monitoring.

    Mid-Level Theory Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  7. What is the Bulkhead pattern? Explain how you isolate dependencies in a .NET 10 service with concurrency limiters, separate named HttpClients and pipelines, connection limits, and separate queues or consumers, how a bulkhead differs from rate limiting, and how you size the limits.

    Bulkhead pattern: isolating failures so one slow dependency can't consume shared resources (threads, sockets, DB connections, memory), outbound bulkheads with Polly v8 concurrency limiters (Polly.RateLimiting, RateLimiterRejectedException) and the standard resilience handler's limiter (1,000 permits, queue 0), separate named HttpClients and MaxConnectionsPerServer, inbound bulkheads with ASP.NET Core AddRateLimiter concurrency policies, separate queues/consumers and MaxConcurrentCalls, bulkhead vs rate limiting, sizing with Little's Law, and rejection handling.

    Senior Theory Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  8. A third-party shipping-rates API starts taking 30 seconds instead of 200 ms. Within minutes your checkout API is timing out for every user, including requests that never call that API. How do you diagnose the cascade, and how do you fix it with timeouts, retry, a circuit breaker, a bulkhead and a fallback?

    Real-world cascading failure: diagnosing with Application Insights dependency telemetry, dotnet-counters (thread pool, SqlClient pool, HTTP connections) and dotnet-dump; root causes (HttpClient 100 s default timeout, retries multiplying load, DB connections held across the external call, health checks including the dependency); mitigation with a feature flag; the real fix with attempt and total timeouts, a single jittered retry, a tuned circuit breaker, a concurrency-limit bulkhead, a flat-rate fallback, moving the call out of the transaction, and chaos testing.

    Senior RealWorldScenario Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world
  9. Orders are saved in SQL Server, but finance reports that some OrderPlaced messages on Azure Service Bus never arrive, and others are processed twice, charging customers twice. How do you find the causes, and how do you fix them with the outbox and inbox patterns without losing or duplicating anything during the rollout?

    Real-world messaging incident: finding lost events (publish after SaveChanges, fire-and-forget Task.Run, swallowed ServiceBusException) and duplicates (publisher retries with a new MessageId each time, peek-lock redelivery after lock expiry) with reconciliation queries, Application Insights correlation and Service Bus metrics; fixing with domain events written to an OutboxMessages table by a SaveChanges interceptor, a relay with UPDLOCK/READPAST and stable MessageId, duplicate detection, an InboxMessages table keyed on (MessageId, Consumer); rollout order (inbox first), backfill and refunds, and ongoing reconciliation.

    Senior RealWorldScenario Enterprise Patterns Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  10. You're setting the architecture for a new .NET 10 service. How do you decide which enterprise patterns (repository, unit of work, CQRS, mediator, domain services, outbox, sagas, resilience patterns) to use? Contrast a CRUD-heavy admin service with a complex domain such as insurance claims, explain how you avoid pattern overuse, and how you record and revisit those decisions.

    Staff-level pattern selection: starting from forces (domain complexity, invariants, consistency, integration, scale, team) rather than a template, a minimal baseline every service gets (DbContext, DTOs, validation, HttpClient resilience, observability), a CRUD admin service (vertical slices, DbContext in handlers, no repositories/CQRS/mediator) vs an insurance-claims domain (aggregates, repositories, domain services, light CQRS, outbox/inbox, saga for long-running claims), triggers for adding patterns, cost of each pattern, ADRs with reversal conditions, architecture fitness functions (NetArchTest), and periodic review.

    Staff / Architect Architecture Enterprise Patterns Β· πŸ”— 4 follow-ups Β· πŸ›  1 real-world

🌐 Sangam's Webring

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