Monday, 13 July 2026

Azure

1. What is REST API?

Answer

REST (Representational State Transfer) is an architectural style for building web services that communicate over HTTP. A REST API exposes resources through URLs and uses standard HTTP methods like GET, POST, PUT, PATCH, and DELETE.

Example

GET /api/orders

Returns all orders.

GET /api/orders/101

Returns Order 101.

Characteristics

  • Stateless communication

  • Client-Server architecture

  • Uniform interface

  • Cacheable responses

  • Uses HTTP methods and status codes

  • Supports JSON/XML (JSON is most common)

Real-time Example

In an e-commerce application:

  • Customer API

  • Order API

  • Payment API

  • Inventory API

Each exposes REST endpoints independently.


2. What are REST API Best Practices?

Answer

A well-designed REST API should follow these best practices:

  • Use nouns instead of verbs.

    • Good: /api/orders

    • Bad: /api/getOrders

  • Use proper HTTP methods.

  • Return correct HTTP status codes.

  • Use API versioning (/api/v1/orders).

  • Validate request models.

  • Handle exceptions globally.

  • Implement authentication and authorization.

  • Support pagination and filtering.

  • Use asynchronous programming.

  • Document APIs using Swagger/OpenAPI.

Interview Tip

Mention Swagger, JWT, FluentValidation, API Versioning, and Global Exception Middleware.


3. Difference between PUT and PATCH?

Answer

PUTPATCH
Replaces the complete resourceUpdates only specified fields
Client sends the entire objectClient sends only changed properties
IdempotentUsually idempotent

Example:

PUT

{
 "Name":"John",
 "Age":30
}

PATCH

{
 "Age":31
}

4. How do you secure REST APIs?

Answer

I typically use:

  • JWT Authentication

  • OAuth2/OpenID Connect

  • Azure AD or Microsoft Entra ID

  • Role-Based Authorization

  • Claims-Based Authorization

  • HTTPS

  • CORS

  • Rate Limiting

  • Input Validation

  • API Gateway

Interview Scenario

"In one project, APIs were secured using JWT tokens issued by Azure AD. Each API validated the JWT, extracted claims, and authorized access based on user roles."


5. How do you improve REST API performance?

Answer

Several techniques:

  • Async programming (async/await)

  • Pagination

  • Projection (DTOs)

  • Database indexing

  • Response compression

  • Redis caching

  • Connection pooling

  • Minimize database round trips

  • Application Insights monitoring

Example

Instead of:

SELECT *

Use

SELECT Id,Name

using DTO projection.


6. Explain Idempotency.

Answer

Idempotency means performing the same operation multiple times should produce the same result.

Example:

Customer clicks "Pay" twice.

Without idempotency:

Two payments.

With idempotency:

Only one payment.

Implementation:

  • Idempotency Key

  • Unique Request ID

  • Duplicate Detection


7. Explain Microservices.

Answer

Microservices is an architectural style where an application is divided into small, independently deployable services. Each service owns a specific business capability and typically has its own database.

Example

Customer Service

Order Service

Payment Service

Inventory Service

Notification Service

Each service:

  • Own Database

  • Own Deployment

  • Independent Scaling

  • Independent Team


8. Microservices vs Monolithic

MonolithicMicroservices
Single deploymentIndependent deployments
One databaseDatabase per service
Tight couplingLoose coupling
Hard to scaleScale individual services
Technology lockedPolyglot possible

9. How do Microservices communicate?

Answer

Two ways:

Synchronous

  • REST API

  • gRPC

Used when immediate response is required.

Example

Order Service

↓

Customer Service

Asynchronous

  • Azure Service Bus

  • Kafka

  • RabbitMQ

Example

Order Created Event

↓

Inventory

↓

Email

↓

Analytics

↓

Invoice

10. What is API Gateway?

Answer

API Gateway is the single entry point for all client requests.

Responsibilities:

  • Authentication

  • Routing

  • Rate Limiting

  • Logging

  • SSL Termination

  • Caching

Examples:

  • Azure API Management

  • YARP

  • Ocelot


Event-Driven Architecture


11. What is Event-Driven Architecture?

Answer

Instead of services calling each other directly, services publish events. Other services subscribe and react independently.

Example

Order Created

↓

Service Bus Topic

↓

Inventory

↓

Email

↓

Invoice

↓

Analytics

Advantages

  • Loose coupling

  • Better scalability

  • Independent deployments

  • Easy integration


12. Queue vs Topic?

Queue

One producer

One consumer


Topic

One producer

Many subscribers

Example

Order Created

↓

Topic

↓

Email

↓

SMS

↓

Analytics

13. Explain Dead Letter Queue.

Answer

Messages that cannot be processed after retries move to the Dead Letter Queue (DLQ).

Reasons

  • Invalid message format

  • Max retries exceeded

  • Business validation failure

After fixing the issue, messages can be replayed.


14. Explain Idempotent Consumer.

Answer

Sometimes the same message is delivered twice.

Consumer should process it only once.

Methods

  • Store MessageId

  • Database unique constraint

  • Duplicate Detection


Unit Testing


15. What is Unit Testing?

Answer

Unit testing verifies a single class or method in isolation.

Frameworks

  • xUnit

  • NUnit

  • MSTest

Mocking

  • Moq


16. What should be mocked?

Mock

  • Repository

  • External APIs

  • Payment Gateway

  • Logger

  • Email Service

Don't mock

Business logic


17. Difference between Unit Test and Integration Test?

Unit TestIntegration Test
Tests one classTests multiple components
Uses mocksUses real dependencies
Very fastSlower
No databaseDatabase allowed

