Chapter 4 — .NET / ASP.NET Core Architecture (60 Questions)
Topics:
Application Architecture
- Explain ASP.NET Core request pipeline
- MVC architecture
- Web API architecture
- REST principles
- Clean Architecture
- Onion Architecture
- Hexagonal Architecture
- Dependency inversion principle
- SOLID principles
- Repository pattern
Enterprise Patterns
- Unit of Work
- CQRS
- Mediator pattern
- Domain-driven design
- DTO pattern
- Mapping strategies
- Validation architecture
- Exception handling architecture
- Logging architecture
- Configuration management
Distributed Systems
- Microservices
- API Gateway
- Service discovery
- Message queues
- RabbitMQ
- Event-driven architecture
- Saga pattern
- Distributed transactions
- Caching strategies
- Idempotency
Cloud Architecture
31–60:
1. Explain the ASP.NET Core request pipeline.
Interview Answer
The ASP.NET Core request pipeline is a sequence of middleware components that process HTTP requests and responses.
Each middleware can:
- process the request
- modify the request/response
- call the next middleware
- stop the pipeline
Pipeline Example
HTTP Request
|
v
Exception Handling Middleware
|
v
HTTPS Redirection
|
v
Static Files
|
v
Routing
|
v
Authentication
|
v
Authorization
|
v
Controller / Endpoint
|
v
HTTP Response
Example
Program.cs
var app = builder.Build();
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Important Interview Point
Middleware order matters.
Example:
Wrong:
app.UseAuthorization();
app.UseAuthentication();
Authorization runs before authentication, so the user identity is not available.
Correct:
app.UseAuthentication();
app.UseAuthorization();
Senior Answer
ASP.NET Core uses a middleware-based pipeline. Each component handles part of the request lifecycle, and the order determines application behavior.
2. Explain MVC architecture in ASP.NET Core.
Interview Answer
MVC stands for:
- Model
- View
- Controller
It separates application responsibilities.
Model
Represents:
- business data
- domain objects
- validation rules
Example:
public class Customer
{
public int Id {get;set;}
public string Name {get;set;}
}
View
Responsible for UI presentation.
Example:
<h1>
@Model.Name
</h1>
Controller
Handles requests and coordinates work.
Example:
public class CustomerController
: Controller
{
public IActionResult Index()
{
return View();
}
}
MVC Flow
Browser
|
v
Controller
|
v
Business Service
|
v
Database
|
v
View
|
v
Browser
Senior Answer
MVC separates presentation, business logic, and data handling, making applications easier to maintain and test.
3. What is the difference between MVC and Web API?
Interview Answer
MVC is mainly designed for server-rendered applications.
Web API is designed for building HTTP services.
MVC Example
Request:
GET /Customers
Response:
CustomerList.cshtml
The server generates HTML.
Web API Example
Request:
GET /api/customers
Response:
[
{
"id":1,
"name":"John"
}
]
Comparison
MVC | Web API |
Returns HTML | Returns data |
Server-side rendering | Client-side applications |
Views | JSON/XML |
Razor pages | Angular/React/mobile apps |
Senior Answer
In modern enterprise applications, I usually use Web API as the backend and Angular/React/Blazor as the frontend.
4. What are REST principles?
Interview Answer
REST (Representational State Transfer) is an architectural style for designing web APIs.
The main principles are:
1. Stateless Communication
Each request contains all required information.
Example:
GET /api/orders/100
Authorization: Bearer token
The server does not remember previous requests.
2. Resource-Based URLs
Good:
GET /api/customers/10
Bad:
GET /api/GetCustomer?id=10
3. HTTP Methods
Method | Purpose |
GET | Retrieve data |
POST | Create |
PUT | Replace |
PATCH | Partial update |
DELETE | Remove |
4. Standard Status Codes
Example:
Success:
200 OK
Created:
201 Created
Bad request:
400 Bad Request
Unauthorized:
401 Unauthorized
Server error:
500 Internal Server Error
Senior Answer
A REST API uses standard HTTP semantics, stateless communication, resource-oriented URLs, and predictable responses.
5. What is Clean Architecture?
Interview Answer
Clean Architecture separates business logic from external concerns.
The main idea:
Business rules should not depend on frameworks, databases, or UI.
Typical Layers
+----------------------+
| Presentation |
| API Controllers |
+----------------------+
|
+----------------------+
| Application |
| Use Cases |
+----------------------+
|
+----------------------+
| Domain |
| Business Rules |
+----------------------+
|
+----------------------+
| Infrastructure |
| Database, APIs |
+----------------------+
Dependency Direction
Dependencies point inward:
Infrastructure
↓
Application
↓
Domain
The domain does not know about SQL Server or HTTP.
Example
Domain:
public interface ICustomerRepository
{
Customer Get(int id);
}
Infrastructure:
public class SqlCustomerRepository
: ICustomerRepository
{
}
Benefits
- easier testing
- replace database
- independent business logic
- better maintainability
Senior Answer
Clean Architecture protects business rules by isolating them from frameworks and external systems.
6. What is Onion Architecture?
Interview Answer
Onion Architecture is similar to Clean Architecture and organizes the system around the domain model.
The domain is the center.
Structure
UI/API
|
Application Services
|
Domain Services
|
Domain Models
Core Principle
Dependencies always point inward.
Example:
The domain should not reference:
- Entity Framework
- ASP.NET Core
- external APIs
Difference from traditional architecture
Traditional:
UI
|
Business Logic
|
Database
Problem:
Business logic depends on database.
Onion:
Domain
^
|
Application
^
|
Infrastructure
Senior Answer
Onion Architecture emphasizes dependency inversion by keeping the domain model independent from technical details.
7. What is Hexagonal Architecture?
Interview Answer
Hexagonal Architecture is also called:
Ports and Adapters Architecture
The idea is that the application core communicates with the outside world through interfaces.
Structure
REST API
|
|
Adapter
|
Application Core
|
Adapter
|
Database
Ports
Interfaces defining communication.
Example:
public interface IPaymentGateway
{
bool Pay(decimal amount);
}
Adapters
Implementations.
Example:
public class StripePaymentGateway
: IPaymentGateway
{
}
Benefits
- replace external systems easily
- better testing
- flexible architecture
Example
Today:
Application
|
Stripe API
Tomorrow:
Application
|
PayPal API
Only adapter changes.
8. Explain SOLID principles.
Interview Answer
SOLID is a set of five object-oriented design principles.
S — Single Responsibility Principle
A class should have one reason to change.
Bad:
class Report
{
Generate();
SaveToDatabase();
SendEmail();
}
Better:
ReportGenerator
ReportRepository
EmailService
O — Open/Closed Principle
Software should be open for extension but closed for modification.
Example:
Instead of changing:
CalculatePrice()
create:
IPricingStrategy
L — Liskov Substitution Principle
Derived classes must work wherever base classes are used.
Example:
If:
Bird
has:
Fly()
then:
Penguin
should not inherit from it.
I — Interface Segregation Principle
Prefer small interfaces.
Bad:
interface IWorker
{
Work();
Eat();
}
Better:
IWorkable
IEatable
D — Dependency Inversion Principle
High-level modules should depend on abstractions.
Bad:
OrderService
|
SqlRepository
Better:
OrderService
|
IRepository
Senior Answer
SOLID principles help create flexible, maintainable, and testable software by reducing coupling.
9. What is the Dependency Inversion Principle?
Interview Answer
Dependency Inversion means high-level business logic should not depend directly on low-level implementations.
Bad design:
public class OrderService
{
private SqlOrderRepository repo;
public OrderService()
{
repo = new SqlOrderRepository();
}
}
Problem:
Changing database requires changing business code.
Better:
public class OrderService
{
private readonly IOrderRepository repo;
public OrderService(
IOrderRepository repo)
{
this.repo = repo;
}
}
Implementation:
public class SqlOrderRepository
: IOrderRepository
{
}
Benefits
- easier testing
- lower coupling
- easier replacement
10. What is the Repository Pattern?
Interview Answer
Repository Pattern abstracts data access logic from business logic.
Instead of:
context.Customers
.Where(x=>x.Active)
everywhere, create:
customerRepository.GetActiveCustomers();
Example:
Interface:
public interface ICustomerRepository
{
Task<Customer> GetByIdAsync(int id);
Task AddAsync(Customer customer);
}
Implementation:
public class CustomerRepository
: ICustomerRepository
{
private readonly AppDbContext context;
public async Task<Customer> GetByIdAsync(int id)
{
return await context.Customers
.FindAsync(id);
}
}
Benefits
- separates concerns
- easier testing
- hides database details
Debate: Is Repository Pattern always needed?
Modern EF Core already provides:
DbSet<T>
which behaves like a repository.
Many teams use:
- EF Core directly
- repositories only for complex domains
Senior Answer
I use repositories when they add business value or isolate complex persistence logic. I avoid unnecessary abstraction layers that only wrap EF Core methods.
11. What is the Unit of Work pattern?
Interview Answer
The Unit of Work pattern manages a group of database operations as a single transaction.
The idea:
All changes should either succeed together or fail together.
Without Unit of Work
Example:
customerRepository.Add(customer);
orderRepository.Add(order);
paymentRepository.Save(payment);
Problem:
What happens if payment fails?
You may have:
Customer saved ✅
Order saved ✅
Payment failed ❌
The database is inconsistent.
With Unit of Work
Start Transaction
|
|
Save Customer
|
|
Save Order
|
|
Save Payment
|
|
Commit
If something fails:
Rollback everything
Example
Interface:
public interface IUnitOfWork
{
ICustomerRepository Customers { get; }
IOrderRepository Orders { get; }
Task CommitAsync();
}
Implementation:
public class UnitOfWork : IUnitOfWork
{
private readonly AppDbContext context;
public async Task CommitAsync()
{
await context.SaveChangesAsync();
}
}
Entity Framework Core
EF Core already provides Unit of Work behavior:
await dbContext.SaveChangesAsync();
All tracked changes are committed together.
Senior Answer
EF Core DbContext already implements many Unit of Work responsibilities. I introduce an explicit Unit of Work only when coordinating multiple repositories or complex transactions.
12. What is CQRS?
Interview Answer
CQRS stands for:
Command Query Responsibility Segregation
It separates operations that modify data from operations that read data.
Traditional approach:
Customer Service
|
|
Database
Read + Write
CQRS:
Application
|
-----------------
| |
Commands Queries
Write Read
| |
Write Database Read Database
Command Example
Changing data:
CreateOrderCommand
UpdateCustomerCommand
CancelOrderCommand
Example:
public class CreateOrderCommand
{
public int CustomerId {get;set;}
}
Query Example
Reading data:
GetCustomerQuery
GetOrdersQuery
Why use CQRS?
Benefits:
- separates responsibilities
- easier scaling
- optimized read models
- cleaner business logic
When NOT to use CQRS?
For simple CRUD applications:
Controller
|
Entity Framework
|
Database
is often enough.
Senior Answer
CQRS is useful for complex domains where read and write workloads have different requirements. I avoid introducing it unnecessarily because it increases complexity.
13. What is the Mediator pattern?
Interview Answer
The Mediator pattern reduces direct communication between objects by introducing a central component.
Instead of:
Controller
|
Service A
|
Service B
|
Service C
Use:
Controller
|
Mediator
|
Handlers
Example using MediatR
Command:
public record CreateUserCommand(
string Name);
Handler:
public class CreateUserHandler
: IRequestHandler<CreateUserCommand>
{
public async Task Handle(
CreateUserCommand request,
CancellationToken token)
{
// business logic
}
}
Controller:
await mediator.Send(command);
Benefits
- loose coupling
- cleaner controllers
- separation of responsibilities
- works well with CQRS
Common Usage
ASP.NET Core applications often use:
- MediatR
- CQRS
- Pipeline behaviors
Senior Answer
Mediator is useful when many components communicate with each other and direct dependencies become difficult to manage.
14. What is Domain-Driven Design (DDD)?
Interview Answer
Domain-Driven Design focuses software design around the business domain and business rules.
The main idea:
The code should reflect the business language.
Important DDD Concepts
Entity
An object with identity.
Example:
public class Customer
{
public CustomerId Id {get;}
public string Name {get;}
}
Two customers can have the same name but different identities.
Value Object
An object defined by its values.
Example:
public record Address(
string City,
string Country);
Two addresses with the same values are equal.
Aggregate
A group of objects managed as one consistency boundary.
Example:
Order Aggregate
Order
|
+-- OrderItem
|
+-- Payment
Domain Service
Business logic that does not naturally belong to one entity.
Example:
CurrencyExchangeService
Senior Answer
DDD is useful for complex business systems where understanding and modeling business rules are more important than simple data CRUD operations.
15. What is the DTO pattern?
Interview Answer
DTO stands for:
Data Transfer Object
A DTO is an object used to transfer data between layers or systems.
Entity:
public class Customer
{
public int Id {get;set;}
public string PasswordHash {get;set;}
public string Email {get;set;}
}
Do not expose entity directly:
{
"id":1,
"passwordHash":"xyz"
}
Create DTO:
public class CustomerDto
{
public int Id {get;set;}
public string Email {get;set;}
}
Response:
{
"id":1,
"email":"john@test.com"
}
Benefits
- security
- API stability
- separation of concerns
- smaller payloads
Senior Answer
DTOs prevent exposing internal domain models and allow APIs to evolve independently.
16. What is AutoMapper and when should you use it?
Interview Answer
AutoMapper is a library that maps objects from one type to another.
Example:
Entity:
public class Customer
{
public int Id {get;set;}
public string Name {get;set;}
}
DTO:
public class CustomerDto
{
public int Id {get;set;}
public string Name {get;set;}
}
Mapping:
CreateMap<Customer, CustomerDto>();
Usage:
var dto =
mapper.Map<CustomerDto>(customer);
Advantages
- reduces repetitive mapping code
- consistent transformations
- useful for large DTO models
Disadvantages
Problems:
- hidden mapping logic
- harder debugging
- performance overhead
Alternative
Manual mapping:
var dto = new CustomerDto
{
Id = customer.Id,
Name = customer.Name
};
Senior Answer
I use AutoMapper for simple object transformations but prefer explicit mapping for critical business logic where clarity is more important.
17. How do you design validation architecture?
Interview Answer
Validation should happen at multiple levels.
1. API Validation
Checks incoming requests.
Example:
public class CreateUserRequest
{
[Required]
public string Email {get;set;}
}
2. Application Validation
Checks business rules.
Example:
if(customer.IsBlocked)
{
return Result.Fail(
"Customer is blocked");
}
3. Database Validation
Protects data integrity.
Examples:
- foreign keys
- constraints
- unique indexes
Typical Flow
HTTP Request
|
API Validation
|
Business Validation
|
Database
FluentValidation Example
public class UserValidator
: AbstractValidator<User>
{
public UserValidator()
{
RuleFor(x=>x.Email)
.NotEmpty();
}
}
Senior Answer
I separate technical validation from business validation. Validation rules should live close to the layer that owns the responsibility.
18. How do you design exception handling architecture?
Interview Answer
Exceptions should be handled centrally instead of everywhere.
Architecture:
Controller
|
Service
|
Repository
|
Exception Middleware
|
Standard Error Response
Example:
app.UseExceptionHandler();
Create standard response:
{
"code":"CUSTOMER_NOT_FOUND",
"message":"Customer does not exist"
}
Good Practices
Log:
- exception details
- stack trace
- correlation ID
Return:
- safe messages
- no sensitive information
Avoid
Bad:
catch(Exception ex)
{
return ex.Message;
}
This exposes internal information.
Senior Answer
I centralize exception handling using middleware, structured logging, and consistent error contracts.
19. How do you design logging architecture?
Interview Answer
A production logging system should provide:
- structured logs
- correlation IDs
- log levels
- centralized storage
Example:
logger.LogInformation(
"Order {OrderId} created",
orderId);
Creates structured data:
Event:
OrderCreated
OrderId:
12345
Log Levels
Trace
Debug
Information
Warning
Error
Critical
Production Architecture
Application
|
ILogger
|
Serilog / Provider
|
CloudWatch / Application Insights / ELK
Senior Answer
Logs should help diagnose production issues, so I prefer structured logging over plain text messages.
20. How do you manage configuration in enterprise applications?
Interview Answer
Configuration should be externalized and environment-specific.
Example:
Development:
appsettings.Development.json
Production:
appsettings.Production.json
Sensitive values should not be stored in source code.
Examples:
Avoid:
{
"Password":"secret123"
}
Use:
- Azure Key Vault
- AWS Secrets Manager
- environment variables
Configuration Hierarchy
appsettings.json
↓
Environment File
↓
Environment Variables
↓
Secret Store
Later values override earlier ones.
Options Pattern
Instead of:
configuration["Database:Connection"]
Use:
public class DatabaseOptions
{
public string Connection {get;set;}
}
Register:
services.Configure<DatabaseOptions>(
configuration.GetSection("Database"));
Senior Answer
Configuration should be environment-specific, secure, and injected through the application's configuration system rather than hardcoded.
21. What is a Microservices Architecture?
Interview Answer
Microservices architecture is a design approach where an application is divided into small, independent services that communicate through APIs or messaging.
Each service:
- owns a specific business capability
- can be deployed independently
- can scale independently
- can have its own database
Example
Traditional monolith:
+--------------------------------+
| E-Commerce App |
| |
| Users |
| Orders |
| Payments |
| Inventory |
| Shipping |
| |
+--------------------------------+
|
v
One Database
Microservices:
API Gateway
|
+------------+-------------+
| | |
User Service Order Service Payment Service
| | |
User DB Order DB Payment DB
Example Services
E-commerce system:
Service | Responsibility |
User Service | Authentication, profiles |
Product Service | Product catalog |
Order Service | Orders |
Payment Service | Payments |
Notification Service | Emails/SMS |
Advantages
Independent deployment
You can deploy:
Payment Service v2
without deploying:
Product Service
Independent scaling
Example:
During Black Friday:
Order Service
|
++++++++
++++++++
++++++++
Payment Service
|
++
Only the busy service scales.
Technology flexibility
Different services can use:
- .NET
- Java
- Python
- Node.js
Disadvantages
Microservices introduce complexity:
- network communication
- distributed transactions
- monitoring
- deployment complexity
- data consistency problems
Senior Answer
Microservices provide independent deployment and scaling, but they introduce distributed system complexity. I use them when business boundaries and scaling requirements justify the additional operational cost.
22. Monolith vs Microservices — what is the difference?
Interview Answer
A monolith is a single deployable application. Microservices split the application into independent services.
Monolith
Application
+------------------------------+
| |
| Users |
| Orders |
| Payments |
| Inventory |
| |
+------------------------------+
|
v
Database
Microservices
User API Order API Payment API
| | |
User DB Order DB Payment DB
Comparison
Monolith | Microservices |
Single deployment | Independent deployment |
Simple development | More operational complexity |
Easier debugging | Distributed debugging |
Shared database possible | Usually separate databases |
Good for smaller systems | Good for large systems |
When choose monolith?
Good when:
- application is small
- team is small
- requirements are changing quickly
When choose microservices?
Good when:
- multiple teams work independently
- system is large
- different scaling needs exist
Senior Answer
I don't choose microservices by default. I start with a modular monolith and move to microservices when organizational or scaling requirements justify it.
23. What is an API Gateway?
Interview Answer
An API Gateway is a single entry point that routes client requests to backend services.
Without gateway:
Mobile App
|
+---- User Service
|
+---- Order Service
|
+---- Payment Service
The client knows every service.
With gateway:
Client
|
API Gateway
/ | \
User Order Payment
Responsibilities
An API Gateway can handle:
Routing
Example:
/api/users
|
v
User Service
/api/orders
|
v
Order Service
Authentication
Validate:
JWT token
before forwarding.
Rate limiting
Example:
1000 requests/minute/user
Logging
Central place for:
- request tracking
- correlation IDs
Response aggregation
Example:
Mobile dashboard:
Get user
Get orders
Get payments
Gateway combines:
{
"user":"John",
"orders":5,
"balance":100
}
Examples
Common technologies:
- Azure API Management
- AWS API Gateway
- Ocelot (.NET)
- YARP (.NET reverse proxy)
Senior Answer
An API Gateway simplifies client communication by centralizing routing, security, monitoring, and cross-cutting concerns.
24. What is Service Discovery?
Interview Answer
Service discovery allows services to find each other dynamically without hardcoded addresses.
Problem:
Service A needs to call Service B.
Hardcoded:
http://192.168.1.25:5000/orders
Problem:
The address changes when containers restart.
Solution:
Service A
|
Service Registry
|
Service B Location
Example
Kubernetes:
order-service
|
|
Kubernetes DNS
|
|
order-service.default.svc.cluster.local
Types
Client-side discovery
Client asks registry:
Where is Order Service?
Client chooses instance.
Server-side discovery
Load balancer chooses instance.
Example:
Client
|
Load Balancer
|
Service Instance
Common Tools
- Kubernetes Service Discovery
- Consul
- Eureka
- AWS Cloud Map
Senior Answer
Service discovery removes dependency on fixed network locations and enables dynamic scaling in distributed systems.
25. What are Message Queues and why are they used?
Interview Answer
A message queue allows services to communicate asynchronously.
Instead of:
Service A
|
|
HTTP call
|
v
Service B
Use:
Service A
|
v
Message Queue
|
v
Service B
Example
Order processing:
User places order.
Without queue:
Order API
|
Payment
|
Inventory
|
|
Response
The user waits for everything.
With queue:
Order API
|
Create Order
|
Message Queue
|
Return Success
Background Workers:
Payment Worker
Inventory Worker
Email Worker
Benefits
Decoupling
Services do not know each other directly.
Reliability
Messages remain in the queue if consumers are temporarily unavailable.
Scalability
Multiple consumers can process messages.
Example:
Queue
|
+ Worker 1
|
+ Worker 2
|
+ Worker 3
Common Technologies
- RabbitMQ
- Azure Service Bus
- AWS SQS
- Kafka
Senior Answer
Message queues improve reliability and scalability by allowing asynchronous communication between distributed services.
26. Explain RabbitMQ architecture.
Interview Answer
RabbitMQ is a message broker that enables asynchronous communication between applications.
Main Components
Producer
|
v
Exchange
|
v
Queue
|
v
Consumer
Producer
Creates messages.
Example:
OrderCreated
Exchange
Receives messages and decides where to route them.
Types:
Direct Exchange
Exact routing key.
Example:
payment.created
Topic Exchange
Pattern matching.
Example:
order.*
Matches:
order.created
order.cancelled
Fanout Exchange
Broadcasts to all queues.
Queue
Stores messages until consumed.
Consumer
Processes messages.
Important Concepts
Acknowledgement
Consumer confirms:
Message processed successfully
RabbitMQ removes it.
Dead Letter Queue
Stores failed messages.
Example:
Payment failed repeatedly
|
v
Dead Letter Queue
Senior Answer
RabbitMQ provides reliable asynchronous communication using producers, exchanges, queues, and consumers with features like acknowledgements and retries.
27. What is Event-Driven Architecture?
Interview Answer
Event-driven architecture is a design where components communicate by publishing and consuming events.
An event represents something that already happened.
Example:
OrderCreated
CustomerRegistered
PaymentCompleted
Flow
Order Service
|
|
publishes
v
OrderCreated Event
|
+-------------+-------------+
Payment Service Notification Service
Event Example
{
"eventType":"OrderCreated",
"orderId":123,
"customerId":55
}
Benefits
- loose coupling
- scalability
- asynchronous processing
- easier integration
Challenges
- eventual consistency
- debugging complexity
- event versioning
Senior Answer
Event-driven architecture works well when systems need loose coupling and asynchronous communication, but requires careful handling of consistency and observability.
28. What is the Saga Pattern?
Interview Answer
Saga manages distributed transactions across multiple microservices.
Since microservices have separate databases, traditional transactions do not work.
Example:
Order process:
Order Service
|
Create Order
|
Payment Service
|
Charge Card
|
Inventory Service
|
Reserve Product
What if inventory fails?
We cannot rollback a database transaction.
Instead:
Payment Completed
|
Inventory Failed
|
Compensating Action:
Refund Payment
Cancel Order
Two Saga Approaches
1. Choreography
Services react to events.
Example:
OrderCreated
|
v
Payment Service
|
PaymentCompleted
|
Inventory Service
No central controller.
2. Orchestration
A coordinator controls the workflow.
Saga Orchestrator
|
Payment
|
Inventory
|
Shipping
Senior Answer
Saga provides transaction management in distributed systems using local transactions and compensating actions instead of global database transactions.
29. What are distributed transactions?
Interview Answer
A distributed transaction is a transaction involving multiple services or databases.
Example:
Order Database
+
Payment Database
+
Inventory Database
Traditional solution
Two-phase commit (2PC):
Prepare
Commit
Problem:
- slow
- difficult in cloud environments
- reduces availability
Modern approach
Use:
- Saga pattern
- Event-driven architecture
- eventual consistency
Example
Instead of:
Create order
Charge payment
Reserve inventory
All succeed or rollback
Use:
OrderCreated event
Payment processed
Inventory reserved
Final status updated
Senior Answer
In modern cloud systems I prefer eventual consistency patterns like Saga instead of distributed database transactions.
30. What is Idempotency and why is it important?
Interview Answer
An operation is idempotent if performing it multiple times produces the same result as performing it once.
Example:
HTTP GET:
GET /customers/10
Calling it 100 times:
Same result
Problem example:
Payment API:
POST /payment
Network failure happens.
Client retries:
Charge $100
Charge $100 again
Customer charged twice.
Solution: Idempotency Key
Request:
POST /payments
Idempotency-Key:
abc123
Server stores:
abc123 -> Payment completed
Retry:
abc123
returns existing result.
Common Uses
- payments
- order creation
- message processing
- cloud APIs
Senior Answer
Idempotency is critical in distributed systems because retries are common. It prevents duplicate processing when requests are repeated.
31. What are containers and why are they used?
Interview Answer
Containers package an application together with all required dependencies so it runs consistently across different environments.
A container includes:
- application code
- runtime
- libraries
- configuration
- operating system dependencies
Traditional Deployment
Developer Machine
.NET Version A
Libraries A,B,C
Production Server
.NET Version B
Libraries X,Y,Z
Problem:
"It works on my machine."
Container Deployment
Docker Container
+----------------------+
| Application |
| .NET Runtime |
| Libraries |
| Configuration |
+----------------------+
Runs everywhere
Benefits
Consistency
Same environment:
- development
- testing
- production
Isolation
Applications do not interfere with each other.
Scalability
Create more containers:
Load Balancer
|
+------------+------------+
Container 1 Container 2 Container 3
Common Technologies
- Docker
- Kubernetes
- Azure Container Apps
- AWS ECS
- AWS EKS
Senior Answer
Containers solve environment consistency problems and provide lightweight isolation and scalability for modern cloud applications.
32. What is Docker?
Interview Answer
Docker is a platform for building, packaging, and running containers.
Main Docker Concepts
Image
A blueprint for a container.
Example:
.NET 9 Application Image
Container
A running instance of an image.
Example:
Running API Container
Dockerfile
Defines how to build an image.
Example:
FROM mcr.microsoft.com/dotnet/aspnet:9.0
WORKDIR /app
COPY . .
ENTRYPOINT ["dotnet",
"MyApi.dll"]
Build:
docker build -t customer-api .
Run:
docker run -p 8080:8080 customer-api
Docker Compose
Runs multiple containers together.
Example:
services:
api:
image: customer-api
database:
image: postgres
Senior Answer
Docker provides a standard way to package applications and their dependencies, making deployments repeatable across environments.
33. What is Kubernetes?
Interview Answer
Kubernetes is a container orchestration platform that manages deployment, scaling, and availability of containers.
Without Kubernetes:
Developer manually:
Start container
Monitor container
Restart failed container
Scale manually
With Kubernetes:
Kubernetes Cluster
|
+-----------+-----------+
Pod Pod Pod
|
Container
Kubernetes Responsibilities
Deployment
Defines desired application state.
Example:
replicas: 3
Meaning:
Keep 3 copies of this service running.
Scaling
Increase replicas:
3 containers
↓
10 containers
Self-healing
If container crashes:
Container failed
↓
Kubernetes creates replacement
Service Discovery
Provides stable networking.
Example:
order-service
↓
Pod IP changes do not matter
Important Kubernetes Objects
Object | Purpose |
Pod | Runs containers |
Deployment | Manages replicas |
Service | Networking |
ConfigMap | Configuration |
Secret | Sensitive data |
Ingress | External routing |
Senior Answer
Kubernetes automates container deployment, scaling, networking, and recovery, making it suitable for large distributed systems.
34. What is the difference between Docker and Kubernetes?
Interview Answer
Docker creates and runs containers.
Kubernetes manages many containers.
Docker | Kubernetes |
Container runtime | Container orchestration |
Runs containers | Manages clusters |
Single machine focus | Multiple servers |
Build images | Deploy applications |
Example:
Docker:
Run one API container
Kubernetes:
Run:
10 API containers
Across:
5 servers
With:
Auto scaling
Senior Answer
Docker solves application packaging, while Kubernetes solves operating and managing containers at scale.
35. Explain CI/CD pipeline.
Interview Answer
CI/CD automates building, testing, and deploying software.
CI:
Continuous Integration
CD:
Continuous Delivery / Deployment
Pipeline Example
Developer
|
v
Git Commit
|
v
Build
|
v
Unit Tests
|
v
Security Scan
|
v
Create Package
|
v
Deploy
CI Activities
- compile code
- run tests
- check quality
- create artifacts
CD Activities
- deploy to environments
- run migrations
- release application
Example Tools
Source Control:
- GitHub
- GitLab
- Bitbucket
Build:
- Azure DevOps
- TeamCity
- Jenkins
Deployment:
- Kubernetes
- AWS CodeDeploy
- Azure Pipelines
Senior Answer
CI/CD reduces deployment risk by automating validation and delivery processes.
36. Describe a typical .NET CI/CD pipeline.
Interview Answer
A typical ASP.NET Core pipeline:
Step 1 — Developer pushes code
Git Push
Step 2 — Build
Example:
dotnet restore
dotnet build
Step 3 — Testing
dotnet test
Runs:
- unit tests
- integration tests
Step 4 — Code Analysis
Examples:
- SonarQube
- security scanning
Step 5 — Create Artifact
Example:
dotnet publish
Creates:
Application Package
Step 6 — Deploy
Example:
Development
↓
QA
↓
Production
Senior Answer
I prefer pipelines that automatically build, test, scan, package, and deploy applications with approvals before production releases.
37. What is Infrastructure as Code (IaC)?
Interview Answer
Infrastructure as Code manages infrastructure using configuration files instead of manual setup.
Traditional:
Create server manually
Configure network manually
Install software manually
Problem:
- inconsistent
- difficult to reproduce
IaC:
Configuration File
|
Automation Tool
|
Cloud Infrastructure
Examples
Terraform
Example:
resource "aws_instance" "web"
{
ami = "abc123"
instance_type = "t3.micro"
}
AWS CloudFormation
Azure ARM/Bicep
Benefits
- repeatability
- version control
- automation
- disaster recovery
Senior Answer
IaC allows infrastructure to be treated like software, making environments consistent, reproducible, and easier to manage.
38. What are load balancing strategies?
Interview Answer
Load balancing distributes incoming traffic across multiple servers.
Architecture:
Users
|
Load Balancer
/ | \
API1 API2 API3
Common Algorithms
Round Robin
Requests distributed sequentially.
Example:
Request 1 → Server A
Request 2 → Server B
Request 3 → Server C
Least Connections
Send traffic to the server with fewer active connections.
Weighted Load Balancing
Servers receive traffic based on capacity.
Example:
Server A: 70%
Server B: 30%
Health Checks
Load balancer removes unhealthy servers.
Example:
API2 failed
↓
Traffic goes to API1/API3
Examples
- AWS Elastic Load Balancer
- Azure Load Balancer
- NGINX
- HAProxy
Senior Answer
Load balancing improves availability and scalability by distributing traffic and removing unhealthy instances automatically.
39. What are scalability patterns?
Interview Answer
Scalability means the ability of a system to handle increasing workload.
There are two main approaches.
Vertical Scaling
Increase server power.
Example:
Before:
4 CPU
16 GB RAM
After:
16 CPU
64 GB RAM
Advantages:
- simple
- no architecture changes
Disadvantages:
- hardware limits
- expensive
Horizontal Scaling
Add more servers.
Example:
Before:
API Server
After:
API1
API2
API3
Advantages:
- unlimited growth
- cloud friendly
Other Patterns
Caching
Example:
Database
↓
Redis Cache
Database scaling
- read replicas
- partitioning
- sharding
Asynchronous processing
Use:
- RabbitMQ
- Kafka
- SQS
Senior Answer
Modern cloud applications usually prefer horizontal scaling combined with caching, asynchronous processing, and stateless services.
40. What is High Availability (HA)?
Interview Answer
High Availability means designing systems that continue operating despite failures.
The goal:
Minimize downtime.
Basic Example
Single server:
Users
|
Server
|
Database
Problem:
Server failure = application unavailable.
High Availability:
Load Balancer
/ \
Server 1 Server 2
|
Database Cluster
HA Techniques
Multiple instances
Avoid single points of failure.
Health checks
Detect failures.
Automatic failover
Move workload automatically.
Database replication
Example:
Primary DB
|
Replica DB
Cloud Examples
AWS:
- Availability Zones
- Auto Scaling Groups
- RDS Multi-AZ
Azure:
- Availability Sets
- Availability Zones
- Scale Sets
Senior Answer
High availability requires eliminating single points of failure through redundancy, health monitoring, and automatic recovery mechanisms.
41. What is Disaster Recovery (DR)?
Interview Answer
Disaster Recovery is the process of restoring applications and data after a major failure.
Examples:
- data center outage
- database corruption
- cyber attack
- accidental deletion
- cloud region failure
Important DR Concepts
RTO — Recovery Time Objective
Defines:
How quickly the system must recover.
Example:
Application must recover within 1 hour
RPO — Recovery Point Objective
Defines:
How much data loss is acceptable.
Example:
Maximum acceptable data loss:
15 minutes
DR Strategies
1. Backup and Restore
Production
|
Backup Storage
|
Restore after failure
Cheapest but slow.
2. Pilot Light
Keep minimal infrastructure running.
Example:
Production Region
|
Database Backup
|
Small DR Environment
3. Warm Standby
A partially running environment.
Example:
Primary Region
|
DR Region
(servers already running)
4. Active-Active
Multiple production environments.
Users
|
+------+------+
Region A Region B
Traffic goes to both.
Senior Answer
Disaster recovery requires defining RTO and RPO, then choosing an appropriate strategy based on business requirements and cost.
42. What is observability?
Interview Answer
Observability is the ability to understand the internal state of a system by analyzing its outputs.
The three main pillars are:
- Logs
- Metrics
- Traces
1. Logs
Events that happened.
Example:
2026-07-25 10:15
Order 123 created successfully
2. Metrics
Numeric measurements.
Examples:
CPU usage: 75%
Requests/sec: 500
Database latency: 120ms
3. Distributed Tracing
Tracks a request across multiple services.
Example:
User Request
|
API Gateway
20ms
|
Order Service
50ms
|
Payment Service
300ms
Senior Answer
Observability allows teams to understand system behavior and troubleshoot production issues using logs, metrics, and traces.
43. What is distributed logging?
Interview Answer
Distributed logging collects logs from multiple services into a centralized system.
Problem:
Microservices:
User Service
Order Service
Payment Service
Notification Service
Each service has its own logs.
Solution:
Services
|
Logging Agent
|
Central Log System
|
Search Dashboard
Common Technologies
- Elasticsearch + Kibana
- Splunk
- AWS CloudWatch Logs
- Azure Monitor
- Application Insights
Correlation ID
A unique identifier follows a request.
Example:
Request:
CorrelationId:
abc-123
Logs:
API Gateway
abc-123
Order Service
abc-123
Payment Service
abc-123
Now you can trace one user request.
Senior Answer
In distributed systems, correlation IDs and centralized logging are essential for troubleshooting requests across multiple services.
44. What is OpenTelemetry?
Interview Answer
OpenTelemetry is an open standard for collecting telemetry data:
- traces
- metrics
- logs
It allows applications to send observability data to different monitoring platforms.
Architecture
Application
|
OpenTelemetry SDK
|
Collector
|
+------------+------------+
Azure AWS Jaeger
Monitor CloudWatch
Example in .NET
Install:
OpenTelemetry.Extensions.Hosting
Configure:
builder.Services
.AddOpenTelemetry()
.AddTracing();
Benefits
- vendor-neutral
- standard format
- works across languages
- easier cloud migration
Senior Answer
OpenTelemetry provides a standardized way to collect telemetry data and avoids being locked into one monitoring vendor.
45. What are common cloud architecture patterns?
Interview Answer
Cloud architecture patterns solve common scalability, reliability, and maintainability problems.
1. Stateless Services
Application servers do not store user state.
Example:
Request 1
API Server A
Request 2
API Server B
Both work.
2. Cache-Aside Pattern
Application checks cache first.
Request
|
Cache
|
Database
Example:
Redis + SQL Server.
3. Queue-Based Load Leveling
Protects systems from traffic spikes.
Users
|
Queue
|
Workers
4. Circuit Breaker
Prevents repeated calls to failing services.
Example:
Payment Service Down
|
Circuit Opens
|
Stop Sending Requests
5. Retry Pattern
Automatically retry temporary failures.
Example:
Network timeout
Retry
Success
Senior Answer
Cloud patterns improve reliability by handling failures, scaling workloads, and reducing coupling between components.
46. What is Azure App Service?
Interview Answer
Azure App Service is a Platform as a Service (PaaS) offering for hosting web applications and APIs.
It supports:
- ASP.NET Core
- Node.js
- Java
- Python
Architecture
User
|
Azure App Service
|
Application
|
Database / External Services
Features
Deployment Slots
Example:
Production Slot
|
Staging Slot
Deploy and test before swapping.
Auto Scaling
Increase instances automatically.
Managed SSL
Azure manages certificates.
Monitoring
Integration with:
- Application Insights
Senior Answer
Azure App Service removes infrastructure management overhead while providing scaling, deployment slots, security, and monitoring.
47. What is AWS ECS?
Interview Answer
Amazon Elastic Container Service (ECS) is a service for running and managing Docker containers.
Architecture
Docker Image
|
ECS Cluster
|
Container Tasks
|
Application
Components
Task Definition
Defines:
- container image
- CPU
- memory
- ports
- environment variables
Example:
{
"image":"customer-api:v1",
"memory":1024
}
Service
Maintains desired number of containers.
Example:
Desired Count = 3
ECS keeps 3 containers running.
Cluster
Collection of resources running containers.
ECS vs Kubernetes
ECS | Kubernetes |
AWS managed | Cloud-neutral |
Simpler | More flexible |
AWS ecosystem | Multi-cloud |
Senior Answer
ECS is a managed container orchestration service that simplifies running Docker applications in AWS.
48. What is AWS EKS?
Interview Answer
Amazon Elastic Kubernetes Service (EKS) is AWS's managed Kubernetes service.
It runs Kubernetes control plane while AWS manages infrastructure.
Architecture
Developer
|
Kubernetes API
|
EKS Control Plane
|
Worker Nodes
|
Containers
Benefits
- standard Kubernetes
- AWS integration
- managed control plane
- auto scaling support
Common Integrations
- EC2
- IAM
- Load Balancer
- CloudWatch
- RDS
Senior Answer
EKS provides Kubernetes orchestration in AWS while reducing the operational overhead of managing the Kubernetes control plane.
49. What is Serverless Architecture?
Interview Answer
Serverless architecture allows developers to run code without managing servers.
The cloud provider manages:
- infrastructure
- scaling
- availability
Examples:
AWS:
- Lambda
Azure:
- Azure Functions
Traditional:
Application
|
Server
|
Operating System
|
Infrastructure
Serverless:
Function Code
|
Cloud Platform
|
Infrastructure Managed Automatically
Example
Image processing:
User uploads image
|
S3 Bucket Event
|
Lambda Function
|
Resize Image
Benefits
- automatic scaling
- pay per execution
- less infrastructure management
Disadvantages
- cold start latency
- execution limits
- vendor lock-in
Senior Answer
Serverless is useful for event-driven workloads and unpredictable traffic where managing servers would add unnecessary complexity.
50. How would you design an event-driven cloud system?
Interview Answer
I would use asynchronous communication with events and independently scalable consumers.
Example: Order Processing
Architecture:
Client
|
API Gateway
|
Order Service
|
OrderCreated Event
|
Message Broker
/ | \
Payment Inventory Notification
Service Service Service
Components
API Layer
Receives requests.
Example:
- ASP.NET Core Web API
Message Broker
Examples:
- RabbitMQ
- AWS SQS
- Azure Service Bus
- Kafka
Consumers
Process events independently.
Storage
Each service owns its data:
Order DB
Payment DB
Inventory DB
Important Considerations
Idempotency
Handle duplicate messages.
Retry Policy
Retry temporary failures.
Dead Letter Queue
Store failed messages.
Monitoring
Track:
- latency
- failures
- message backlog
Senior Answer
I would design the system around asynchronous events, independent services, reliable messaging, idempotent consumers, and strong observability.
51. What is OAuth 2.0?
Interview Answer
OAuth 2.0 is an authorization framework that allows applications to access resources on behalf of a user without sharing the user's password.
It answers:
"Is this application allowed to access this resource?"
Example
A user wants to allow a third-party application to access their profile.
Instead of:
Application
|
|
User password
OAuth uses:
User
|
Authorization Server
|
Access Token
|
API Resource
Common OAuth Roles
Resource Owner
The user.
Example:
John
Client
The application requesting access.
Example:
Mobile App
Authorization Server
Issues tokens.
Examples:
- Microsoft Entra ID
- Auth0
- Okta
Resource Server
The API protecting data.
Example:
Customer API
Common Grant Types
Authorization Code Flow
Most common for web applications.
Flow:
User Login
|
Authorization Server
|
Authorization Code
|
Application
|
Access Token
Client Credentials Flow
For service-to-service communication.
Example:
Order Service
|
Payment API
No user involved.
Senior Answer
OAuth 2.0 is used for delegated authorization. It allows applications to access protected resources using tokens instead of sharing credentials.
52. What is OpenID Connect (OIDC)?
Interview Answer
OpenID Connect is an authentication layer built on top of OAuth 2.0.
OAuth:
"What can you access?"
OIDC:
"Who are you?"
Flow
User
|
Identity Provider
|
ID Token
|
Application
Example ID Token
JWT:
{
"name": "John",
"email": "john@test.com",
"sub": "12345"
}
OAuth vs OIDC
OAuth 2.0 | OpenID Connect |
Authorization | Authentication |
Access token | ID token |
Access resources | Identify users |
Common Providers
- Microsoft Entra ID
- Google Identity
- Auth0
- Okta
Senior Answer
I use OpenID Connect when applications need user authentication, and OAuth 2.0 for API authorization.
53. What is JWT authentication?
Interview Answer
JWT (JSON Web Token) is a compact token format used to securely transmit identity information between parties.
JWT Structure
A JWT contains:
Header.Payload.Signature
Example:
xxxxx.yyyyy.zzzzz
Header
Contains metadata:
{
"alg":"RS256",
"typ":"JWT"
}
Payload
Contains claims:
{
"sub":"123",
"role":"Admin",
"exp":1700000000
}
Signature
Ensures the token was not modified.
Authentication Flow
Client
|
| username/password
v
Authentication Server
|
| JWT Token
v
Client
|
| Bearer Token
v
API
ASP.NET Core Example
Configuration:
services
.AddAuthentication()
.AddJwtBearer();
Senior Answer
JWT provides stateless authentication and works well with distributed systems because the server does not need to store session information.
54. How do you secure a Web API?
Interview Answer
API security requires multiple layers.
1. Authentication
Verify identity.
Examples:
- JWT
- OAuth2
- OpenID Connect
2. Authorization
Control permissions.
Examples:
- roles
- claims
- policies
3. HTTPS
Encrypt communication.
Never send credentials over HTTP.
4. Input Validation
Protect against:
- SQL injection
- malicious input
- invalid data
Example:
if(string.IsNullOrEmpty(request.Email))
{
return BadRequest();
}
5. Rate Limiting
Prevent abuse.
Example:
100 requests/minute/user
6. Secure Headers
Examples:
- Content Security Policy
- HSTS
- X-Content-Type-Options
7. Secrets Management
Do not store:
{
"password":"123456"
}
Use:
- Azure Key Vault
- AWS Secrets Manager
Senior Answer
API security requires authentication, authorization, encryption, validation, rate limiting, and proper secret management.
55. What is ASP.NET Core Data Protection?
Interview Answer
ASP.NET Core Data Protection provides cryptographic services for protecting sensitive application data.
Used for:
- authentication cookies
- CSRF tokens
- temporary data
- password reset tokens
Example:
IDataProtector protector =
provider.CreateProtector(
"UserPassword");
Protect:
var encrypted =
protector.Protect("secret");
Unprotect:
var original =
protector.Unprotect(encrypted);
In Distributed Applications
Multiple servers need shared keys.
Example:
Server 1
|
Shared Key Storage
|
Server 2
Possible storage:
- Azure Blob Storage
- Redis
- Database
Senior Answer
Data Protection provides secure encryption services inside ASP.NET Core and is especially important when applications run across multiple instances.
56. How do you manage secrets in cloud applications?
Interview Answer
Secrets should never be stored in source code.
Examples of secrets:
- database passwords
- API keys
- certificates
- connection strings
Bad:
{
"ConnectionString":
"Password=myPassword123"
}
Better:
Application
|
Secret Manager
|
Retrieve Secret
Examples
Azure:
- Azure Key Vault
AWS:
- AWS Secrets Manager
- AWS Parameter Store
.NET Example
builder.Configuration
.AddAzureKeyVault();
Benefits
- centralized management
- auditing
- rotation
- access control
Senior Answer
I externalize secrets using managed secret stores and control access through identity-based permissions.
57. How do you improve ASP.NET Core application performance?
Interview Answer
Performance optimization should be based on measurements and profiling.
1. Database Optimization
Use:
- indexes
- efficient queries
- pagination
- caching
2. Async Programming
Avoid blocking threads.
Bad:
var result =
service.GetData().Result;
Better:
var result =
await service.GetDataAsync();
3. Caching
Use:
- MemoryCache
- Redis
Example:
Request
|
Redis
|
Database
4. Response Compression
Reduce payload size.
5. Connection Pooling
Reuse connections.
6. Reduce Allocations
Use:
- Span<T>
- pooling
- efficient collections
Senior Answer
I first measure performance using profiling tools, then optimize the bottleneck instead of making premature optimizations.
58. How do you troubleshoot a slow production application?
Interview Answer
I follow a systematic approach.
Step 1 — Check Monitoring
Look at:
- CPU
- memory
- requests per second
- errors
- latency
Step 2 — Check Application Logs
Look for:
- exceptions
- slow operations
- dependency failures
Step 3 — Check Database
Analyze:
- slow queries
- execution plans
- locks
- indexes
Step 4 — Check External Dependencies
Examples:
- APIs
- queues
- storage
Step 5 — Profile
Tools:
- Application Insights
- AWS X-Ray
- dotTrace
- PerfView
Example Scenario
Problem:
API response time increased from 200ms to 5 seconds
Investigation:
API logs
|
Database query took 4.5 seconds
|
Missing index
|
Add index
|
Response returns to normal
Senior Answer
I use observability data to identify whether the bottleneck is application code, database, infrastructure, or external dependencies.
59. How would you design a scalable ASP.NET Core application?
Interview Answer
I would design around scalability, reliability, and maintainability.
Architecture
Users
|
Load Balancer
|
ASP.NET Core APIs
/ \
Cache Database
Redis SQL
Message Queue
|
Background Workers
Key Design Decisions
Stateless APIs
Allow horizontal scaling.
Caching
Reduce database load.
Async Processing
Move long operations to background workers.
Database Optimization
Use:
- indexes
- read replicas
- partitioning
Monitoring
Implement:
- logs
- metrics
- tracing
Senior Answer
A scalable ASP.NET Core system should use stateless services, caching, asynchronous processing, optimized data access, and strong observability.
60. How do you answer a system design interview question?
Interview Answer
I follow a structured approach.
Step 1 — Clarify Requirements
Ask:
- expected users?
- traffic volume?
- availability requirements?
- data size?
- security needs?
Step 2 — Define High-Level Architecture
Example:
Client
|
API Gateway
|
Services
|
Database / Cache / Queue
Step 3 — Design Components
Discuss:
- APIs
- databases
- messaging
- caching
- security
Step 4 — Discuss Scaling
Explain:
- load balancing
- horizontal scaling
- partitioning
- caching
Step 5 — Discuss Reliability
Include:
- retries
- circuit breakers
- monitoring
- disaster recovery
Example Interview Question
"Design a stock trading platform."
Answer structure:
Frontend
|
API Gateway
|
Trading Services
|
Market Data Service
|
Message Queue
|
Database
|
Cache
Consider:
- real-time updates
- low latency
- security
- audit logs
- scalability
Senior Answer
In system design interviews, I start with requirements, define the architecture, explain trade-offs, and discuss scalability, reliability, and security.
Chapter 4 — .NET / ASP.NET Core Architecture Completed ✅
Total Questions Completed: 60
You should now be prepared for:
✅ ASP.NET Core architecture
✅ Clean Architecture
✅ Microservices
✅ Distributed systems
✅ Cloud design
✅ Security architecture
✅ DevOps concepts
✅ Production troubleshooting