.NET 8 --- Exhaustive Technical Interview Flashcards
How to use this deck This deck focuses on the .NET 8 platform and production architecture, while the C# 12 deck focuses on language semantics.
The later sections deliberately move from framework knowledge to senior Architect / Engineering Manager scenarios, troubleshooting, security, scalability, observability, and war stories.
1. .NET 8 Platform Fundamentals
Q: What is .NET? .NET is Microsoft's cross-platform
developer platform containing the runtime, base libraries, SDK, application frameworks, tooling, and supporting infrastructure for building applications.
Q: What is the difference between .NET Framework and
modern .NET? .NET Framework is the original Windows-focused implementation.
Modern .NET is cross-platform, unified, and used for current server, cloud, desktop, and other application workloads.
Modern applications should generally target current supported .NET releases rather than starting new development on .NET Framework.
Q: What is .NET 8? .NET 8 is a Long Term Support
release of modern .NET, providing the runtime, libraries, SDK, ASP.NET Core 8, and related platform capabilities.
Q: What is the CLR in .NET 8? The runtime executes
managed .NET code and provides garbage collection, JIT compilation, exception handling, threading, type safety, and other execution services.
Q: What is the .NET SDK? The SDK contains the
command-line tooling, compilers, templates, MSBuild integration, and development components required to build .NET applications.
Q: SDK vs Runtime? The SDK is used to build applications.
The runtime is sufficient to run applications when the required runtime and application artifacts are already available.
Q: What is a target framework moniker? A TFM identifies
the target platform/version for a project.
For .NET 8 applications, a common target is
net8.0.
2. Application Hosting and Generic Host
Q: What is the Generic Host? The Generic Host provides
common application infrastructure such as dependency injection, configuration, logging, application lifetime, and hosted services.
Q: Why is the Generic Host important in ASP.NET Core?
It gives web applications a consistent application-hosting model and integrates configuration, DI, logging, and lifecycle management.
Q: What is
WebApplicationin ASP.NET Core?WebApplicationis the simplified hosting/application builder model used by modern ASP.NET Core applications.It combines host configuration, service registration, middleware pipeline construction, and application startup.
Q: What is the difference between
WebApplicationBuilderandWebApplication?WebApplicationBuilderis used to configure and build the application.
WebApplicationrepresents the built application and middleware pipeline that is run.
Q: What happens during ASP.NET Core startup? The
application builds configuration, registers services, constructs the dependency injection container, builds the middleware pipeline, starts hosted services, and begins accepting requests.
3. Configuration
Q: How does configuration work in ASP.NET Core? ASP.NET
Core combines configuration from multiple providers into a unified configuration system.
Common providers include JSON files, environment variables, command-line arguments, user secrets, and external configuration providers.
Q: What is configuration precedence? Later providers
can override values from earlier providers.
The exact order depends on the configured providers, but environment-specific and environment-variable values are commonly used to override base configuration in deployed environments.
Q: Why use the Options pattern? The Options pattern
binds configuration into strongly typed classes instead of scattering string-based configuration lookups throughout the application.
Q:
IOptions<T>vsIOptionsSnapshot<T>vsIOptionsMonitor<T>?IOptions<T>provides a stable options value.
IOptionsSnapshot<T>supports scoped snapshots and is useful when options can change between requests.
IOptionsMonitor<T>supports monitoring changes and retrieving current values.
Production Pitfall Do not place secrets directly in
appsettings.jsonand commit them to source control. Use environment-specific secret/configuration mechanisms such as managed secret stores or environment injection.
Q: What is the difference between configuration and
secrets? Configuration controls application behavior and may include non-sensitive settings.
Secrets are sensitive credentials such as passwords, API keys, and connection secrets and require stronger protection and lifecycle management.
4. Dependency Injection
Q: What is built-in dependency injection in ASP.NET
Core? ASP.NET Core provides a built-in DI container that resolves registered services and injects them into constructors, method parameters, or other supported locations.
Q: What are the three common service lifetimes?
Transient → new instance each time requested.
Scoped → one instance per DI scope, commonly one HTTP request.
Singleton → one instance for the application’s DI container lifetime.
Q: When would you use Scoped? Scoped is commonly used
for request-oriented services such as EF Core
DbContextand business services that should share state within a request but not across requests.
Q: When would you use Singleton? Use singleton for
stateless, thread-safe, application-wide services or shared resources whose lifetime genuinely matches the application.
Critical Pitfall A singleton must not directly depend on
a scoped service.
This creates a lifetime mismatch and can cause incorrect state retention or runtime resolution failures.
Q: Why can singleton services be dangerous? Singleton
state is shared across concurrent requests.
If the service contains mutable non-thread-safe state, requests can interfere with one another.
Q: How would you detect a captive dependency? A
longer-lived service indirectly depends on a shorter-lived service.
For example, a singleton depending on a scoped service is a classic captive dependency.
Q: What is constructor injection? Dependencies are
supplied through the constructor and stored by the class.
It makes required dependencies explicit and encourages immutable service design.
Q: What is the service locator anti-pattern in ASP.NET
Core? Calling
IServiceProvider.GetService<T>()throughout application code to dynamically obtain dependencies hides the dependency graph.It is generally preferable to use explicit constructor injection.
5. Middleware
Q: What is ASP.NET Core middleware? Middleware is a
component in the HTTP request pipeline that can inspect, modify, handle, or pass a request to the next component.
Q: How does middleware execute? Middleware generally
follows a pipeline pattern:
Request → Middleware A → Middleware B → Endpoint → Middleware B → Middleware A → Response
Q: Why does middleware order matter? Middleware order
determines which components run before or after others and therefore affects authentication, authorization, exception handling, routing, CORS, static files, compression, and other behaviors.
Common Pitfall Adding middleware without understanding
pipeline order can produce security or functionality bugs that look unrelated to the middleware itself.
Q: Middleware vs MVC filter? Middleware operates at the
HTTP pipeline level and can apply broadly.
MVC filters operate within the MVC/controller execution pipeline and have more framework-specific context.
Q: Middleware vs endpoint filter? Middleware is broader
and sits in the HTTP pipeline.
Endpoint filters are associated with endpoint execution and are useful for cross-cutting concerns around endpoint handlers.
Q: Where should global exception handling happen? A
top-level exception-handling middleware or equivalent centralized mechanism is generally appropriate so unhandled exceptions are translated consistently into HTTP responses and logged.
6. Routing and Endpoints
Q: What is endpoint routing? Endpoint routing matches
an incoming request to an endpoint and stores endpoint metadata in the request context.
Q: What is the difference between conventional and
attribute routing? Conventional routing defines route patterns centrally.
Attribute routing declares route templates on controllers/actions or related endpoint definitions.
Q: What are minimal APIs? Minimal APIs provide a
lightweight approach for defining HTTP endpoints without requiring traditional controller classes.
Q: Minimal APIs vs controllers? Minimal APIs can reduce
ceremony and are useful for focused APIs and services.
Controllers can provide a more structured model for larger applications with filters, conventions, model binding, and controller-specific organization.
The choice should follow team and domain complexity rather than fashion.
7. Model Binding, Validation, and HTTP APIs
Q: What is model binding? Model binding maps HTTP
request data such as route values, query parameters, headers, and request bodies into .NET method parameters or models.
Q: What is model validation? Validation checks whether
incoming data satisfies defined rules before business processing continues.
Q: Why should validation happen before domain
processing? It prevents invalid input from reaching deeper layers and keeps boundary concerns separate from business invariants.
Q: Authentication vs authorization? Authentication determines who the caller is.
Authorization determines what the caller is allowed to do.
Mnemonic AuthN = identity
AuthZ = permissions
Q: What status code should represent validation
failure? Common API designs use
400 Bad Requestfor malformed or invalid client input, though the exact response contract should be consistent with the API’s validation model.
Q:
401vs403?401 Unauthorizedgenerally means authentication is missing or invalid.
403 Forbiddenmeans the caller is authenticated but lacks permission.
8. Serialization
Q: What JSON serializer is commonly used by ASP.NET
Core?
System.Text.Jsonis the default JSON serializer for modern ASP.NET Core applications.
Q: Why might you use custom JSON options? To control
naming policies, null handling, enum serialization, converters, reference behavior, number handling, or compatibility with external contracts.
Contract Pitfall Changing JSON property names or
serialization behavior can be a breaking API change for clients. Treat external JSON as a contract.
Q: Why use DTOs instead of exposing EF Core entities
directly? DTOs prevent persistence models from becoming accidental API contracts and allow API shape, security, and versioning to evolve independently.
9. Logging
Q: What is structured logging? Structured logging
records named properties rather than only formatted text.
Example:
logger.LogInformation("Order {OrderId} created for {CustomerId}", orderId, customerId);
Q: Why is structured logging better for production? Log
backends can index and query structured properties, making correlation, filtering, alerting, and incident investigation easier.
Q: What should you never log? Do not log secrets,
passwords, authentication tokens, sensitive personal information, payment credentials, or other data prohibited by policy.
Production Pitfall Logging "everything" is not
observability. Excessive logs increase cost, noise, storage, and potentially security exposure.
Q: What is correlation ID? A correlation ID is an
identifier used to associate logs and operations belonging to the same logical request or workflow.
10. OpenTelemetry and Observability
Q: What are the three major observability signals?
Logs, metrics, and traces.
Q: What is distributed tracing? Distributed tracing
follows a logical request across multiple services and records spans representing work performed by each component.
Q: What is a trace? A trace represents the end-to-end
journey of an operation through a distributed system.
Q: What is a span? A span represents a timed unit of
work within a trace.
Q: What is OTLP? OTLP is the OpenTelemetry Protocol
used to transport telemetry to an OpenTelemetry Collector or compatible backend.
Q: Why prefer OTLP over vendor-specific application
exporters? OTLP decouples application instrumentation from a specific observability vendor.
The application can send telemetry to a collector, allowing the backend vendor to change without rewriting application instrumentation.
Performance Pitfall Exporting 100% of traces in a
high-throughput production service can increase CPU, network, storage, and observability costs.
Sampling and appropriate collector configuration are important.
Q: What is the difference between metrics and traces?
Metrics summarize behavior numerically over time, such as request rate, error rate, and latency.
Traces explain the path and timing of individual requests across components.
11. HTTP Client and Resilience
Q: Why should you use
IHttpClientFactory? It provides a managed way to create and configureHttpClientinstances and helps avoid common lifetime and connection-management problems associated with repeatedly constructing clients incorrectly.
Q: Why can creating a new HttpClient for every request
be problematic? Improperly creating and disposing clients at high frequency can contribute to connection management issues and socket exhaustion patterns.
Common Pitfall
HttpClientis not simply a lightweight object that should always be instantiated per request.
Q: What is a typed HttpClient? A typed client is a
class representing a specific downstream HTTP API and configured through DI and
IHttpClientFactory.
Q: What is resilience in HTTP communication? Resilience
is the ability to tolerate transient failures while avoiding cascading failures.
Techniques include timeouts, retries with backoff, circuit breakers, bulkheads, rate limits, and fallback where appropriate.
Q: Why are retries dangerous? Retries can multiply
traffic toward an already unhealthy dependency.
They should be bounded, selective, and combined with appropriate backoff.
Production Pitfall Never blindly retry every HTTP error.
Retrying a non-idempotent operation can duplicate business effects.
12. Timeouts and Cancellation
Q: Why are timeouts essential in distributed systems?
Without timeouts, a request can wait indefinitely for a dependency, consuming threads, connections, memory, and other resources.
Q: What is a cancellation token in ASP.NET Core? The
request cancellation token allows application work to observe when the client disconnects or the request is otherwise cancelled.
Q: Should cancellation be propagated to database and
HTTP calls? Generally yes, when the underlying API supports it and when cancellation is safe for the operation.
Production Mnemonic Timeout bounds waiting.
Cancellation stops work when it is no longer needed.
13. EF Core
Q: What is Entity Framework Core? EF Core is a .NET ORM
that maps application objects to database data and translates LINQ expressions into database queries for supported providers.
Q: EF Core vs Dapper? EF Core provides ORM
capabilities, change tracking, LINQ translation, relationships, migrations, and unit-of-work behavior.
Dapper is a lightweight micro-ORM focused on mapping SQL results to objects while leaving SQL control largely to the developer.
Architect Trade-off Choose based on workload and team needs,
not ideology.
EF Core → productivity + rich ORM behavior.
Dapper → explicit SQL + lightweight mapping.
Q: What is
DbContext?DbContextrepresents a session with the database and coordinates querying, change tracking, and persistence.
Q: What lifetime should DbContext usually have in
ASP.NET Core? Scoped is the common default so a context is associated with one request scope.
Critical Pitfall
DbContextis not designed to be used concurrently from multiple threads.
Q: What is change tracking? EF Core tracks entity state
so it can determine which inserts, updates, or deletes should be persisted.
Q: What is
AsNoTracking()? It tells EF Core not to track returned entities, which can reduce overhead for read-only queries.
Q: What is the N+1 query problem? It occurs when an
application executes one query to retrieve parent records and then performs additional queries for each parent.
This can produce a large number of database round trips.
Performance Pitfall Inspect generated SQL and query
counts rather than assuming a concise LINQ expression is efficient.
Q: What is eager loading? Eager loading retrieves
related data as part of the query, commonly using
IncludeandThenInclude.
Q: What is projection? Projection selects only the
fields required by the application into a DTO or anonymous/object shape.
Projection can reduce transferred data and avoid unnecessary entity materialization.
Q: Why is projection often preferable for read APIs? It
can fetch only required columns, reduce memory usage, avoid tracking when appropriate, and prevent exposing persistence entities directly.
14. Transactions
Q: What is a database transaction? A transaction groups
database operations into an atomic unit governed by ACID semantics.
Q: What is the difference between database transaction
and distributed transaction? A database transaction coordinates operations within a transactional resource.
A distributed transaction spans multiple resource managers and is substantially more complex.
Q: Why avoid distributed transactions in microservices
when possible? They increase coupling, operational complexity, failure modes, and coordination costs across services.
Patterns such as transactional outbox and sagas are often preferable.
Q: What is optimistic concurrency? It detects
conflicting updates rather than locking records for the entire business operation.
EF Core can implement concurrency checks using concurrency tokens.
Q: What is pessimistic concurrency? It relies on
locking to prevent conflicting operations while a resource is being used.
15. ASP.NET Core Performance
Q: What are common causes of slow ASP.NET Core APIs?
Common causes include:
- Slow database queries
- External HTTP calls
- Excessive allocations
- Serialization
- Lock contention
- Thread-pool starvation
- Connection-pool exhaustion
- Excessive logging
- Large payloads
- Inefficient middleware
- GC pressure
Q: How would you investigate an API with high latency?
Break latency into components:
Request → Middleware → Controller/Endpoint → DB/HTTP/Cache → SerializationThen use metrics, traces, logs, profiling, database execution plans, and dependency telemetry to identify the dominant component.
Performance Mnemonic Measure first. Optimize the bottleneck, not the code you happen to dislike.
Q: What is response compression? Response compression
reduces payload size over the network, potentially improving bandwidth usage and latency at the cost of CPU.
Q: When can caching improve API performance? Caching
can reduce repeated computation, database queries, and external calls when data can tolerate the required staleness and invalidation model.
Cache Pitfall The hardest part of caching is often
invalidation and consistency, not adding the cache itself.
16. Caching
Q: In-memory cache vs distributed cache? In-memory
cache is local to one application instance.
Distributed cache is shared across instances, enabling consistent cached data across a horizontally scaled service.
Q: Why can local memory caching be dangerous in a
multi-node production system? Different nodes can hold different cached values.
A request routed to node A may see different state from a request routed to node B.
Q: What is cache stampede? A cache stampede occurs when
many requests simultaneously attempt to regenerate an expired or missing cache entry, overwhelming the underlying data source.
Production Pitfall A cache can move the bottleneck
rather than eliminate it. Plan for cache misses, expiry storms, and backend recovery.
Q: What is cache-aside? The application checks the
cache first. On a miss, it loads data from the source, stores it in the cache, and returns the data.
Q: What is cache invalidation? Cache invalidation
removes or marks cached data as no longer valid because the source state changed.
Q: Cache eviction vs invalidation? Invalidation means the data is no longer considered valid.
Eviction means the cache removes an entry, often due to capacity, TTL, or an explicit removal operation.
17. Background Services
Q: What is
IHostedService? It defines lifecycle methods for services that start and stop with the host.
Q: What is
BackgroundService? It is a base class that simplifies implementing long-running hosted background work using an asynchronous execution method.
Q: What should you consider when using
BackgroundService? Consider:
- Cancellation
- Graceful shutdown
- Error handling
- Service lifetime
- Retry behavior
- Idempotency
- Concurrency
- Health monitoring
Production Pitfall An unhandled exception in background
processing can terminate or disrupt the hosted service depending on the hosting behavior and configuration. Treat background workers as production workloads, not fire-and-forget tasks.
18. Messaging and Kafka Integration
Q: When would ASP.NET Core use Kafka instead of direct
HTTP? Kafka is useful when asynchronous event-driven communication, decoupling, replay, multiple independent consumers, or high-throughput streaming is valuable.
Q: What is the difference between an HTTP command and a
Kafka event? An HTTP command generally asks a specific service to perform an action and often expects a response.
An event describes something that happened and can be consumed independently by multiple subscribers.
Q: How would you make a Kafka consumer in .NET
reliable? Use controlled retries, idempotent processing, proper offset strategy, cancellation, observability, bounded concurrency, and a dead-letter strategy where appropriate.
19. Security
Q: What is ASP.NET Core authentication? Authentication
establishes the identity of the caller.
Q: What is authorization? Authorization evaluates
whether the authenticated principal has permission to perform an operation.
Q: What is JWT authentication? A JWT is a signed token
containing claims that can be validated by the API to establish identity and authorization context.
Security Pitfall A JWT being signed does not
automatically mean every claim inside it should be trusted for every business decision. Validate issuer, audience, signature, expiry, and authorization semantics.
Q: What is policy-based authorization? It defines
authorization requirements as policies rather than scattering role checks throughout controller code.
Q: What is CORS? Cross-Origin Resource Sharing controls
whether browser-based clients from one origin can make requests to another origin under defined rules.
Security Pitfall CORS is a browser security mechanism.
It is not an API authentication or authorization mechanism.
Q: How should secrets be handled in production? Store
secrets in an appropriate secret-management system and inject them through secure configuration mechanisms. Do not commit secrets to source control.
20. Rate Limiting and Abuse Protection
Q: Why use rate limiting? Rate limiting protects
services from excessive traffic, accidental overload, abuse, and unfair resource consumption.
Q: What should you consider when designing rate limits?
Consider:
- Per-user limits
- Per-client limits
- Per-IP limits
- Endpoint cost
- Burst behavior
- Distributed deployment
- Retry behavior
- Business priority
Q: Why can per-instance rate limiting be insufficient?
In a multi-node deployment, each instance has its own counters unless state is shared.
A client could therefore exceed the intended global limit by distributing requests across nodes.
21. Health Checks
Q: What is a health check? A health check exposes
application or dependency health information so orchestrators and monitoring systems can determine whether an application is functioning correctly.
Q: Liveness vs readiness? Liveness asks whether the process should be considered alive.
Readiness asks whether it is ready to receive traffic.
Production Pitfall Do not make liveness depend on every
external dependency. A temporary database outage should not necessarily cause an orchestrator to repeatedly kill every application instance.
Q: What should readiness check? Readiness should
reflect whether the instance can safely serve traffic, considering critical startup dependencies and application state.
22. Distributed Systems and Microservices
Q: What is the biggest challenge in microservices?
Distributed systems introduce network failure, latency, partial failure, independent deployment, data consistency challenges, observability complexity, and operational overhead.
Q: Why is a microservice not simply a smaller class
library? A microservice has operational and distributed-system boundaries: deployment, networking, data ownership, observability, security, scaling, and failure handling.
Q: When should you not create a microservice? Avoid a
separate service when the domain boundary is unclear, independent deployment is unnecessary, operational overhead outweighs benefits, or the service would create excessive synchronous coupling.
Architect Mnemonic Service boundary = business boundary + operational boundary + data boundary.
23. Service-to-Service Communication
Q: Synchronous HTTP vs asynchronous messaging?
Synchronous HTTP provides immediate request/response semantics but creates temporal coupling.
Messaging reduces temporal coupling and supports buffering/replay but introduces eventual consistency and operational complexity.
Q: What is temporal coupling? Temporal coupling occurs
when two services must be available at the same time for an operation to succeed.
Q: What is eventual consistency? Different parts of a
distributed system may temporarily have different views of state but converge over time.
Q: How do you handle partial failure between services?
Use timeouts, retries with backoff, circuit breakers, idempotency, fallback where meaningful, asynchronous messaging where appropriate, and clear failure contracts.
24. Distributed Transactions and Sagas
Q: What is the Saga pattern? A saga breaks a
distributed business transaction into a sequence of local transactions with compensating actions when later steps fail.
Q: Orchestration vs choreography in a saga?
Orchestration uses a coordinator that directs participants.
Choreography uses events and decentralized reactions among services.
Architect Trade-off Choreography can reduce central
coordination but can become difficult to understand as event dependencies grow. Orchestration improves visibility but introduces a coordinator.
Q: When would you choose an outbox plus Kafka? When a
service must reliably persist local business state and publish an event without relying on a distributed transaction.
Q: What is idempotency in a distributed API? It means
repeated delivery of the same logical operation does not produce unintended additional business effects.
25. API Design
Q: What makes a good REST API? Clear resource modeling,
consistent HTTP semantics, validation, meaningful status codes, predictable error contracts, idempotency where appropriate, versioning strategy, security, and observability.
Q: PUT vs PATCH? PUT commonly represents replacement of
a resource representation.
PATCH represents partial modification.
Q: What is idempotency of an HTTP operation? An
operation is idempotent when repeating it has the same intended effect as performing it once, even though responses may differ.
Q: How would you implement idempotency for a payment
API? Accept an idempotency key, persist the key and outcome atomically with the business operation, and return the existing result when the same logical request is retried.
Production Pitfall An idempotency key is useful only if
its storage and business operation are coordinated correctly. A simple in-memory dictionary is not sufficient for a multi-node production API.
26. API Versioning and Compatibility
Q: Why does API versioning matter? Clients and servers
often deploy independently. Versioning provides a controlled compatibility strategy when contracts must evolve.
Q: What makes an API change breaking? Removing or
renaming fields, changing semantics, changing required inputs, altering authentication behavior, or changing response expectations can break clients.
Q: Should every API have a new version for every
change? No.
Backward-compatible additive changes may not require a new version depending on the organization’s compatibility policy.
27. Resilience Architecture
Q: What is a circuit breaker? A circuit breaker stops
repeatedly calling a failing dependency after a threshold is reached, allowing the dependency and caller to recover.
Q: What are circuit breaker states? Common states are:
- Closed
- Open
- Half-open
Q: What is a bulkhead? A bulkhead isolates resource
pools so failure or saturation in one dependency or workload does not consume all application resources.
Mnemonic Timeout → stop waiting
Retry → try again carefully
Circuit breaker → stop calling
Bulkhead → isolate capacity
Q: Why can retries and circuit breakers conflict?
Poorly configured retries can delay failure detection and increase traffic, while circuit breakers need meaningful failure signals.
Resilience policies should be composed deliberately rather than stacked blindly.
28. Dependency and Connection Pools
Q: What is connection-pool exhaustion? It occurs when
an application has more concurrent requests requiring connections than the configured or available pool can provide.
Q: What symptoms suggest connection-pool exhaustion?
Increasing latency, timeout errors, blocked requests, low application CPU, and traces showing long waits for database or HTTP connections can be clues.
Q: How would you troubleshoot it? Measure active/idle
connections, request concurrency, dependency latency, pool limits, connection leaks, long-running transactions, and traffic changes.
29. Containers and Deployment
Q: Why containerize a .NET 8 application? Containers
package the application and its runtime dependencies into a repeatable deployment unit and provide consistency across environments.
Q: What should a production Docker image optimize for?
Small attack surface, reproducibility, startup behavior, security, caching efficiency, and appropriate runtime-only contents.
Q: Why use multi-stage Docker builds? One stage can
compile/publish the application while a smaller runtime stage contains only what is needed to run it.
Security Pitfall Do not assume a small image is
automatically secure. Base-image vulnerabilities, permissions, secrets, and runtime configuration still matter.
Q: Why should containers generally run as non-root
where practical? It reduces the impact of a container compromise by limiting privileges.
30. Cloud and AWS Mapping
Q: How would you deploy an ASP.NET Core .NET 8 API on
AWS? Common options include:
- ECS/Fargate
- ECS on EC2
- EKS
- Elastic Beanstalk
- Lambda for suitable workloads
- EC2 directly
The choice depends on workload shape, operational requirements, scaling model, cold-start tolerance, networking, and team expertise.
Q: When would you choose Lambda for .NET? Lambda is
attractive for event-driven or bursty workloads where managed scaling and serverless operations outweigh cold-start and execution-model constraints.
Q: When would you choose ECS/Fargate? Fargate is useful
for long-running containerized workloads when you want container control without managing EC2 instances.
Q: When would you choose ECS on EC2? When you need more
control over the underlying compute, specialized instance characteristics, or potentially better economics at predictable high utilization.
31. Performance Troubleshooting
Q: A .NET API's P99 latency increased but average
latency is unchanged. What does that suggest? Tail latency is degrading for a subset of requests.
Investigate slow dependencies, lock contention, GC pauses, connection-pool waits, retries, noisy neighbors, large payloads, and specific request classes.
Q: CPU is 90% and throughput is falling. What would you
investigate? Profile CPU usage and determine whether the cost is application code, serialization, encryption, logging, GC, regex, JSON processing, or another hot path.
Q: CPU is low but requests are queued. What would you
investigate? Look for blocking I/O, thread-pool starvation, connection-pool exhaustion, lock contention, dependency latency, and synchronization bottlenecks.
Troubleshooting Mnemonic High CPU → compute problem
Low CPU + high latency → waiting problem until proven otherwise
Q: Memory keeps growing in a long-running .NET service.
What do you investigate? Determine whether the process is:
- Allocating faster than GC can reclaim
- Retaining objects unexpectedly
- Growing a cache
- Accumulating static references
- Leaking event subscriptions
- Holding large buffers
- Experiencing native/unmanaged memory growth
32. Production Scenarios
Q: Your .NET API suddenly returns 503 responses after a
deployment. Walk me through your investigation. First determine whether 503s originate from the application, reverse proxy, load balancer, container orchestrator, or dependency.
Check deployment health, readiness probes, application startup logs, dependency availability, resource limits, configuration changes, routing, and recent version differences.
Q: All pods are healthy but users report slow APIs.
What do you investigate? Health does not mean performance is healthy.
Check latency percentiles, dependency latency, database connections, CPU throttling, memory pressure, thread-pool starvation, locks, network latency, and load-balancer behavior.
Q: Database CPU is at 100% after a .NET deployment.
What would you do? Compare query volume and query shape before and after deployment.
Investigate N+1 queries, missing indexes, changed LINQ translation, accidental materialization, increased request concurrency, and query-plan regressions.
Q: A deployment doubled database calls without
increasing user traffic. What might have happened? Potential causes include:
- N+1 query regression
- Duplicate service invocation
- Missing caching
- Retry amplification
- Changed ORM query behavior
- New background worker
- Duplicate event consumption
Q: A downstream payment service is failing. How should
your .NET service behave? Apply bounded timeouts, appropriate retry only for transient/idempotent operations, circuit breaking, clear error handling, observability, and potentially asynchronous processing.
The goal is to prevent the payment outage from becoming an outage of every upstream service.
Senior-Level Principle A resilient service should degrade deliberately, not fail unpredictably.
33. Production War Stories
Q: Tell me about a .NET production performance
incident. Explain:
Symptom → business impact → metrics → investigation → root cause → mitigation → permanent fix → prevention.
Include concrete latency, throughput, CPU, memory, or error-rate numbers when possible.
Q: Tell me about a database bottleneck you solved in
.NET. Explain how you proved the database was the bottleneck rather than simply assuming it from the API latency.
Q: Tell me about a memory leak or memory-retention
issue. Explain the evidence, dump/profile analysis, retained object graph, root cause, fix, and monitoring added afterward.
Q: Tell me about a production incident caused by a bad
retry policy. Explain how retries amplified the failure, what dependency became saturated, how the retry policy was changed, and what safeguards were added.
Q: Tell me about a deployment that caused a regression.
Explain:
- What changed
- Why tests did not catch it
- How production telemetry exposed it
- How you mitigated it
- Whether rollback or forward-fix was chosen
- What was changed in the delivery pipeline afterward
Q: Tell me about a time you chose simplicity over a
more sophisticated architecture. Explain the requirements, alternatives, operational costs, and why the simpler design was the better engineering decision.
34. Architecture Scenarios --- 15-Year Level
Q: Design a .NET 8 e-commerce backend that must scale
horizontally. Discuss:
- Stateless API instances
- Load balancing
- Externalized state
- Database strategy
- Caching
- Messaging
- Idempotency
- Observability
- Authentication/authorization
- Rate limiting
- Resilience
- Deployment strategy
Explain where state lives and why.
Q: Your service runs on 20 nodes. Where should shared
state live? Shared state that must be consistent across nodes should generally live in an appropriate shared system such as a database, distributed cache, or messaging system.
Request-local state can remain in memory within the request.
Architect Mental Model Local state → process/request
Shared durable state → database
Shared ephemeral state → distributed cache
Event history → event/messaging platform
Q: When would you use Redis instead of PostgreSQL for
shared state? Redis is appropriate for low-latency ephemeral or cache-oriented state where its consistency and durability characteristics fit the requirement.
PostgreSQL is generally the source of truth for durable relational business state.
Q: Design an order workflow where payment, inventory,
and shipping are separate services. I would model the workflow as a distributed business process.
Options include orchestration or choreography using events, with local transactions, idempotent consumers, an outbox, retries, compensating actions, and clear workflow state.
Q: The business says checkout must be atomic across
five microservices. How would you respond? I would challenge the requirement for a distributed ACID transaction.
I would ask which invariants truly require atomicity and whether the workflow can be modeled using local transactions plus a saga and compensating actions.
Q: Design a .NET service for 100,000 requests per
second. Start with workload characteristics rather than immediately selecting infrastructure.
Establish request cost, payload size, read/write ratio, latency target, dependency behavior, consistency requirements, cacheability, failure model, and scaling characteristics.
Then design stateless horizontal scaling, database partitioning/scaling, caching, asynchronous work, connection pools, rate limiting, and observability.
Q: How would you prove the system can handle 100,000
requests/sec? Use load testing and capacity testing with production-like payloads and dependencies.
Measure throughput, P50/P95/P99 latency, error rate, CPU, memory, GC, network, database utilization, connection pools, queue depth, and saturation points.
35. Architecture Trade-offs
Q: Monolith vs microservices? A monolith is usually
simpler to develop, test, deploy, and operate initially.
Microservices can provide independent deployment and scaling and clearer bounded contexts, but add distributed-system complexity.
Architect Pitfall Do not treat microservices as the
default definition of a mature architecture.
Q: EF Core vs Dapper? EF Core is strong when domain
mapping, change tracking, LINQ, migrations, and productivity matter.
Dapper is attractive when SQL control, simplicity, and predictable query mapping matter.
A system can legitimately use both where different workloads justify them.
Q: REST vs gRPC? REST/JSON is broadly interoperable and
browser/client friendly.
gRPC provides strongly typed contracts and efficient binary communication and can be attractive for internal service-to-service communication.
Q: Synchronous vs asynchronous architecture?
Synchronous communication is simpler for immediate request/response flows.
Asynchronous communication reduces temporal coupling and supports buffering and independent processing but introduces eventual consistency and more operational complexity.
Q: In-memory cache vs distributed cache? In-memory is
fastest and simplest but node-local.
Distributed cache provides shared state across nodes at the cost of network hops and operational dependency.
36. Testing
Q: Unit vs integration vs end-to-end tests? Unit tests
isolate a small unit.
Integration tests verify interaction with real or realistic infrastructure/components.
End-to-end tests verify complete user/business flows across multiple components.
Q: Should every dependency be mocked in unit tests? No.
Over-mocking can produce tests that verify implementation details rather than behavior. Use real components where integration behavior matters.
Q: What is the testing pyramid? A common model favors
many fast unit tests, fewer integration tests, and fewer expensive end-to-end tests.
Testing Tip The objective is not the maximum test count. It
is high confidence at reasonable feedback cost.
37. Deployment and CI/CD
Q: What should a .NET CI pipeline validate? Typical
stages include:
- Restore
- Build
- Unit tests
- Static analysis
- Security scanning
- Package/build artifact
- Integration tests where appropriate
- Container build
- Deployment
- Post-deployment verification
Q: What is blue-green deployment? Two environments
exist: one serving traffic and another prepared with the new version.
Traffic can be switched between them, simplifying rollback at the cost of additional infrastructure.
Q: What is canary deployment? A small percentage of
traffic is sent to the new version first. Metrics are observed before increasing traffic.
Deployment Mnemonic Deploy safely → Observe → Increase traffic → Verify → Roll back if necessary
38. Graceful Shutdown
Q: What is graceful shutdown? Graceful shutdown allows
an application to stop accepting new work while completing or safely abandoning in-flight work.
Q: Why is graceful shutdown important for containerized
.NET services? Orchestrators regularly terminate and replace instances during deployments and scaling.
Without graceful shutdown, requests or background jobs can be interrupted unexpectedly.
Q: What should happen to a background worker during
shutdown? It should observe cancellation, stop taking new work, and finish or safely checkpoint current work within the allowed shutdown window.
39. .NET Security Scenarios
Q: How would you secure a public .NET API? Use TLS,
strong authentication, authorization policies, input validation, rate limiting, secure secret management, safe serialization, dependency patching, security headers where relevant, logging/auditing, and continuous vulnerability scanning.
Q: What would you do if an API key was accidentally
committed to Git? Treat it as compromised.
Revoke/rotate the credential immediately, investigate usage, remove it from future history where policy requires, and fix the secret-management process that allowed it.
Q: How would you protect an API from abuse? Combine
authentication, authorization, rate limiting, request-size limits, timeouts, validation, WAF/API gateway controls where appropriate, and monitoring.
40. Senior Interview Follow-up Traps
Q: You said scoped means one instance per request. Is
that universally true? No.
Scoped means one instance per DI scope. In ASP.NET Core a request commonly creates a scope, but scopes can also be created explicitly outside HTTP requests.
Q: You said singleton is one instance. One instance per
what? One instance per DI container/service-provider lifetime.
Multiple processes, containers, or separately constructed service providers can each have their own singleton instance.
Q: You said ASP.NET Core is asynchronous. Does that
mean every operation uses another thread? No.
Asynchronous I/O can complete without dedicating a worker thread for the entire wait.
Q: You said Redis is a distributed cache. Should it
become your database? Not automatically.
Redis can support durable or persistent workloads in some designs, but whether it should be the source of truth depends on the consistency, durability, query, and recovery requirements.
Q: You said adding instances improves scalability. What
if PostgreSQL is already saturated? More API instances can increase pressure on the database and make the bottleneck worse.
Horizontal scaling only helps when the downstream architecture can absorb the additional concurrency.
Architect Trap Scaling one tier without checking the bottleneck tier can amplify failure.
Q: You said caching improves performance. What happens
when the cache goes down? The architecture should define whether the cache is optional or required.
For a cache-aside design, the source of truth should remain available so the application can potentially rebuild the cache, subject to acceptable load.
Q: You said retries improve reliability. What happens
when all clients retry at once? The system can experience a retry storm.
Use bounded retries, exponential backoff, jitter where appropriate, and circuit breaking.
Q: You said health checks are green. Why can the API
still be down from the user’s perspective? Health checks may not exercise the actual user path, or they may omit a degraded dependency.
Health is multidimensional: process health, readiness, dependency health, and user-facing performance are different signals.
Q: You said the API is stateless. Where does the user's
session live? In a stateless architecture, session state should be externalized or represented in a client token when appropriate.
Common shared state systems include a database or distributed cache.
41. Final .NET 8 Architect Mental Model
┌───────────────────────┐
│ Client │
└───────────┬───────────┘
│
▼
┌───────────────────────┐
│ Load Balancer / WAF │
└───────────┬───────────┘
│
▼
┌──────────────────────────────────┐
│ ASP.NET Core │
│ │
│ Middleware │
│ ↓ │
│ Routing / Endpoint │
│ ↓ │
│ Validation / Authorization │
│ ↓ │
│ Application / Domain Logic │
└───────────────┬──────────────────┘
│
┌────────────────┼────────────────┐
▼ ▼ ▼
PostgreSQL Redis Kafka
source of ephemeral / events
truth cache
│ │ │
└────────────────┼────────────────┘
▼
External Services
Observability across everything:
Logs + Metrics + Traces + Health Checks
Reliability:
Timeout + Retry + Circuit Breaker + Bulkhead
Idempotency + Outbox + Saga
Security:
TLS + Authentication + Authorization
Secrets + Validation + Rate LimitingFinal .NET 8 Interview Mental Model For almost every senior
.NET architecture question, reason in this order:
1. What is the business requirement?
2. Where is the state?
3. Is the operation synchronous or asynchronous?
4. What happens when a dependency is slow?
5. What happens when it fails?
6. Can the operation be retried safely?
7. How does it scale horizontally?
8. What is the consistency model?
9. How do we observe it in production?
10. What trade-off are we consciously accepting?