Azure Functions


18. What is Azure Function?

Answer

Azure Function is a serverless compute service that runs code in response to events.

Triggers

  • HTTP

  • Blob

  • Queue

  • Timer

  • Service Bus


19. Why Isolated Worker?

Answer

Microsoft recommends Isolated Worker because:

  • Supports .NET 8+

  • Better Dependency Injection

  • Independent runtime

  • Better middleware support

  • Future-proof


20. What is Cold Start?

Answer

In Consumption Plan, the first request after inactivity takes longer because the Function App needs to start.

Solutions

  • Premium Plan

  • Always Ready instances

  • Keep-alive pings


Azure Service Bus


21. Why Service Bus instead of REST?

REST

Immediate response

Service Bus

Reliable asynchronous messaging

Retry

Dead Letter Queue

Ordering

Transactions


22. Peek Lock vs Receive and Delete?

Peek Lock

Receive

Process

Complete

Safe


Receive and Delete

Deletes immediately

Risk of message loss


Azure Key Vault


23. What is Azure Key Vault?

Answer

Secure storage for

  • Secrets

  • Certificates

  • Encryption Keys

Never store

Connection Strings

Passwords

API Keys

inside appsettings.json.

Use Managed Identity.


Azure Blob Storage


24. What is Blob Storage?

Stores

  • Images

  • Videos

  • Documents

  • Backups

Supports

  • SAS Tokens

  • Versioning

  • Lifecycle Management

  • Geo-redundancy


Azure Queue Storage


25. Difference between Queue Storage and Service Bus?

Queue StorageService Bus
Basic messagingEnterprise messaging
CheapMore features
No ordering guaranteeSessions for ordering
No DLQ (same capabilities)Dead Letter Queue
Simple retryAdvanced retry

Application Insights


26. What does Application Insights monitor?

  • Requests

  • Exceptions

  • Dependencies

  • SQL queries

  • Performance

  • Availability

  • Distributed tracing


27. How do you troubleshoot a slow API?

Steps

  1. Open Application Insights.

  2. Check Response Time.

  3. Check Dependency Calls.

  4. Find slow SQL.

  5. Check Exceptions.

  6. Optimize.


Azure DevOps


28. Explain Pull Request Workflow.

Developer

Feature Branch

Commit

Push

Pull Request

Code Review

Build Validation

Approval

Merge


29. What do you check in Code Review?

  • Naming

  • SOLID

  • Exception Handling

  • Logging

  • Security

  • Performance

  • Unit Tests

  • Code Duplication


GitFlow


30. Explain GitFlow.

main

↓

develop

↓

feature branches

↓

release branch

↓

main

↓

hotfix

↓

main

↓

develop

31. Difference between Merge and Rebase?

Merge

Keeps history

Safe

Rebase

Cleaner history

Rewrites commits


Senior-Level Scenario Question

Question:

Design an Azure-based e-commerce system where an Order API receives 10,000 requests per minute. Orders should trigger payment processing, inventory updates, email notifications, invoice generation, and analytics. The system must remain available even if the Payment service is temporarily unavailable.

Answer (Interview):

"I would expose the Order API through Azure API Management or YARP and implement it using ASP.NET Core. Secrets like database connection strings and API keys would be stored in Azure Key Vault and accessed via Managed Identity. After validating and storing the order in SQL Server, the API would publish an OrderCreated event to an Azure Service Bus Topic. Services such as Inventory, Notification, Invoice, and Analytics would subscribe independently to the topic, enabling loose coupling and scalability. For the external Payment service, I would use Polly with Retry, Circuit Breaker, and Timeout policies to handle transient failures. Consumers would be idempotent by storing processed message IDs to prevent duplicate processing. Product images would be uploaded directly to Azure Blob Storage using SAS tokens, avoiding large file uploads through the API. Azure Functions (Isolated Worker) would process background tasks like invoice generation or image processing. Azure Application Insights would provide distributed tracing, dependency monitoring, exception tracking, and performance metrics. The solution would follow SOLID principles, use dependency injection, include xUnit-based unit tests and integration tests, and be deployed through Azure DevOps CI/CD with GitFlow branching and Pull Request approvals."



IQS


.NET Core Version

Current .NET versions:

  • .NET 6 – LTS (Support ended)

  • .NET 8 – Current LTS (Most companies use this)

  • .NET 9 – Standard Term Support (STS)

Answer

I have primarily worked on .NET Core 6 and .NET 8 for developing REST APIs and Microservices. Most production applications are currently on .NET 8 because it is an LTS version.


What is your approach in CQRS Pattern?

CQRS (Command Query Responsibility Segregation) separates read and write operations.

Command Side

  • Insert

  • Update

  • Delete

Query Side

  • Read operations only

Workflow

Client
   |
Command API
   |
Command Handler
   |
Database

Client
   |
Query API
   |
Query Handler
   |
Read Database

Advantages

  • Better scalability

  • Better performance

  • Independent optimization

  • Easy maintenance


How do Microservices communicate?

Two ways:

1. Synchronous

  • REST API

  • gRPC

Used when immediate response is required.

Example

Order Service
      |
 REST API
      |
Inventory Service

2. Asynchronous

Using

  • RabbitMQ

  • Kafka

  • Azure Service Bus

  • AWS SQS

Used for

  • Email

  • Notifications

  • Payment

  • Order processing

No direct dependency.


How do you populate data from two tables using Microservices?

Never directly join another service's database.

Correct approaches:

Option 1 (Most common)

Order Service calls Customer Service API.

