Friday, 17 July 2026

Angular


Section 1: Angular Basics (1–15)

1. What is Angular?

Answer:
Angular is a TypeScript-based, open-source front-end framework developed by Google for building Single Page Applications (SPAs). It follows a component-based architecture and provides features like dependency injection, routing, forms, HTTP communication, and RxJS for reactive programming.


2. What are the features of Angular?

Answer:

  • Component-based architecture

  • Dependency Injection (DI)

  • Two-way Data Binding

  • Routing

  • Lazy Loading

  • Reactive Forms

  • RxJS Observables

  • Directives

  • Pipes

  • Built-in Testing Support

  • TypeScript support

  • Ahead-of-Time (AOT) Compilation


3. What is SPA?

Answer:

SPA (Single Page Application) loads a single HTML page and dynamically updates content without reloading the entire page.

Examples:

  • Gmail

  • Facebook

  • LinkedIn

Advantages:

  • Fast navigation

  • Better user experience

  • Reduced server load


4. Difference between AngularJS and Angular?

AngularJSAngular
JavaScriptTypeScript
MVCComponent-based
ControllersComponents
Poor PerformanceBetter Performance
No Mobile SupportMobile Friendly
No Lazy LoadingSupports Lazy Loading

5. Why Angular uses TypeScript?

Answer:

TypeScript provides:

  • Strong Typing

  • Interfaces

  • Classes

  • Better IntelliSense

  • Easier Debugging

  • Better Code Maintainability


6. What is a Component?

Answer:

A Component controls a specific portion of the UI.

Example:

EmployeeComponent

employee.component.ts

employee.component.html

employee.component.css

7. What is Module?

Answer:

A Module groups related components, directives, services, and pipes.

Example:

AppModule

8. What is AppModule?

Answer:

AppModule is the root module where Angular application starts.


9. What is CLI?

Answer:

Angular CLI is a command-line tool used to create and manage Angular applications.

Examples:

ng new ProjectName

ng serve

ng build

ng test

10. Difference between Component and Module?

ComponentModule
Controls UIGroups Components
HTML + TS + CSSCollection
ReusableRoot Configuration

11. What is Metadata?

Answer:

Metadata tells Angular how to process a class.

Example:

@Component({
 selector:'app-home',
 templateUrl:'home.component.html'
})

12. What is Decorator?

Answer:

Decorators are special functions that add metadata.

Examples:

@Component

@NgModule

@Injectable

@Input

@Output

13. What is Bootstrapping?

Answer:

Bootstrapping is the process of loading the root Angular component during application startup.


14. What is main.ts?

Answer:

It is the application's entry point.

Flow:

main.ts

↓

AppModule

↓

AppComponent

15. Explain Angular Architecture.

Browser

↓

main.ts

↓

AppModule

↓

Components

↓

Services

↓

HttpClient

↓

.NET API

↓

Database

Section 2: Data Binding (16–22)

16. What is Data Binding?

Answer:

Data Binding synchronizes data between the component and the HTML template.


17. Types of Data Binding?

  1. Interpolation

  2. Property Binding

  3. Event Binding

  4. Two-way Binding


18. What is Interpolation?

{{employeeName}}

Displays component data in HTML.


19. Property Binding?

<img [src]="image">

20. Event Binding?

<button (click)="Save()">

21. Two-way Binding?

[(ngModel)]

Example:

<input [(ngModel)]="employee.name">

22. Difference between Property and Event Binding?

PropertyEvent
Component → ViewView → Component

Section 3: Directives (23–30)

23. What is Directive?

A Directive changes the appearance or behavior of DOM elements.


24. Types of Directives?

  • Component

  • Structural

  • Attribute


25. What is *ngIf?

Shows or hides an element.

<div *ngIf="isAdmin">

26. What is *ngFor?

Displays a list.

<li *ngFor="let emp of employees">

27. What is ngSwitch?

Displays content based on conditions.


28. What is ngClass?

Adds dynamic CSS classes.


29. What is ngStyle?