Order Service
      |
Customer API
      |
Customer Details

Merge the response.


Option 2

Use API Gateway or Aggregator Service.

Client
   |
Aggregator Service
  /      \
Order   Customer

Option 3

CQRS Read Model

Combine data using events.


Request Flow in Microservices

Client

API Gateway

Authentication

Order Service

Business Logic

Database

Response

If another service is required

Order Service

Inventory Service

Payment Service

Notification Service

What is an Abstract Class?

An abstract class cannot be instantiated.

It contains

  • Abstract methods

  • Normal methods

  • Constructors

  • Fields

Example

abstract class Animal
{
    public abstract void Sound();

    public void Eat()
    {
        Console.WriteLine("Eating");
    }
}

Used when multiple classes share common functionality.


If two tables need updating in Microservices?

If both tables belong to same service

Use

TransactionScope

or

Begin Transaction
Commit
Rollback

If different microservices

Don't use distributed transactions.

Use

  • Saga Pattern

  • Event-driven architecture


API Gateway Techniques

Popular gateways

  • YARP (.NET)

  • Ocelot

  • Azure API Management

  • AWS API Gateway

  • Kong

Responsibilities

  • Authentication

  • Authorization

  • Routing

  • Load balancing

  • Rate limiting

  • Logging

  • SSL termination

  • Caching


Authentication in Microservices

Usually JWT with OAuth2/OpenID Connect.

Flow

User Login

Identity Provider

JWT Generated

Client stores JWT

Each request sends JWT

API Gateway validates

Microservice validates

How to Configure JWT?

Install

Microsoft.AspNetCore.Authentication.JwtBearer

Program.cs

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer=true,
        ValidateAudience=true,
        ValidateLifetime=true,
        ValidateIssuerSigningKey=true
    };
});

Four Microservices - User communicates with only one service?

User never calls all services.

Flow

Client

API Gateway

Order Service

Inventory Service

Payment Service

Notification Service

Gateway routes requests.


JWT Lifecycle

Login

Generate JWT

Return Token

Client stores Token

Every Request

Validate JWT

Expired

Refresh Token

New JWT

Main Purpose of Terraform

Infrastructure as Code (IaC).

Automates

  • EC2

  • S3

  • RDS

  • VPC

  • IAM

  • Kubernetes

  • Azure Resources

Benefits

  • Version Control

  • Automation

  • Repeatability

  • Easy rollback


CI/CD Pipeline Issues

Common challenges

  • Build failures

  • Dependency conflicts

  • Deployment failures

  • Wrong environment variables

  • Secret management

  • Docker image issues

  • Rollback

  • Long build time

  • Test failures


How do you maintain logs?

Centralized logging.

Popular tools

  • Serilog

  • NLog

  • ELK Stack

  • Splunk

  • Grafana Loki

  • Azure Application Insights

  • AWS CloudWatch

Always include

  • Correlation ID

  • User ID

  • Request ID

  • Exception details


What is RDS?

Amazon RDS

Managed relational database.

Supports

  • SQL Server

  • MySQL

  • PostgreSQL

  • MariaDB

  • Oracle

Features

  • Backup

  • Monitoring

  • High Availability

  • Scaling


Read Replica vs Write Replica

Primary

  • Read

  • Write

Read Replica

  • Read only

Purpose

  • Reporting

  • Analytics

  • High read traffic


Disaster Recovery in Same AZ?

Not recommended.

AZ failure impacts everything.

Use

  • Multi-AZ

  • Cross-region replication

  • Automated backups


Availability Zone vs Region

RegionAvailability Zone
Geographic locationOne or more data centers
Example: Mumbaiap-south-1a
Multiple AZsIndependent power/network

How does AZ work?

Application deployed across

AZ-1

AZ-2

AZ-3

If one AZ fails

Traffic moves automatically.


Authentication vs Authorization

Authentication

Who are you?

Example

Login

Authorization

What can you access?

Example

Admin

Employee

Manager


Concurrency vs Parallelism

Concurrency

Multiple tasks make progress.

Parallelism

Multiple tasks execute simultaneously.


Unit Testing

Tests individual methods.

Popular frameworks

  • xUnit

  • NUnit

  • MSTest

Mocking

  • Moq


CQRS Workflow

Client

Command API

Command Handler

Database

Publish Event

Update Read Model

Query API

Read Database

Response

Design Patterns in Microservices

  • CQRS

  • Saga

  • Circuit Breaker

  • API Gateway

  • Repository

  • Dependency Injection

  • Factory

  • Observer

  • Retry Pattern

  • Bulkhead

  • Outbox Pattern


Snapshot (AWS)

Snapshot

Point-in-time backup of

  • EBS

  • RDS

Used for

  • Disaster Recovery

  • Restore

  • Migration


Why React?

Advantages

  • Component-based

  • Virtual DOM

  • Fast rendering

  • Reusable components

  • Large ecosystem

  • Easy integration with APIs


.NET Framework vs .NET Core

.NET Framework.NET
Windows onlyCross-platform
SlowerFaster
IIS dependentSelf-hosted/Kestrel
OlderModern
Less cloud friendlyCloud-native
Limited containersDocker/Kubernetes support

Middleware

Middleware processes every HTTP request.

Pipeline

Request

Logging

Authentication

Authorization

Exception

Controller

Response

If Middleware fails?

If exception isn't handled

Request stops.

Returns

500 Internal Server Error

Use

app.UseExceptionHandler();

Global exception middleware prevents application crash.


JWT Token

Contains

  • Header

  • Payload

  • Signature

Stateless authentication.