Applies dynamic styles.


30. Difference between ngIf and hidden?

ngIfhidden
Removes DOMHides Element

Section 4: Components (31–40)

31. Lifecycle Hooks?

  • constructor

  • ngOnChanges

  • ngOnInit

  • ngDoCheck

  • ngAfterContentInit

  • ngAfterViewInit

  • ngOnDestroy


32. Difference between constructor and ngOnInit?

ConstructorngOnInit
Dependency InjectionInitialization
Runs firstRuns after constructor

33. What is ngOnDestroy?

Used to clean up resources and unsubscribe from Observables to prevent memory leaks.


34. Parent to Child Communication?

@Input()

35. Child to Parent Communication?

@Output()

EventEmitter

36. ViewChild?

Access child component or DOM elements.


37. ContentChild?

Access projected content using <ng-content>.


38. Change Detection?

Angular checks the component tree for data changes and updates the view.


39. OnPush Change Detection?

Improves performance by checking changes only when inputs or Observable references change.


40. Standalone Components?

Angular 14+ allows components without NgModule.


Section 5: Services & Dependency Injection (41–50)

41. What is Service?

A Service contains reusable business logic and API communication.


42. Why use Services?

  • Code reuse

  • Separation of concerns

  • API calls

  • Shared state


43. What is Dependency Injection?

DI automatically provides instances of services to components.


44. What is @Injectable?

Marks a class as available for DI.


45. Singleton Service?

A service provided at the root level; only one instance exists across the application.


46. How to inject a Service?

constructor(private employeeService: EmployeeService) {}

47. What is provider?

Registers a service with Angular's injector.


48. Service Scope?

  • Root

  • Module

  • Component


49. Difference between Component and Service?

ComponentService
UI LogicBusiness Logic

50. Why shouldn't API calls be in Components?

To keep components lightweight, reusable, and easier to test.


Section 6: HTTP & RxJS (51–65)

51. How do you call a .NET Web API?

Using Angular HttpClient.

this.http.get<Employee[]>('/api/employees');

52. What is HttpClient?

A built-in Angular service used to make HTTP requests.


53. Difference between GET and POST?

  • GET retrieves data.

  • POST creates new data.


54. Difference between PUT and PATCH?

  • PUT replaces the entire resource.

  • PATCH updates only specified fields.


55. What is an Observable?

An asynchronous data stream provided by RxJS.


56. Difference between Observable and Promise?

ObservablePromise
Multiple valuesSingle value
CancelableNot cancelable
LazyEager

57. What is subscribe()?

Used to receive data emitted by an Observable.


58. What is pipe()?

Allows chaining RxJS operators.


59. Common RxJS operators?

  • map

  • filter

  • tap

  • switchMap

  • mergeMap

  • concatMap

  • debounceTime

  • distinctUntilChanged

  • catchError

  • retry

  • finalize


60. What is Subject?

Acts as both an Observable and an Observer, allowing multicasting.


61. What is BehaviorSubject?

A Subject that stores the latest value and immediately emits it to new subscribers.


62. When would you use BehaviorSubject?

For sharing application state such as logged-in user or theme.


63. What is switchMap?

Switches to a new Observable and cancels the previous one—useful for search boxes.


64. What is debounceTime()?

Delays emissions to reduce frequent API calls during typing.


65. How do you handle HTTP errors?

Use catchError() in the service or an HTTP interceptor for centralized handling.


Section 7: Routing (66–75)

66. What is Routing in Angular?

Answer

Routing enables navigation between different components in a Single Page Application (SPA) without reloading the browser.

For example:

Dashboard
     ↓
Employees
     ↓
Employee Details
     ↓
Employee Edit

Angular uses the @angular/router package to manage routes.

Example:

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'employees', component: EmployeeComponent },
  { path: 'about', component: AboutComponent }
];

67. How do you configure Routes?

Answer

Routes are configured inside app-routing.module.ts.

const routes: Routes = [
  {
      path:'employees',
      component:EmployeeComponent
  },
  {
      path:'dashboard',
      component:DashboardComponent
  }
];