Expiry Time

Usually

  • 15 minutes

  • 30 minutes

  • 1 hour

Configured using

expires: DateTime.UtcNow.AddMinutes(30)

Refresh Token Purpose

Used to obtain a new JWT without requiring the user to log in again.

Benefits

  • Better security

  • Improved user experience


Delegate in C#

A delegate is a type-safe function pointer.

Example

delegate void Notify();

Notify n = ShowMessage;

Multicast Delegate

Can invoke multiple methods.

notify += Email;
notify += SMS;

notify();

Both methods execute.


Unique Elements with Collections

Use

HashSet<int>

Automatically removes duplicates.


Binary Search vs Linear Search

Binary SearchLinear Search
Sorted data requiredNo sorting needed
O(log n)O(n)
FasterSlower

Which Data Structures do you use?

  • Dictionary → Fast lookup

  • List → Sequential data

  • HashSet → Unique values

  • Queue → FIFO

  • Stack → LIFO

  • ConcurrentDictionary → Multithreading


Code First Approach

Write C# classes first.

Entity Framework creates database.

Commands

Add-Migration

Update-Database

JWT NuGet Package

Microsoft.AspNetCore.Authentication.JwtBearer

Also commonly used:

System.IdentityModel.Tokens.Jwt

Protect API From

  • JWT Authentication

  • OAuth2

  • HTTPS

  • Rate Limiting

  • API Gateway

  • IP Filtering

  • CORS

  • Input Validation

  • WAF


Prevent API from DDoS

  • AWS Shield

  • AWS WAF

  • Azure Front Door

  • Azure DDoS Protection

  • API Gateway Rate Limiting

  • CDN

  • Load Balancer

  • Auto Scaling


Indexes

Improve query performance.

Types

  • Clustered

  • Non-clustered

  • Composite

  • Filtered

  • Unique


How many Clustered Indexes?

Clustered

Only 1 per table.

Non-clustered

Up to 999 per table (SQL Server).


SQL Query Performance

Techniques

  • Proper indexes

  • Avoid SELECT *

  • Use execution plans

  • Optimize joins

  • Use stored procedures where appropriate

  • Partition large tables

  • Keep statistics updated

  • Avoid unnecessary cursors


Circuit Breaker

Prevents repeated calls to a failing service.

States

  • Closed

  • Open

  • Half-Open

In .NET, commonly implemented using Polly.


S3 Bucket (AWS)

Amazon S3 is an object storage service.

Uses

  • File storage

  • Image storage

  • Document storage

  • Static website hosting

  • Backups

  • Log storage

Features

  • High durability (11 9's)

  • Versioning

  • Lifecycle policies

  • Encryption

  • Cross-region replication

-------------------------------------------------------------------------------------------------------

These are the most frequently asked interview topics for a Senior .NET Developer (10+ years). Below are concise yet interview-ready explanations.


1. Azure Functions

What is Azure Functions?

Azure Functions is a serverless compute service that lets you execute code in response to events without managing servers.

Key Features

  • Serverless

  • Auto Scaling

  • Pay only for execution

  • Event-driven

  • Supports C#, Java, Python, Node.js


Types of Triggers

TriggerUse Case
HTTP TriggerREST APIs
Timer TriggerScheduled jobs
Queue TriggerProcess Azure Queue messages
Service Bus TriggerProcess messages from Azure Service Bus
Blob TriggerProcess uploaded files
Event Hub TriggerProcess streaming data
Event Grid TriggerReact to Azure events
Cosmos DB TriggerReact to database changes

Bindings

Bindings reduce boilerplate code.

Input Binding

Reads data automatically.

[BlobInput("images/{name}")]

Output Binding

Writes data automatically.

[BlobOutput("output/{name}")]

Hosting Plans

  • Consumption Plan

  • Flex Consumption Plan

  • Premium Plan

  • Dedicated (App Service) Plan


Interview Question

Q: Why Azure Functions?

Answer:

  • No server management

  • Auto scaling

  • Cost-effective

  • Event-driven

  • Fast development


2. Application Insights

Application Insights is Azure Monitor's APM (Application Performance Monitoring) solution.

It monitors

  • Requests

  • Exceptions

  • Dependencies

  • Performance

  • Availability

  • User behavior


What does it capture?

  • API execution time

  • SQL execution

  • HTTP calls

  • Exceptions

  • Memory usage

  • CPU

  • Availability tests


Sample Logging

_logger.LogInformation("Order Created");

_logger.LogWarning("Retrying");

_logger.LogError(ex, "Payment Failed");

Custom Events

telemetryClient.TrackEvent("PaymentSuccess");

Interview Question

How do you monitor production applications?

Answer:

  • Application Insights

  • Azure Monitor

  • Alerts

  • Dashboards

  • Live Metrics


3. Logging

Logging records application activity for diagnostics and monitoring.


Log Levels

LevelPurpose
TraceDetailed diagnostics
DebugDevelopment
InformationNormal operations
WarningUnexpected but recoverable
ErrorFailed operations
CriticalApplication crash

Best Practices

  • Structured logging

  • Correlation IDs

  • Avoid logging secrets

  • Log exceptions with stack trace

  • Centralize logs


Example

_logger.LogInformation("Order {OrderId} Created", orderId);

4. Exception Handling

Purpose

Handle runtime errors gracefully.


Types

  • Try Catch

  • Finally

  • Global Exception Middleware

  • Exception Filters


Example

try
{
}
catch(Exception ex)
{
    _logger.LogError(ex,"Error");
}

Global Exception Middleware

Client

↓

Middleware

↓

Exception

↓

Log

↓

Return JSON Error

Benefits

  • Centralized handling

  • Consistent responses

  • Logging

  • Better security


5. Saga Pattern

Purpose

Manages distributed transactions in Microservices.


Instead of

One Transaction

Use

Local Transaction

↓

Next Service

↓

Next Service

↓

Compensating Transaction

Types

  • Choreography

  • Orchestration


Compensation Example

Payment Success

Inventory Reserved

Shipping Failed

Refund Payment

Release Inventory

Cancel Order


6. .NET Core Middleware

Middleware is software that handles HTTP requests and responses in the ASP.NET Core pipeline.


Pipeline

Request

↓

Authentication

↓

Authorization

↓

Routing

↓

Custom Middleware

↓

Controller

↓

Response

Common Middleware

  • Authentication

  • Authorization

  • Routing

  • CORS

  • Static Files

  • Exception Handling

  • HTTPS Redirection

  • Swagger


Custom Middleware

public async Task Invoke(HttpContext context)
{
    await _next(context);
}

Middleware Order

Exception

↓

HTTPS

↓

Static Files

↓

Routing

↓

Authentication

↓

Authorization

↓

Endpoints

7. C# Advanced Topics

Delegates

Stores method references.

delegate void Notify();

Events

Publisher/Subscriber pattern.


Lambda Expressions

x => x.Id

LINQ

Query collections.

employees.Where(x=>x.Salary>50000);

Async Await

Improves scalability.

await service.GetDataAsync();

Task Parallel Library

Parallel execution.


Reflection

Inspect types at runtime.


Generics

Reusable type-safe classes.


Extension Methods

Add methods without modifying classes.


Records

Immutable reference types.


Pattern Matching

switch
is
when

Nullable Reference Types

Avoid NullReferenceException.


Dependency Injection

Constructor Injection


Memory Management

  • Stack

  • Heap

  • Garbage Collection


IDisposable

Releases unmanaged resources.


Span

High-performance memory access.


Yield

Lazy iteration.


8. OOP

Four Pillars

Encapsulation

Hide internal data.


Abstraction

Show only required functionality.


Inheritance

Reuse code.


Polymorphism

Same method, different behavior.

Compile Time

Method Overloading

Runtime

Method Overriding

9. SOLID Principles

S

Single Responsibility Principle

One class → One responsibility


O

Open Closed Principle

Open for Extension

Closed for Modification


L

Liskov Substitution Principle

Derived class should replace base class without changing behavior.


I

Interface Segregation Principle

Small interfaces are better than large ones.


D

Dependency Inversion Principle

Depend on abstractions, not concrete implementations.


Common Interview Questions

QuestionExpected Answer
Difference between Azure Function and Web APIAzure Functions are event-driven and serverless; Web APIs are continuously hosted and ideal for long-running REST services.
What is Middleware?Software that processes HTTP requests and responses in the ASP.NET Core pipeline.
Explain Application Insights.Azure service for monitoring requests, dependencies, exceptions, performance, and availability.
How do you handle exceptions globally?Use custom exception-handling middleware to log errors and return standardized error responses.
Difference between Logging and Application Insights?Logging records application events, while Application Insights collects logs plus telemetry such as requests, dependencies, performance metrics, and exceptions.
Explain Saga Pattern.Coordinates distributed transactions across microservices using local transactions and compensating actions instead of a single distributed transaction.
Explain SOLID.Five object-oriented design principles that improve maintainability, extensibility, and testability.
What are advanced C# features?Delegates, events, LINQ, async/await, generics, reflection, extension methods, records, pattern matching, nullable reference types, Span, and dependency injection.

1. How did you implement Global Exception Handling using Custom Middleware?

Interview Answer

"In my ASP.NET Core applications, I implemented a custom Global Exception Handling Middleware to centralize exception handling. Instead of writing try-catch blocks in every controller or service, all unhandled exceptions are captured by the middleware. It logs the exception details using ILogger and Application Insights, maps different exception types to appropriate HTTP status codes, and returns a standardized JSON error response. This ensures consistent error handling, better logging, and avoids exposing sensitive exception details to clients."

Request Flow

Client Request
      │
      ▼
Middleware Pipeline
      │
      ▼
Custom Exception Middleware
      │
      ▼
Controller
      │
      ▼
Service
      │
      ▼
Database

If an exception occurs:

Exception
      │
      ▼
Middleware catches Exception
      │
      ├── Log to Application Insights
      ├── Log using ILogger
      ├── Return HTTP Status Code
      └── Return Standard JSON Response

Sample Response

{
  "success": false,
  "message": "Unexpected error occurred.",
  "statusCode": 500
}

Benefits

  • Centralized exception handling

  • Clean controllers

  • Consistent API responses

  • Better monitoring

  • Improved security (no stack trace exposed)


2. How did you use Azure Functions with Service Bus, Blob Storage, and Timer Triggers?

Interview Answer

"In one of my projects, we used Azure Functions for event-driven background processing. HTTP APIs accepted user requests and published messages to Azure Service Bus. A Service Bus-triggered Azure Function processed those messages asynchronously. For file uploads, we used Blob Storage triggers to process files automatically after they were uploaded. We also used Timer Trigger Functions for scheduled jobs such as report generation, cleanup tasks, and sending reminder emails."


Architecture

Client
   │
   ▼
Web API
   │
Publish Message
   ▼
Azure Service Bus
   │
   ▼
Azure Function
   │
Business Logic
   ▼
Azure SQL

Blob Trigger Example

Upload File
     │
Azure Blob Storage
     │
Blob Trigger Function
     │
Read File
     │
Process Data
     │
Save to Database

Timer Trigger Example

Runs automatically.

Every Night 2 AM

↓

Azure Function

↓

Generate Reports

↓

Send Email

↓

Cleanup Old Data

Benefits

  • Auto Scaling

  • Pay per execution

  • Decoupled architecture

  • Event-driven processing

  • Reduced API response time


3. How did you monitor Production using Application Insights?

Interview Answer

"We integrated Application Insights into all APIs and Azure Functions. It automatically captured request execution time, dependency calls, SQL queries, failed requests, exceptions, and performance metrics. We also logged custom business events and configured Azure Monitor alerts to notify the support team through email or Teams whenever exception counts or response times exceeded predefined thresholds."


Monitored Items

  • API Requests

  • SQL Queries

  • HTTP Calls

  • Azure Service Bus Calls

  • Exceptions

  • CPU

  • Memory

  • Availability Tests


Custom Logging

_logger.LogInformation("Order Created");

telemetryClient.TrackEvent("OrderPlaced");

Alerts

Examples:

  • Response Time > 3 Seconds

  • Exception Count > 10

  • Failed Requests > 5%

  • CPU > 80%

  • Availability Test Failed


Dashboard

API

↓

Application Insights

↓

Azure Monitor

↓

Alerts

↓

Email / Teams Notification

4. How did you design Microservices using Saga Pattern?

Interview Answer

"We implemented the Saga Pattern using Azure Service Bus to manage distributed transactions across microservices. Each service owned its own database and executed local transactions. Instead of distributed transactions, services communicated through events. If any step failed, compensating transactions were triggered to maintain data consistency."


Example

Customer Places Order

Order Service
      │
Create Order
      ▼
Publish OrderCreated Event

Payment Service

Charge Payment

Inventory Service

Reserve Stock

Shipping Service

Create Shipment

If Shipping Fails

Shipping Failed
      │
      ▼
Publish Failure Event
      │
      ▼
Inventory Release
      │
Refund Payment
      │
Cancel Order

Messaging

We used

  • Azure Service Bus Topics

  • Queues

  • Dead Letter Queue

  • Retry Policy


Benefits

  • Loose Coupling

  • Scalability

  • Event-driven

  • Eventual Consistency

  • Better fault tolerance


5. How did you apply SOLID Principles and Dependency Injection?

Interview Answer

"While designing services, we followed SOLID principles to keep the code modular, testable, and maintainable. Business logic was separated into service classes, repositories handled data access, interfaces were used for abstractions, and dependencies were injected through the built-in Dependency Injection container."


Example

Instead of

OrderService

↓

new PaymentService()

We used

OrderService

↓

IPaymentService

↓

PaymentService

Constructor Injection

public OrderService(IPaymentService paymentService)
{
    _paymentService = paymentService;
}

SOLID Used

Single Responsibility

Each class has one responsibility.

Example

OrderService

Repository

EmailService

NotificationService

Open Closed

Added new payment methods without changing existing code.


Liskov

Any payment provider could replace another.


Interface Segregation

Created small interfaces.

IEmailService

ISMSService

IPaymentService

Dependency Inversion

Depended on interfaces instead of concrete classes.


Benefits

  • Easy Testing

  • Mocking

  • Maintainability

  • Loose Coupling

  • Better Readability


6. How did you optimize Performance?

Interview Answer

"We optimized performance at multiple levels. Database queries were tuned with proper indexing and optimized LINQ queries. Asynchronous programming using async/await improved scalability by preventing thread blocking. Frequently accessed data was cached using Azure Cache for Redis. We monitored performance using Application Insights and optimized slow SQL queries and API response times."


Optimizations

Async Await

Instead of

var data = repository.Get();

Used

var data = await repository.GetAsync();

Benefits

  • Non-blocking

  • Better scalability

  • More concurrent requests


LINQ Optimization

Avoid

context.Users.ToList().Where(x=>x.IsActive);

Better

context.Users.Where(x=>x.IsActive).ToList();

Reason

Filtering happens in SQL instead of memory.


Projection

Instead of

context.Users.ToList();

Use

context.Users.Select(x=>new UserDto())

Only required columns are fetched.


Indexing

Added indexes on

  • CustomerId

  • OrderId

  • CreatedDate

  • Status

Reduced query time significantly.


Redis Cache

Frequently used data

  • Product Catalog

  • Master Data

  • Configuration

Stored in Redis.

Benefits

  • Faster response

  • Reduced DB load


Profiling

Used

  • Application Insights

  • SQL Execution Plans

  • EF Core Logging

  • Azure Monitor

Found

  • Slow SQL Queries

  • Long-running APIs

  • Memory usage

  • Deadlocks

  • Dependency failures


Final Interview Summary (2-Minute Answer)

"In my recent projects, I developed ASP.NET Core microservices hosted on Azure. I implemented global exception handling using custom middleware, which centralized logging through ILogger and Application Insights while returning standardized error responses. We used Azure Functions with Service Bus triggers for asynchronous message processing, Blob triggers for file processing, and Timer triggers for scheduled jobs. Production systems were monitored with Application Insights and Azure Monitor, where we tracked requests, dependencies, exceptions, and configured alerts for failures and performance thresholds. For distributed workflows like order processing, we implemented the Saga pattern using Azure Service Bus, allowing each microservice to manage its own database and use compensating transactions for failures. Throughout the application, we followed SOLID principles and dependency injection to keep the code modular, loosely coupled, and easy to test. To improve performance, we used async/await for non-blocking operations, optimized LINQ queries to execute filtering in SQL, added database indexes, cached frequently accessed data with Redis, and continuously profiled APIs and database queries using Application Insights and SQL execution plans."

Q) Why is DDD used with Microservices?