Import the routing module:

@NgModule({
 imports:[RouterModule.forRoot(routes)],
 exports:[RouterModule]
})

68. What is RouterOutlet?

Answer

<router-outlet> is a placeholder where Angular loads the routed component.

Example

<router-outlet></router-outlet>

Without router-outlet, Angular cannot display routed pages.


69. Difference between RouterLink and href?

RouterLinkhref
Angular navigationBrowser navigation
No page reloadFull page reload
FasterSlower
RecommendedAvoid inside Angular

Example

<a routerLink="/employees">Employees</a>

70. What is Lazy Loading?

Answer

Lazy Loading loads feature modules only when the user navigates to them instead of loading the entire application at startup.

Benefits:

  • Faster startup

  • Better performance

  • Smaller bundle size

Example

{
 path:'admin',
 loadChildren:() =>
 import('./admin/admin.module')
 .then(m=>m.AdminModule)
}

71. Advantages of Lazy Loading?

Answer

  • Faster initial loading

  • Reduced JavaScript bundle size

  • Better scalability

  • Lower memory usage

  • Improved user experience


72. What are Route Parameters?

Answer

Route parameters pass dynamic values in the URL.

Example

employees/101
employees/102

Configuration

{
 path:'employee/:id',
 component:EmployeeDetailComponent
}

Access

this.route.snapshot.params['id'];

73. What is ActivatedRoute?

Answer

ActivatedRoute provides access to route information such as:

  • Route parameters

  • Query parameters

  • URL segments

  • Route data

Example

constructor(private route:ActivatedRoute){}

ngOnInit(){
   let id=this.route.snapshot.paramMap.get('id');
}

74. What is Route Resolver?

Answer

A Resolver loads data before navigating to a component.

Flow

Navigation
      ↓
Resolver
      ↓
API
      ↓
Component Opens

Benefits

  • Prevents empty screens

  • Improves user experience

  • Ensures data is available before rendering


75. What are Route Guards?

Answer

Route Guards protect routes by deciding whether navigation is allowed.

Types:

  • CanActivate

  • CanDeactivate

  • Resolve

  • CanLoad

  • CanMatch

Example

canActivate():boolean{

return this.authService.isLoggedIn();

}

Real-world example

Only authenticated users can access the Dashboard.


Section 8: Forms (76–85)

76. What are Template-driven Forms?

Answer

Template-driven forms use Angular directives in the HTML template and rely on ngModel.

Example

<input [(ngModel)]="employee.name">

Best for:

  • Small forms

  • Simple validation


77. What are Reactive Forms?

Answer

Reactive Forms define form controls in the TypeScript class, offering better scalability and testability.

Example

this.employeeForm=this.fb.group({

name:['',Validators.required],

email:['']

});

Advantages

  • Better validation

  • Dynamic forms

  • Unit testing

  • Complex business rules


78. What is FormGroup?

Answer

A FormGroup groups multiple form controls into a single object.

Example

this.form=new FormGroup({

name:new FormControl(),

email:new FormControl()

});

79. What is FormControl?

Answer

A FormControl represents a single input element.

Example

new FormControl('')

80. What is FormBuilder?

Answer

FormBuilder simplifies creating Reactive Forms.

Instead of

new FormGroup()

Use

this.fb.group({

name:[''],

email:['']

});

81. What are Validators?

Answer

Validators validate user input.

Common validators:

  • required

  • email

  • minlength

  • maxlength

  • pattern

Example

Validators.required

82. What is a Custom Validator?

Answer

Custom validators validate business-specific rules.

Example

export function ageValidator(control:AbstractControl){

if(control.value<18)

return {invalidAge:true};

return null;

}

83. What is FormArray?

Answer

FormArray manages a dynamic collection of controls.

Example

Employee

Phone 1

Phone 2

Phone 3

Useful when the number of controls changes dynamically.


84. What are Dynamic Forms?

Answer