DDD helps identify bounded contexts, and each bounded context can become an independent microservice. This keeps services loosely coupled, with clear ownership of business logic and data.


Q) How have you used DDD in your projects?

"In our .NET Core microservices application, we used DDD to organize business logic into domain entities, aggregates, and domain services. Each microservice represented a bounded context—for example, Order, Inventory, and Payment. The Order aggregate enforced business rules such as preventing orders without items. Repositories handled persistence using EF Core, while domain events were published through Azure Service Bus to notify other microservices. This approach improved maintainability, testing, and scalability by keeping business logic centralized and services loosely coupled."


Friday, 3 July 2026

IQS

"In my current project, we use several Azure services:

  • Azure App Service – to host ASP.NET Core Web APIs.
  • Azure Functions – for event-driven and background processing.
  • Azure Blob Storage – to store files, documents, and images.
  • Azure SQL Database – as the primary relational database.
  • Azure Key Vault – to securely store secrets, connection strings, and certificates.
  • Azure Service Bus – for asynchronous communication between microservices.
  • Azure DevOps – for source control, CI/CD pipelines, work item tracking, and releases.
  • Application Insights – to monitor application performance, logs, exceptions, and telemetry.
  • Azure Monitor – for health monitoring and alerts."

If they ask which services you worked on directly, you can say:

"I have hands-on experience with Azure App Service, Azure Functions, Azure DevOps, Azure Blob Storage, Key Vault, and Application Insights. I also work with Azure SQL Database and integrate with Azure Service Bus in our microservices environment."


".NET Framework is the older Microsoft framework that primarily runs on Windows and is mainly used for maintaining legacy applications like ASP.NET Web Forms, WCF, and Windows desktop applications.

.NET Core (now unified as .NET 5/6/7/8+) is a modern, cross-platform framework that runs on Windows, Linux, and macOS. It's designed for high performance, cloud-native applications, microservices, REST APIs, and containerized deployments."

Key advantages of .NET Core over .NET Framework

  • Cross-platform – Runs on Windows, Linux, and macOS.
  • Better performance – Faster runtime and improved memory management.
  • Built-in Dependency Injection – No need for third-party DI frameworks.
  • High scalability – Ideal for cloud and microservices.
  • Cross-platform CLI – Easy to build and deploy using the dotnet CLI.
  • Side-by-side versioning – Multiple .NET versions can coexist on the same machine.
  • Container support – Excellent support for Docker and Kubernetes.
  • Lightweight and modular – Only required packages are included.
  • Active development – Microsoft continues to enhance modern .NET, while .NET Framework receives mainly maintenance updates.
ASP.net core request pipeline.
Client
   ↓
Kestrel Web Server
   ↓
Middleware Pipeline
   ↓
Routing
   ↓
Authentication
   ↓
Authorization
   ↓
Controller / Minimal API
   ↓
Business Logic
   ↓
Database
   ↓
Response

Explain each middleware

  • Exception Handling – Catches unhandled exceptions.
  • HTTPS Redirection – Redirects HTTP requests to HTTPS.
  • Static Files – Serves CSS, JavaScript, and images.
  • Routing – Matches the incoming URL to an endpoint.
  • Authentication – Verifies the user's identity (e.g., JWT).
  • Authorization – Checks whether the authenticated user has permission.
  • MapControllers – Invokes the appropriate controller action.

Code FirstDatabase First
Start with C# classesStart with an existing database
Database created from codeCode generated from the database
Uses EF MigrationsRegenerate models when the database changes
Best for new projectsBest for legacy/existing databases

 

How do you improve entity framework performance? Entity framework performance.

In my current project, we mainly improve EF Core performance by using AsNoTracking() for read-only operations, selecting only required fields, adding proper indexes, using async queries, avoiding the N+1 problem, and implementing pagination for large datasets.


How do you take care of web API?

In my current project, we secure our APIs using JWT authentication, validate all incoming requests, use global exception handling and logging, optimize database queries with EF Core, document APIs using Swagger, deploy over HTTPS, and monitor performance with Application Insights. These practices help us build secure, reliable, and scalable Web APIs


What is Domain-Driven Design (DDD)?

Domain-Driven Design (DDD) is a software design approach where the application is modeled around the business domain rather than the database or technical implementation. The main goal is to keep business rules and domain logic at the center of the application

Core concepts of DDD

  • Domain – The business problem being solved (e.g., Banking, E-commerce).
  • Entity – An object with a unique identity (e.g., Customer, Order).
  • Value Object – An object without identity, defined by its values (e.g., Address, Money).
  • Aggregate – A group of related entities treated as a single unit.
  • Aggregate Root – The main entity through which the aggregate is accessed (e.g., Order).
  • Repository – Handles data access for aggregates.
  • Domain Service – Contains business logic that doesn't belong to a single entity.

Example

"In an e-commerce application, an Order is the Aggregate Root. It contains multiple OrderItems. Instead of allowing direct changes to OrderItems, all updates go through the Order entity. This ensures business rules, such as validating stock or calculating the total amount, are always enforced."

Benefits

  • Keeps business logic separate from infrastructure.
  • Easier to maintain and test.
  • Better suited for large, complex business applications.
  • Works well with microservices and clean architecture.

Friday, 19 June 2026

IQS

This summary is not available. Please click here to view the post.

.NET Scenario-Based IQ

 