Dynamic Forms allow form fields to be generated at runtime based on configuration or API data.

Example

Registration forms where questions change based on user role.


85. How do you Disable or Enable Controls?

Example

this.form.controls['name'].disable();

this.form.controls['name'].enable();

Section 9: Security (86–92)

86. Explain JWT Authentication.

Answer

JWT (JSON Web Token) authenticates users securely.

Flow

Login

↓

.NET API

↓

JWT Token

↓

Angular Stores Token

↓

Interceptor

↓

Authorization Header

↓

API validates JWT

Header

Authorization: Bearer Token

87. What are Route Guards?

Route Guards prevent unauthorized access.

Example

User Logged In?

↓

Yes

↓

Dashboard

↓

No

↓

Login

88. What is an HTTP Interceptor?

Answer

An Interceptor modifies HTTP requests and responses globally.

Uses

  • Attach JWT

  • Logging

  • Error handling

  • Request modification

Example

request.clone({

setHeaders:{

Authorization:'Bearer '+token

}

});

89. What is XSS?

Answer

Cross-Site Scripting (XSS) is an attack where malicious scripts are injected into web pages.

Angular prevents XSS by automatically sanitizing template bindings.

Avoid using innerHTML with untrusted input.


90. What is DomSanitizer?

Answer

DomSanitizer safely displays trusted HTML, URLs, or resources.

Example

this.sanitizer.bypassSecurityTrustHtml(html);

Use it cautiously and only with trusted content.


91. What is CORS?

Answer

CORS (Cross-Origin Resource Sharing) allows a frontend hosted on one domain to access APIs on another domain.

Example

Angular

localhost:4200

.NET API

localhost:5001

Enable CORS in ASP.NET Core.


92. What is CSRF?

Answer

CSRF (Cross-Site Request Forgery) tricks a user's browser into sending unwanted authenticated requests.

Protection methods:

  • Anti-forgery tokens

  • SameSite cookies

  • Token validation

When using JWT in Authorization headers (instead of cookies), CSRF risk is generally much lower.


Section 10: Performance (93–100)

93. How does Lazy Loading improve performance?

Only the required modules are downloaded, reducing the application's initial bundle size and improving startup time.


94. What is trackBy?

trackBy helps Angular identify list items uniquely when using *ngFor, preventing unnecessary DOM updates.

Example

trackById(index:number,item:any){

return item.id;

}

95. What is OnPush Change Detection?

OnPush reduces unnecessary change detection cycles by checking components only when:

  • An @Input() reference changes

  • An event occurs

  • An Observable emits a new value

This improves performance in large applications.


96. Difference between Pure and Impure Pipes?

Pure PipeImpure Pipe
Executes only when input reference changesExecutes on every change detection cycle
Better performanceSlower
Default behaviorUse only when necessary

97. What is Virtual Scrolling?

Virtual Scrolling renders only the visible items instead of the entire list.

Example:

  • 100,000 records

  • Only ~20 visible records are rendered

This significantly improves rendering performance.


98. What is Tree Shaking?

Tree Shaking removes unused JavaScript code during the production build, reducing bundle size.


99. Difference between AOT and JIT?

AOTJIT
Compiles during buildCompiles in the browser
Faster startupSlower startup
Smaller bundleLarger bundle
Used in productionUsed during development

100. How do you optimize Angular applications?

Common techniques:

  • Lazy Loading

  • OnPush Change Detection

  • trackBy with *ngFor

  • Virtual Scrolling

  • Avoid unnecessary subscriptions

  • Unsubscribe in ngOnDestroy

  • Use the async pipe

  • Split feature modules

  • Optimize images and assets

  • Build with production configuration


Advanced Questions (101–115)

101. What are Angular Signals?

Signals, introduced in Angular 16, are a reactive state management primitive that automatically notifies Angular when state changes.

Example:

count = signal(0);

count.set(1);

count.update(v => v + 1);

Advantages:

  • Simpler state management

  • Fine-grained reactivity

  • Reduced change detection overhead


102. Signals vs Observables?