1. Suppose we have three middlewares in the pipeline. If an exception occurs in the second middleware, how will the request/response flow behave? Will the third middleware ever get executed?

Answer:

Middleware execution follows a pipeline pattern.

Middleware1 → Middleware2 → Middleware3 → Controller

If Middleware2 throws an exception:

  • Execution immediately stops.

  • Middleware3 will not execute.

  • The exception propagates back through the pipeline.

  • If an Exception Handling Middleware is configured earlier in the pipeline, it catches the exception and returns an error response.

Example:

app.UseExceptionHandler("/Error");
app.UseMiddleware<Middleware1>();
app.UseMiddleware<Middleware2>();
app.UseMiddleware<Middleware3>();

Interview Answer:

If Middleware2 throws an exception and does not handle it, Middleware3 will never execute. The exception travels back up the pipeline and can be handled by a global exception middleware configured earlier in the request pipeline.


2. An API is consumed by two customers: one expects JSON and another expects XML. How can we support both without creating separate endpoints?

Answer:

Use Content Negotiation.

Configure both formatters:

builder.Services.AddControllers()
    .AddXmlSerializerFormatters();

Client Requests:

Accept: application/json

Returns JSON.

Accept: application/xml

Returns XML.

Controller:

[HttpGet]
public IActionResult GetEmployee()
{
    return Ok(employee);
}

Interview Answer:

ASP.NET Core supports content negotiation. Based on the Accept header, the same endpoint can return JSON or XML without creating multiple APIs.


3. Middleware order matters — why? What happens if arranged incorrectly?

Answer:

Middleware executes in the order registered.

Correct Order:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Wrong Order:

app.UseAuthorization();
app.UseAuthentication();

Problem:

  • Authorization executes before user identity is established.

  • User becomes unauthorized.

Other examples:

  • CORS after endpoints → CORS fails.

  • Exception middleware at bottom → Exceptions not captured.

  • Static files after routing → Files may not be served.

Interview Answer:

Middleware order is critical because each middleware depends on work done by previous middleware. Incorrect ordering can cause authentication failures, routing issues, CORS problems, and unhandled exceptions.


Angular Scenario-Based Questions & Answers

1. If a component is declared in two different NgModules, what happens?

Answer:

Angular throws a compilation error.

Example:

@NgModule({
  declarations: [EmployeeComponent]
})
export class ModuleA {}
@NgModule({
  declarations: [EmployeeComponent]
})
export class ModuleB {}

Error:

Type EmployeeComponent is part of the declarations of 2 modules.

Solution:

Declare the component in only one module and export it.

@NgModule({
  declarations: [EmployeeComponent],
  exports: [EmployeeComponent]
})
export class SharedModule {}

Interview Answer:

Angular does not allow a component to be declared in multiple modules. The application fails to compile with a duplicate declaration error.


2. Service A depends on Service B, and Service B depends on Service A. What happens?

Answer:

This creates a circular dependency.

Example:

@Injectable()
export class ServiceA {
  constructor(private serviceB: ServiceB) {}
}
@Injectable()
export class ServiceB {
  constructor(private serviceA: ServiceA) {}
}

Angular DI Error:

Circular dependency detected

Solutions:

  • Refactor responsibilities.

  • Introduce a third service.

  • Use an event-based pattern (RxJS Subject).

Interview Answer:

Angular's dependency injection container detects circular dependencies and throws an error because it cannot determine which service should be instantiated first.


SQL Scenario-Based Questions & Answers

1. A column contains values 1, 2, 3 and NULL. How does ORDER BY treat NULL values?

Assume:

Value
-----
1
2
3
NULL

ORDER BY ASC

SELECT Value
FROM TestTable
ORDER BY Value ASC;

Result in SQL Server:

NULL
1
2
3

ORDER BY DESC

SELECT Value
FROM TestTable
ORDER BY Value DESC;

Result:

3
2
1
NULL

SQL Server Rule:

  • NULL is treated as the lowest value.

Interview Answer:

In SQL Server, NULLs appear first in ascending order and last in descending order because NULL is considered lower than any numeric value.


2. What happens if we try to insert values directly into an Identity column?

Table:

CREATE TABLE Employee
(
    Id INT IDENTITY(1,1),
    Name VARCHAR(50)
)

Query:

INSERT INTO Employee(Id, Name)
VALUES (100, 'John');

Error:

Cannot insert explicit value for identity column
when IDENTITY_INSERT is set to OFF.

To Insert Explicitly

SET IDENTITY_INSERT Employee ON;

INSERT INTO Employee(Id, Name)
VALUES (100, 'John');

SET IDENTITY_INSERT Employee OFF;

Important Notes

  • Only one table per session can have IDENTITY_INSERT ON.

  • Generally used during data migration.

Interview Answer:

SQL Server does not allow manual insertion into an Identity column by default. To insert explicit values, IDENTITY_INSERT must be enabled temporarily.


Additional Follow-up Interview Questions

.NET

  1. Difference between Use, Run, and Map middleware?

  2. What happens if next() is not called in middleware?

  3. How does global exception handling work in ASP.NET Core?

Angular

  1. Difference between lazy loading and eager loading?

  2. What is OnPush change detection?

  3. Difference between Subject, BehaviorSubject, and ReplaySubject?

SQL

  1. Difference between DELETE, TRUNCATE, and DROP?

  2. Clustered vs Non-Clustered Index?

  3. ROW_NUMBER(), RANK(), and DENSE_RANK() differences?

These are commonly asked in Senior .NET + Angular + SQL interviews (8–12+ years experience).