SignalsObservables
State managementAsynchronous streams
Synchronous readsAsync data/events
Simpler syntaxRich RxJS operators
Great for UI stateGreat for HTTP, WebSockets, events

103. What is NgRx?

NgRx is a Redux-inspired state management library for Angular.

Core concepts:

  • Store

  • Actions

  • Reducers

  • Effects

  • Selectors

Best suited for large enterprise applications with complex shared state.


104. What is State Management?

State Management is the process of storing and sharing application data consistently.

Options include:

  • Services + BehaviorSubject

  • Signals

  • NgRx

  • Component Store


105. What is Zone.js?

Zone.js patches asynchronous browser APIs (such as setTimeout, Promises, and DOM events) so Angular knows when asynchronous work completes and can trigger change detection automatically.


106. How does Angular Change Detection work?

Angular traverses the component tree and checks whether bound data has changed.

Strategies:

  • Default

  • OnPush

For better performance, use immutable data with OnPush.


107. Explain Dependency Injection hierarchy.

Angular resolves dependencies through a hierarchy of injectors.

Common scopes:

  • Root injector (application-wide singleton)

  • Feature module injector

  • Component injector

Angular searches from the nearest injector upward until it finds the requested service.


108. What are Standalone APIs?

Standalone APIs allow Angular applications to work without NgModule.

Example:

@Component({
  standalone: true,
  imports: [CommonModule]
})
export class EmployeeComponent {}

Benefits:

  • Less boilerplate

  • Easier lazy loading

  • Simpler application structure


109. What is Angular Universal?

Angular Universal enables Server-Side Rendering (SSR).

Benefits:

  • Faster first page load

  • Better SEO

  • Improved performance on slow devices


110. How do you optimize Angular performance in enterprise applications?

  • Lazy-load feature modules

  • Use OnPush

  • Implement trackBy

  • Use virtual scrolling

  • Cache API responses

  • Minimize unnecessary subscriptions

  • Use production builds (AOT)

  • Optimize images and assets

  • Split large components

  • Use Signals or efficient state management


111. What is a Microfrontend architecture?

Microfrontends split a large frontend into independently developed and deployed applications.

Benefits:

  • Independent deployments

  • Team autonomy

  • Easier scaling

  • Technology flexibility (where appropriate)


112. How do you implement Role-Based Authorization?

  1. User logs in.

  2. Backend returns a JWT containing roles/claims.

  3. Angular stores the token.

  4. Route Guards verify roles before navigation.

  5. Backend also validates the role for every protected API.

Never rely only on frontend checks; always enforce authorization on the server.


113. How do you securely store JWT tokens?

Recommended practices:

  • Prefer secure, HttpOnly cookies for high-security applications when architecture permits.

  • If using browser storage, understand the XSS risks and keep token lifetimes short.

  • Always use HTTPS.

  • Implement refresh tokens and token expiration.

  • Never hardcode secrets in the Angular application.


114. How do you integrate Angular with an ASP.NET Core Web API?

Flow:

Angular Component
        ↓
Angular Service (HttpClient)
        ↓
ASP.NET Core Web API
        ↓
Business Layer
        ↓
Entity Framework Core
        ↓
SQL Server

Use JWT authentication, centralized HTTP interceptors, proper error handling, and RESTful APIs.


115. Explain an end-to-end Login Flow using Angular, JWT, and ASP.NET Core.

Step 1: User enters credentials in Angular.

Step 2: Angular sends a POST request to the ASP.NET Core login API.

Step 3: The backend validates the credentials and generates a JWT containing user claims.

Step 4: Angular stores the token securely (based on your application's security approach).

Step 5: An HTTP Interceptor automatically adds the Authorization: Bearer <token> header to subsequent API requests.

Step 6: ASP.NET Core middleware validates the JWT before executing protected endpoints.

Step 7: Route Guards prevent unauthorized users from accessing protected pages.

Step 8: On token expiration, the application either redirects the user to log in again or uses a refresh-token mechanism if implemented.



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."