Friday, July 31, 2026

Azure DevOps

Microsoft Azure DevOps official documentation

Azure DevOps — Complete Guide for .NET Lead

1. What is Azure DevOps?

Azure DevOps is a set of services for planning, developing, testing, deploying, and monitoring software.

Think of a typical .NET project:

Developer
    |
    v
Write C# Code
    |
    v
Git Repository
    |
    v
Build
    |
    v
Unit Tests
    |
    v
Code Quality
    |
    v
Deploy to DEV
    |
    v
Testing
    |
    v
Deploy to QA
    |
    v
Deploy to Production
    |
    v
Azure Monitor / Application Insights

Azure DevOps helps automate this entire process.


2. Main Azure DevOps Services

You should remember these:

Azure DevOps
    |
    +-- Azure Repos
    |
    +-- Azure Pipelines
    |
    +-- Azure Boards
    |
    +-- Azure Test Plans
    |
    +-- Azure Artifacts

Easy way to remember

ServicePurpose
Azure ReposSource Code
Azure PipelinesCI/CD
Azure BoardsWork Management
Azure Test PlansTesting
Azure ArtifactsPackage Management

3. Real-Time Project

Let's take a real enterprise application:

Angular Frontend
       |
       v
ASP.NET Core Web API
       |
       +---- Azure SQL
       |
       +---- Azure Service Bus
       |
       +---- Azure Functions
       |
       +---- Azure Storage

Developers work on:

C#
Angular
SQL
Azure

Now imagine 10 developers working on the same project.

Azure DevOps provides the platform for:

Planning
   ↓
Coding
   ↓
Pull Request
   ↓
Review
   ↓
Build
   ↓
Unit Tests
   ↓
Security/Quality checks
   ↓
Deployment
   ↓
Monitoring

4. Azure Repos

Azure Repos provides Git repositories for source control.

Example:

MyCompany
   |
   +-- OrderManagement
   |
   +-- PaymentService
   |
   +-- InventoryService

You can use:

git clone
git pull
git push
git branch
git merge

just like other Git hosting platforms.


5. Typical Git Workflow

Suppose you are developing an Order API.

You shouldn't directly modify the production branch.

Instead:

main
 |
 +---- feature/order-api

Developer:

git checkout -b feature/order-api

Develop code:

OrderController.cs
OrderService.cs
OrderRepository.cs

Then:

git add .
git commit -m "Add order API"
git push origin feature/order-api

Then create:

Pull Request

6. Pull Request

The PR process is very important for a Lead.

Developer
    |
    v
Feature Branch
    |
    v
Pull Request
    |
    +---- Code Review
    +---- Build
    +---- Unit Tests
    +---- Quality Checks
    |
    v
Approve
    |
    v
Merge

A Lead should establish policies such as:

  • Minimum reviewers

  • Build validation

  • Linked work items

  • No direct pushes to main

  • Required checks

  • Branch naming conventions


7. Branching Strategy

For many enterprise projects:

main
 |
 +-- develop
      |
      +-- feature/order
      |
      +-- feature/payment
      |
      +-- bugfix/order

Another common approach is trunk-based development:

main
 |
 +-- short-lived feature branch
 |
 +-- short-lived feature branch
 |
 +-- short-lived feature branch

Lead-level point

Don't say:

"Git Flow is always the best."

Instead:

"I choose the branching strategy based on release frequency, team size, deployment model, and whether we use feature flags or continuous delivery."

That's a stronger architectural answer.


8. Azure Boards

Azure Boards is used to manage work.

Typical hierarchy:

Epic
  |
  +-- Feature
        |
        +-- User Story
              |
              +-- Task
              +-- Bug

Example:

Epic:
E-Commerce Platform

Feature:
Order Management

User Story:
As a customer, I want to place an order.

Tasks:
- Create Order API
- Create Order table
- Add validation
- Write unit tests
- Create Angular UI

9. Agile Sprint

Example:

Sprint 1
------------------------
Order API
Payment API
Login
Customer API

Azure Boards helps track:

To Do
   ↓
In Progress
   ↓
Code Review
   ↓
Testing
   ↓
Done

10. Azure Pipelines

This is probably the most important Azure DevOps feature for a .NET Lead.

Azure Pipelines automates:

Build
Test
Package
Deploy

This is called CI/CD.


11. What is CI?

Continuous Integration

Developers frequently merge code into the shared repository.

Every change triggers:

Git Push
   ↓
Pipeline
   ↓
Restore
   ↓
Build
   ↓
Unit Test
   ↓
Quality Checks

If build/test fails:

Pipeline FAILED

The developer fixes it before the change progresses.


12. What is CD?

Continuous Delivery/Deployment

After successful CI:

Build
   ↓
Test
   ↓
Deploy DEV
   ↓
Deploy QA
   ↓
Approval
   ↓
Deploy Production

13. Complete CI/CD Pipeline

For a .NET application:

                    Developer
                        |
                        v
                   Azure Repos
                        |
                        v
                   Pull Request
                        |
                        v
                 Build Validation
                        |
             +----------+----------+
             |                     |
             v                     v
         dotnet build         dotnet test
             |                     |
             +----------+----------+
                        |
                        v
                  Create Artifact
                        |
                        v
                     DEV
                        |
                        v
                  Integration Test
                        |
                        v
                     QA
                        |
                        v
                  Approval/Gate
                        |
                        v
                   Production
                        |
                        v
               Application Insights

This is a very strong diagram to explain during interviews.


14. Azure Pipeline YAML

A basic .NET pipeline can look like:

trigger:
- main

pool:
  vmImage: 'ubuntu-latest'

variables:
  buildConfiguration: 'Release'

steps:

- task: UseDotNet@2
  inputs:
    packageType: 'sdk'
    version: '9.x'

- script: dotnet restore
  displayName: 'Restore'

- script: dotnet build --configuration $(buildConfiguration) --no-restore
  displayName: 'Build'

- script: dotnet test --configuration $(buildConfiguration) --no-build
  displayName: 'Run Unit Tests'

- script: dotnet publish \
          --configuration $(buildConfiguration) \
          --output $(Build.ArtifactStagingDirectory)
  displayName: 'Publish'

- task: PublishBuildArtifacts@1
  inputs:
    pathToPublish: '$(Build.ArtifactStagingDirectory)'
    artifactName: 'drop'

The exact task versions and recommended YAML patterns can evolve, so use Microsoft's current task documentation when building a production pipeline.

Azure Pipelines documentation


15. Let's Understand the Pipeline

Step 1 — Trigger

trigger:
- main

Means:

Run the pipeline when changes are pushed to main.


Step 2 — Agent

pool:
  vmImage: 'ubuntu-latest'

Azure DevOps provides an agent to execute pipeline steps.

Conceptually:

Azure DevOps
     |
     v
Build Agent
     |
     +-- Restore
     +-- Build
     +-- Test
     +-- Publish

16. Restore

- script: dotnet restore

Restores NuGet dependencies.


17. Build

- script: dotnet build --configuration Release

Compiles the application.

If C# has errors:

Build FAILED

The deployment doesn't continue.


18. Unit Testing

- script: dotnet test

Suppose:

100 Tests
98 Passed
2 Failed

Pipeline:

FAILED

This prevents broken code from moving forward.


19. Publish

dotnet publish

Creates deployable output.

Conceptually:

Source Code
    ↓
Build
    ↓
Publish
    ↓
Artifact

20. What is an Artifact?

An artifact is the output produced by the build that can be used later by deployment stages.

Example:

Build
  |
  v
drop.zip

Then:

drop.zip
   |
   +---- DEV
   |
   +---- QA
   |
   +---- PROD

A key Lead-level principle is:

Build once, deploy the same artifact through environments.

You don't want to rebuild differently for production.


21. Multi-Stage Pipeline

A better enterprise pipeline:

stages:

- stage: Build
  jobs:
  - job: Build
    steps:
    - script: dotnet restore

    - script: dotnet build --configuration Release

    - script: dotnet test --configuration Release

    - script: dotnet publish \
              --configuration Release \
              --output $(Build.ArtifactStagingDirectory)

    - publish: $(Build.ArtifactStagingDirectory)
      artifact: drop


- stage: DeployDev
  dependsOn: Build
  jobs:
  - deployment: Deploy
    environment: Dev
    strategy:
      runOnce:
        deploy:
          steps:
          - download: current
            artifact: drop


- stage: DeployQA
  dependsOn: DeployDev
  jobs:
  - deployment: Deploy
    environment: QA
    strategy:
      runOnce:
        deploy:
          steps:
          - download: current
            artifact: drop

This demonstrates the concept:

Build
 ↓
Artifact
 ↓
DEV
 ↓
QA
 ↓
PROD

22. Environments

Azure DevOps environments represent deployment targets such as:

DEV
QA
UAT
PROD

Example:

Build
 |
 v
DEV
 |
 v
QA
 |
 v
UAT
 |
 v
PROD

23. Production Approval

Suppose your pipeline reaches:

Deploy Production

You can require an approval:

Pipeline
   |
   v
Production
   |
Approval required
   |
   v
Manager/Lead approves
   |
   v
Deployment

This is important for controlled enterprise releases.


24. Variable Groups

Don't hard-code environment configuration into YAML.

Bad:

SqlConnectionString: "Server=..."

Instead, use variables/configuration mechanisms.

Example:

Variable Group
      |
      +-- Dev
      +-- QA
      +-- Prod

Then:

DEV → Dev configuration
QA  → QA configuration
PROD → Prod configuration

For sensitive secrets, prefer Azure Key Vault integration rather than plain pipeline variables wherever appropriate.


25. Azure Key Vault + Azure DevOps

A strong enterprise architecture:

Azure DevOps Pipeline
       |
       v
Azure Key Vault
       |
       +---- SQL connection information
       +---- API secrets
       +---- Certificates
       +---- Other secrets

The pipeline doesn't need secrets embedded in source code.


26. Azure DevOps + App Service

Suppose your application is deployed to:

Azure App Service documentation

Architecture:

Azure Repos
     |
     v
Azure Pipeline
     |
     v
Build
     |
     v
Test
     |
     v
Artifact
     |
     v
Azure App Service

27. Azure DevOps + Azure Functions

Exactly the same principle:

Git
 |
 v
Azure Pipeline
 |
 +-- Build
 +-- Test
 +-- Package
 |
 v
Azure Function

28. Azure DevOps + AKS

For containerized microservices:

Developer
    |
    v
Azure Repos
    |
    v
Azure Pipeline
    |
    +-- Build .NET
    +-- Test
    +-- Docker Build
    +-- Push Image
    |
    v
Azure Container Registry
    |
    v
AKS

This connects several Azure services you should know as a .NET Lead.


29. Docker + Azure DevOps

Dockerfile:

FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base

WORKDIR /app

EXPOSE 8080

FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build

WORKDIR /src

COPY . .

RUN dotnet restore

RUN dotnet publish \
    -c Release \
    -o /app/publish

FROM base AS final

WORKDIR /app

COPY --from=build /app/publish .

ENTRYPOINT ["dotnet", "OrderApi.dll"]

Pipeline:

Code
 ↓
Build
 ↓
Docker Image
 ↓
ACR
 ↓
AKS

30. Azure Container Registry

ACR stores container images.

Azure DevOps
      |
      v
docker build
      |
      v
Docker Image
      |
      v
Azure Container Registry
      |
      v
AKS

Example image:

mycompany.azurecr.io/order-api:1.0.0

31. Infrastructure as Code

A Lead should know that infrastructure shouldn't always be manually created in the Azure Portal.

Use:

Bicep
ARM templates
Terraform

Conceptually:

Infrastructure Code
       |
       v
Azure DevOps Pipeline
       |
       v
Azure Resources

Example:

Bicep
 ↓
App Service
 ↓
SQL
 ↓
Service Bus
 ↓
Key Vault
 ↓
Application Insights

This gives you repeatable environments.


32. Deployment Strategies

You should know these concepts.

Blue-Green

Production
    |
 +-- Blue
 |
 +-- Green

Deploy to Green and switch traffic when validated.


Canary

Users
 |
 +---- 95% → Version 1
 |
 +---- 5%  → Version 2

Monitor Version 2.

If healthy:

5%
 ↓
25%
 ↓
50%
 ↓
100%

Rolling

Gradually replace old instances with new ones.

These strategies are particularly relevant to App Service, AKS and modern deployment architectures.


33. CI/CD Security

Your pipeline should include:

Code
 ↓
Build
 ↓
Unit Tests
 ↓
Security Scan
 ↓
Dependency Scan
 ↓
Quality Checks
 ↓
Artifact
 ↓
Deployment

A Lead should think about:

  • Secret management

  • Least privilege

  • Service connections

  • Branch policies

  • Dependency vulnerabilities

  • Container image scanning

  • Approval controls

  • Audit logs


34. Service Connections

Azure DevOps needs permission to deploy to Azure.

Conceptually:

Azure DevOps
     |
     | Service Connection
     v
Azure Subscription
     |
     +---- App Service
     +---- Function
     +---- ACR
     +---- AKS

Use appropriate identity-based authentication and least privilege rather than broadly granting excessive permissions.


35. Self-Hosted vs Microsoft-Hosted Agents

Microsoft-hosted agent

Azure DevOps provides the machine.

Pipeline
   |
   v
Microsoft-hosted Agent

Advantages:

  • Easy setup

  • Clean environment

  • Microsoft-managed infrastructure

Self-hosted agent

Your organization manages the agent.

Pipeline
   |
   v
Company Agent

Useful when you need:

  • Private network access

  • Special software

  • Internal systems

  • Custom build environments


36. Azure DevOps + Private Network

Suppose your SQL server is private:

Azure DevOps
     |
     X
Public Internet

You may need an appropriate self-hosted agent/network architecture.

Azure DevOps
     |
     v
Self-hosted Agent
     |
     v
VNet
     |
     v
Private SQL

This is an excellent Lead-level scenario.


37. Azure DevOps + Application Insights

You can connect deployment and monitoring:

Azure DevOps
     |
     v
Deploy
     |
     v
App Service
     |
     v
Application Insights
     |
     v
Azure Monitor

Suppose deployment happens:

Version 1.2.0

Then Application Insights shows:

Error rate
   ↑
Latency
   ↑

The Lead can investigate whether the new release caused the regression.


38. Production Deployment Strategy

I would recommend:

Developer
   |
   v
Feature Branch
   |
   v
Pull Request
   |
   +-- Reviewer Approval
   +-- Build Validation
   +-- Unit Tests
   |
   v
main
   |
   v
CI Pipeline
   |
   v
Artifact
   |
   v
DEV
   |
   v
Automated Tests
   |
   v
QA
   |
   v
UAT
   |
   v
Production Approval
   |
   v
PROD
   |
   v
Application Insights

39. Important Lead-Level Principle

Build Once, Deploy Many

Don't do:

Build → DEV
Build → QA
Build → PROD

Instead:

Build
  |
  v
Artifact
  |
  +---- DEV
  |
  +---- QA
  |
  +---- PROD

The same artifact should progress through environments.

This reduces "works in QA but not in production" problems caused by different builds.


40. Another Important Principle — Shift Left

Testing shouldn't start only in production.

You want:

Developer
   ↓
Compile
   ↓
Unit Test
   ↓
Static Analysis
   ↓
Security Scan
   ↓
Integration Test
   ↓
Deploy

The earlier you detect a defect, the cheaper it is to fix.


41. Rollback

Suppose:

Version 2.0

is deployed and causes:

HTTP 500 ↑
Latency ↑
Exceptions ↑

A good pipeline should support rollback.

Conceptually:

Production
   |
   v
Version 2.0
   |
   X
Problem
   |
   v
Rollback
   |
   v
Version 1.9

But a mature deployment strategy also aims to make rollback safe with database migration compatibility and backward-compatible contracts.


42. Database Migration Problem

Suppose:

Application v2

requires:

NewColumn

You can't blindly rollback if the database migration has destroyed compatibility.

Use an approach such as:

Expand
   ↓
Deploy
   ↓
Migrate data
   ↓
Switch application
   ↓
Contract

This is an important Lead-level DevOps + architecture topic.


43. Azure DevOps vs GitHub Actions

You may be asked this.

Both support CI/CD.

Azure DevOps offers a broader suite:

Boards
Repos
Pipelines
Test Plans
Artifacts

GitHub combines source control, collaboration and Actions-based automation in a different platform model.

Lead answer:

"I don't choose solely based on tool popularity. I consider existing organizational tooling, source-control platform, enterprise governance, security, integrations, team expertise and deployment requirements."


44. Azure DevOps Interview Questions

Basic

  1. What is Azure DevOps?

  2. What is Azure Repos?

  3. What is Azure Boards?

  4. What is Azure Pipelines?

  5. What is Azure Artifacts?

  6. What is Azure Test Plans?

  7. What is Git?

  8. What is a Pull Request?

  9. What is CI?

  10. What is CD?


45. Intermediate Questions

  1. Explain a CI/CD pipeline.

  2. What is a build artifact?

  3. What is a pipeline agent?

  4. Microsoft-hosted vs self-hosted agent?

  5. What are environments?

  6. How do you configure DEV/QA/PROD?

  7. How do you handle secrets?

  8. What is a variable group?

  9. What are service connections?

  10. How do you implement approvals?

  11. What are branch policies?

  12. How do you implement rollback?

  13. How do you deploy .NET applications?

  14. How do you deploy Azure Functions?

  15. How do you deploy Docker containers to AKS?


46. Lead-Level Questions

Q26. Design CI/CD for a microservices application.

You should draw:

Git
 ↓
PR
 ↓
Build
 ↓
Test
 ↓
Security
 ↓
Artifact
 ↓
ACR
 ↓
AKS
 ↓
Application Insights

Q27. How would you secure the pipeline?

Answer:

"I would use least-privilege service connections, managed identities where supported, Key Vault for secrets, branch protection, PR approvals, secret scanning, dependency and container scanning, environment approvals, audit logging and separation of duties."


Q28. How would you implement zero-downtime deployment?

Discuss:

Blue/Green
Canary
Rolling deployment
Health checks
Backward-compatible DB changes
Monitoring
Rollback

Q29. How would you handle a failed production deployment?

Strong answer:

Detect
 ↓
Stop further rollout
 ↓
Check Application Insights
 ↓
Compare deployment version
 ↓
Determine impact
 ↓
Rollback / forward fix
 ↓
Verify health
 ↓
Root Cause Analysis
 ↓
Improve pipeline

Q30. How would you design a pipeline for 20 microservices?

Don't necessarily create one giant pipeline.

Consider:

             Shared Templates
                    |
       +------------+------------+
       |            |            |
       v            v            v
 Order Pipeline  Payment       Inventory
       |          Pipeline       Pipeline
       v            v            v
      ACR          ACR           ACR
       |            |             |
       v            v             v
      AKS          AKS           AKS

Use reusable YAML templates and standard pipeline conventions.


47. Real-Time .NET Lead Example

Let's put everything together.

Your company has:

Angular
ASP.NET Core
Azure SQL
Service Bus
Azure Functions
AKS
Key Vault
Application Insights

The delivery architecture:

                      Developer
                          |
                          v
                    Azure Repos
                          |
                          v
                    Pull Request
                          |
                 +--------+--------+
                 |                 |
                 v                 v
              Review         Build Validation
                                   |
                                   v
                              Azure Pipeline
                                   |
               +-------------------+-------------------+
               |                   |                   |
               v                   v                   v
             Build              Unit Test          Security
               |                   |                   |
               +-------------------+-------------------+
                                   |
                                   v
                              Docker Build
                                   |
                                   v
                         Azure Container Registry
                                   |
                                   v
                                  AKS
                                   |
                                   v
                          Application Insights
                                   |
                                   v
                            Azure Monitor

This is a very strong architecture to explain in a Lead interview.


48. What Would I Say in the Interview?

If asked:

"Explain how you have used Azure DevOps in your project."

You can answer:

"We used Azure Repos for Git-based source control and Azure Boards for Agile work management. Developers worked on feature branches and created pull requests with mandatory reviews and build validation. Azure Pipelines implemented CI/CD. The CI stage restored dependencies, built the .NET solution, executed unit tests and security/quality checks, and published an immutable artifact. Deployment stages promoted the same artifact through DEV, QA, UAT and Production with environment-specific configuration and approvals. Secrets were managed through Key Vault, and production deployments were monitored through Application Insights and Azure Monitor. For containerized services, the pipeline built Docker images, pushed them to Azure Container Registry and deployed them to AKS."

That's a strong .NET Lead-level answer.


49. One Diagram to Memorize

For your interview, remember this:

                         AZURE DEVOPS
                              |
       +----------------------+----------------------+
       |                      |                      |
       v                      v                      v
    BOARDS                  REPOS                PIPELINES
       |                      |                      |
    Stories                 Git                 Build
    Tasks                   PR                  Test
    Bugs                    Review              Package
       |                      |                  Deploy
       +----------------------+----------------------+
                              |
                              v
                           Artifact
                              |
                +-------------+-------------+
                |             |             |
                v             v             v
               DEV           QA            PROD
                                             |
                                             v
                                    Application Insights
                                             |
                                             v
                                       Azure Monitor

The 10 things I recommend mastering for your Lead interview

  1. Git + Branching Strategy

  2. Pull Requests + Branch Policies

  3. CI/CD

  4. YAML Pipelines

  5. Build Artifacts

  6. Multi-stage deployment

  7. Environment approvals

  8. Key Vault + Secret Management

  9. Docker + ACR + AKS deployment

  10. Application Insights + Azure Monitor integration


Azure Monitor & Application Insights

Azure Monitor & Application Insights - 

Complete Guide for .NET Lead

Azure Monitor documentation

Application Insights documentation

1. First understand the difference

The easiest way to remember:

Application Insights = Monitor your application.
Azure Monitor = Monitor your overall Azure environment.

Think of it like this:

                    Azure Monitor
                         |
       +-----------------+------------------+
       |                 |                  |
       v                 v                  v
 Application         Infrastructure      Azure Resources
  Insights              Metrics             Logs
       |
       +--- Requests
       +--- Exceptions
       +--- Dependencies
       +--- Traces
       +--- Availability

Application Insights is an Azure Monitor feature for application performance monitoring (APM). It can collect telemetry such as requests, dependencies, exceptions, traces and availability information.


2. Real-Time Project

Let's imagine you are a .NET Lead working on an e-commerce application.

Architecture:

                         Angular
                            |
                            v
                    Azure API Management
                            |
                            v
                    ASP.NET Core API
                            |
             +--------------+--------------+
             |                             |
             v                             v
         Azure SQL                    Azure Service Bus
                                           |
                                           v
                                    Azure Function
                                           |
                               +-----------+-----------+
                               |                       |
                               v                       v
                           Payment                 Notification
                           Service                   Service

Now your manager says:

"Production users are complaining that the Order API is slow."

You need to answer:

Where is the problem?

Is it:

Angular?
API?
SQL?
Service Bus?
Payment API?
Azure Function?
Network?

This is where Application Insights + Azure Monitor become extremely useful.


3. What does Application Insights collect?

For an ASP.NET Core application, you can monitor:

Requests

POST /api/orders
GET /api/products
GET /api/customers/100

Dependencies

SQL
HTTP API
Service Bus
Redis
Storage

Exceptions

SqlException
HttpRequestException
NullReferenceException
TimeoutException

Traces

Your application logs:

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

Availability

You can monitor whether your application/API is reachable and responding correctly.


4. Real-Time Problem

Suppose your customer reports:

"Creating an order takes 10 seconds."

You open Application Insights.

You see:

POST /api/orders

Duration: 10.4 seconds

Now you need to find why.

Application Insights can show the request's dependencies.

You discover:

Order API
    |
    +---- SQL: 0.5 sec
    |
    +---- Payment API: 8.7 sec
    |
    +---- Service Bus: 0.3 sec

Immediately:

Payment API = 8.7 seconds

You have identified the bottleneck.

That's the real value of Application Insights.


5. Application Insights Architecture

Conceptually:

ASP.NET Core API
      |
      | Telemetry
      v
Application Insights
      |
      v
Azure Monitor
      |
 +----+-----+----------+
 |          |          |
 v          v          v
Logs      Metrics    Alerts

6. Step 1 — Create Application Insights

In Azure Portal:

Azure Portal
     ↓
Create a resource
     ↓
Search "Application Insights"
     ↓
Create

You'll generally associate it with the appropriate Azure resource/workload.


7. Step 2 — Add Application Insights to .NET

For an ASP.NET Core application, add the Application Insights SDK.

For example:

dotnet add package Microsoft.ApplicationInsights.AspNetCore

Then in Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddApplicationInsightsTelemetry();

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

Your application can then send telemetry to Application Insights.


8. Connection Configuration

Application Insights uses a connection string.

For example:

{
  "ApplicationInsights": {
    "ConnectionString": "YOUR_CONNECTION_STRING"
  }
}

In production, don't commit secrets or sensitive configuration into Git.

Use appropriate Azure configuration/security mechanisms such as managed identity, Key Vault and environment configuration.


9. Add Logging

Suppose we have:

[HttpPost]
public async Task<IActionResult> CreateOrder(
    CreateOrderRequest request)
{
    _logger.LogInformation(
        "Creating order for customer {CustomerId}",
        request.CustomerId);

    // Business logic

    return Ok();
}

Application Insights can capture this telemetry.


10. Structured Logging

Avoid:

_logger.LogInformation(
    "Customer 1001 created order 5001");

Prefer:

_logger.LogInformation(
    "Customer {CustomerId} created Order {OrderId}",
    customerId,
    orderId);

Why?

Because structured properties make logs easier to search, filter and correlate.


11. Real-Time Example — Order API

Let's build a simple service.

POST /api/orders

Controller:

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    private readonly ILogger<OrdersController> _logger;
    private readonly IOrderService _orderService;

    public OrdersController(
        ILogger<OrdersController> logger,
        IOrderService orderService)
    {
        _logger = logger;
        _orderService = orderService;
    }

    [HttpPost]
    public async Task<IActionResult> CreateOrder(
        CreateOrderRequest request)
    {
        _logger.LogInformation(
            "Creating order for Customer {CustomerId}",
            request.CustomerId);

        var result =
            await _orderService.CreateAsync(request);

        _logger.LogInformation(
            "Order {OrderId} created successfully",
            result.OrderId);

        return Ok(result);
    }
}

12. Add Exception Logging

try
{
    var result =
        await _orderService.CreateAsync(request);

    return Ok(result);
}
catch (Exception ex)
{
    _logger.LogError(
        ex,
        "Error creating order for Customer {CustomerId}",
        request.CustomerId);

    throw;
}

Application Insights can then help you find:

Exceptions
    |
    +--- Exception Type
    +--- Message
    +--- Stack Trace
    +--- Request
    +--- Timestamp

13. Application Insights — Failures

Suppose production shows:

Failures
-----------------------------
Exceptions       1,243
Failed Requests   850

You click Failures.

You discover:

SqlException
Timeout expired

Now you investigate the database dependency.


14. Application Insights — Performance

Suppose:

Requests
-------------------------------
GET /api/products     100ms
GET /api/customers    150ms
POST /api/orders      8.7 sec

You immediately know:

POST /api/orders

needs investigation.


15. Dependency Tracking

This is one of the most useful features.

Your API:

POST /api/orders

calls:

Azure SQL
Payment API
Service Bus

Application Insights can help show the dependency calls and their duration.

Conceptually:

POST /api/orders
       |
       +---- SQL
       |     300 ms
       |
       +---- Payment API
       |     8,000 ms
       |
       +---- Service Bus
             100 ms

Now your troubleshooting becomes much faster.


16. Distributed Tracing

This becomes very important in microservices.

Imagine:

Angular
   |
   v
API Management
   |
   v
Order API
   |
   v
Service Bus
   |
   v
Payment Function
   |
   v
Payment API
   |
   v
Azure SQL

The user says:

"Order 5001 failed."

You need to trace the entire operation.

This is where correlation IDs and distributed tracing become extremely valuable.


17. Correlation ID

Suppose we create:

CorrelationId = ABC-123

Then:

Order API
    |
    | ABC-123
    v
Service Bus
    |
    | ABC-123
    v
Payment Function
    |
    | ABC-123
    v
Payment API

You can search logs/telemetry around that operation.


18. Custom Telemetry

You can also send custom telemetry using TelemetryClient.

For example:

using Microsoft.ApplicationInsights;

public class PaymentService
{
    private readonly TelemetryClient _telemetry;

    public PaymentService(
        TelemetryClient telemetry)
    {
        _telemetry = telemetry;
    }

    public async Task ProcessPaymentAsync(
        int orderId,
        decimal amount)
    {
        _telemetry.TrackEvent(
            "PaymentStarted",
            new Dictionary<string, string>
            {
                ["OrderId"] = orderId.ToString()
            });

        // Payment processing

        _telemetry.TrackMetric(
            "PaymentAmount",
            (double)amount);

        await Task.CompletedTask;
    }
}

19. Custom Events

For business monitoring, custom events can be useful.

Example:

OrderCreated
PaymentCompleted
PaymentFailed
InvoiceGenerated

Then you can investigate business activity in addition to technical telemetry.


20. Azure Monitor

Now let's move one level higher.

Application Insights focuses heavily on application telemetry.

Azure Monitor provides broader monitoring capabilities across Azure resources and applications.

Think:

                    Azure Monitor
                         |
        +----------------+----------------+
        |                |                |
        v                v                v
    Application       Platform         Infrastructure
     Insights          Metrics            Logs
        |
        v
    Application

Examples of Azure resources you might monitor:

App Service
Azure SQL
Service Bus
Storage
Functions
AKS
Virtual Machines

21. Azure Monitor Metrics

Suppose Azure SQL is slow.

You could examine metrics related to:

CPU
Storage
Connections
Database performance

For Service Bus:

Messages
Active messages
Dead-lettered messages
Incoming/outgoing operations

For App Service:

CPU
Memory
Requests
HTTP errors
Response time

The exact available metrics depend on the Azure resource.


22. Logs vs Metrics

Very important interview question.

Metrics

Numerical measurements.

Example:

CPU = 78%
Memory = 65%
Requests = 10,000
Response Time = 1.5 sec

Good for:

Dashboards
Alerts
Trend analysis

Logs

Detailed records.

Example:

Order 1001 failed because SQL timeout occurred.

Good for:

Troubleshooting
Debugging
Detailed investigation

23. Azure Monitor Logs and KQL

One of the most important skills for Azure interviews is Kusto Query Language (KQL).

You can query telemetry in Azure Monitor Logs/Application Insights.

For example, a request query might look like:

requests
| where timestamp > ago(1h)
| summarize
    Count = count(),
    AvgDuration = avg(duration)
    by name
| order by AvgDuration desc

This answers:

"Which API endpoints have the highest average duration during the last hour?"


24. Find Failed Requests

requests
| where success == false
| project
    timestamp,
    name,
    resultCode,
    duration
| order by timestamp desc

This gives you failed requests and their details.


25. Find Exceptions

exceptions
| where timestamp > ago(1h)
| project
    timestamp,
    type,
    outerMessage
| order by timestamp desc

You can investigate what exceptions are happening in production.


26. Find Slow APIs

requests
| where timestamp > ago(1h)
| where duration > 2000
| project
    timestamp,
    name,
    duration,
    resultCode
| order by duration desc

This finds requests taking more than 2 seconds.


27. Find SQL Dependency Problems

Conceptually, you can query dependency telemetry:

dependencies
| where timestamp > ago(1h)
| where duration > 1000
| project
    timestamp,
    name,
    target,
    duration,
    success
| order by duration desc

You might discover:

SQL Query
Duration: 4.2 sec

Now you investigate SQL.


28. Application Map

One of the most useful visual concepts is the Application Map.

Imagine:

                  Order API
                      |
        +-------------+-------------+
        |             |             |
        v             v             v
      SQL        Service Bus     Payment API
                      |
                      v
                Azure Function

This helps you understand:

  • Dependencies

  • Failures

  • Performance

  • Service relationships

For a microservices environment, this is extremely valuable.


29. Real-Time Production Problem

Let's walk through a real incident.

User complaint

"Order creation is taking 15 seconds."

You start with:

Application Insights
        ↓
Performance

You discover:

POST /api/orders
Duration = 15 seconds

Then inspect dependencies:

SQL              = 300 ms
Service Bus      = 200 ms
Payment API      = 14.2 sec

Problem identified:

Payment API

Then you inspect the Payment API.

You find:

Payment API
   |
   v
SQL Query
   |
   v
Slow query = 13 seconds

Now you move to:

Azure SQL

You investigate:

  • Query execution plan

  • Indexes

  • Blocking

  • CPU

  • Database resource usage

This is how monitoring helps you move from:

"Application is slow"

to:

"Payment API's SQL dependency is causing the latency."


30. Alerts

Monitoring without alerts isn't enough.

Imagine:

API failure rate > 5%

You can configure an alert.

Conceptually:

API
 |
 v
Application Insights
 |
 v
Failure Rate > 5%
 |
 v
Azure Monitor Alert
 |
 +---- Email
 +---- Teams/notification integration
 +---- Incident management

Similarly:

SQL CPU > threshold
Service Bus DLQ > threshold
API latency > threshold
Function failures > threshold

can be monitored with appropriate alert rules.


31. Service Bus Monitoring Example

Your architecture:

Order API
    |
    v
Service Bus
    |
    v
Order Function

Suddenly users report:

"Orders aren't getting processed."

You open Service Bus monitoring.

You discover:

Active Messages = 50,000
Dead Letter = 5,000

This tells you the consumer is falling behind or failing.

Then Application Insights shows:

Order Function
    |
    v
SQL TimeoutException

Now you've connected:

Service Bus backlog
       ↓
Function failures
       ↓
SQL timeout

This is the kind of troubleshooting a Lead should be able to explain.


32. Azure Monitor + Application Insights + Service Bus

Complete monitoring picture:

                         Azure Monitor
                              |
             +----------------+----------------+
             |                                 |
             v                                 v
     Application Insights                Azure Metrics
             |
     +-------+-------+
     |       |       |
     v       v       v
 Requests  Errors  Dependencies
     |
     +---- API
     +---- SQL
     +---- Service Bus
     +---- External APIs

33. Production Logging Strategy

Don't just write:

Console.WriteLine("Something happened");

Prefer:

_logger.LogInformation(
    "Order {OrderId} submitted by Customer {CustomerId}",
    orderId,
    customerId);

And:

_logger.LogError(
    exception,
    "Failed to process Order {OrderId}",
    orderId);

This gives structured telemetry that is much easier to query.


34. What Should You NOT Log?

Never casually log:

Passwords
Connection strings
Access tokens
API keys
Credit card information
Sensitive personal information

For example, don't do:

_logger.LogInformation(
    "Payment token = {Token}",
    token);

That's a security problem.


35. Health Checks vs Application Insights

Don't confuse them.

Health Check

Answers:

"Is my application/dependency healthy right now?"

Example:

/api/health

Application Insights

Answers:

"What has my application been doing? What failed? What is slow? What dependencies are causing problems?"

They complement each other.


36. Application Insights vs Azure Monitor — Interview Answer

If interviewer asks:

"What's the difference between Azure Monitor and Application Insights?"

Answer:

"Application Insights is an application performance monitoring capability within Azure Monitor. It focuses on application telemetry such as requests, dependencies, exceptions, traces and availability. Azure Monitor provides the broader monitoring platform for Azure resources, infrastructure, metrics, logs, alerts and application telemetry."

That's a strong answer.


37. Lead-Level Architecture

For a production system, I'd propose:

                         Users
                           |
                           v
                    API Management
                           |
                           v
                     App Service
                           |
          +----------------+----------------+
          |                                 |
          v                                 v
      Azure SQL                       Service Bus
                                            |
                                            v
                                       Azure Function
                                            |
                                            v
                                     External Payment
                                            |
                                            v
                                      Notification


          ALL COMPONENTS
                 |
                 v
          Azure Monitor
                 |
        +--------+--------+
        |                 |
        v                 v
 Application          Resource
  Insights             Metrics
        |
 +------+--------+
 |      |        |
 v      v        v
Logs  Traces  Exceptions
        |
        v
      KQL
        |
        v
     Alerts

38. Lead Interview Scenario

Interviewer:

"Production API is slow. How would you troubleshoot it?"

Don't say:

"I'll check the code."

Give a structured answer.

Step 1 — Application Insights

Check:

Request duration
Failure rate
Exceptions
Dependencies

Step 2 — Identify bottleneck

Example:

API = 10 seconds

SQL = 1 sec
Service Bus = 100 ms
Payment API = 8.5 sec

Step 3 — Drill down

Investigate Payment API.

Step 4 — Check Azure Monitor

Look at:

CPU
Memory
Network
Database metrics
Service Bus backlog

Step 5 — KQL

Query slow requests/dependencies.

Step 6 — Correlation

Follow the same operation across services using distributed tracing/correlation.

Step 7 — Fix

Potential causes:

Slow SQL query
Missing index
External API latency
Connection pool exhaustion
Thread starvation
High CPU
Service Bus backlog
Network issue

Step 8 — Prevent recurrence

Add:

Alert
Dashboard
Performance baseline
Capacity planning

That demonstrates Lead-level troubleshooting rather than simply knowing where the Azure Portal menus are.


39. Top KQL Queries to Remember

Failed requests

requests
| where success == false
| project timestamp, name, resultCode, duration

Slow requests

requests
| where duration > 2000
| project timestamp, name, duration
| order by duration desc

Exceptions

exceptions
| project timestamp, type, outerMessage
| order by timestamp desc

Request count

requests
| summarize count() by bin(timestamp, 5m)

Average response time

requests
| summarize avg(duration) by name
| order by avg_duration desc

Dependency failures

dependencies
| where success == false
| project timestamp, name, target, duration

40. Interview Questions

Basic

  1. What is Azure Monitor?

  2. What is Application Insights?

  3. What is the difference between them?

  4. What is telemetry?

  5. What is distributed tracing?

  6. What are dependencies?

  7. What is Application Map?

  8. What are metrics?

  9. What are logs?

  10. What are alerts?

Intermediate

  1. How do you monitor an ASP.NET Core API?

  2. How do you capture exceptions?

  3. How do you monitor SQL dependencies?

  4. How do you monitor Service Bus?

  5. How do you find slow APIs?

  6. What is KQL?

  7. How do you configure alerts?

  8. How do you track external API calls?

  9. How do you monitor Azure Functions?

  10. How do you troubleshoot production failures?

Lead-level

  1. How would you monitor a microservices architecture?

  2. How do you trace a request across multiple services?

  3. How do you troubleshoot an API taking 10 seconds?

  4. How do you identify whether SQL or an external API is causing latency?

  5. How do you design monitoring for a production system?

  6. What metrics would you monitor for Service Bus?

  7. How would you monitor Azure SQL?

  8. How do you design alerting without creating alert fatigue?

  9. What should and shouldn't be logged?

  10. How do you implement observability across microservices?


41. Three Words to Remember

For a Lead interview, remember:

Logs

What happened?

Metrics

How much/how often?

Traces

Where did the request travel and where did it spend time?

Together:

                 Observability
                      |
          +-----------+-----------+
          |           |           |
          v           v           v
         Logs       Metrics      Traces
          |           |           |
          v           v           v
       Details     Numbers     Journey

42. Final Real-Time Example

Imagine this production flow:

Customer
   |
   v
Angular
   |
   v
API Management
   |
   v
Order API
   |
   +-------> Azure SQL
   |
   +-------> Service Bus
                 |
                 v
            Azure Function
                 |
                 v
            Payment API

Customer says:

"My order is taking 12 seconds."

You don't randomly check everything.

You follow:

Application Insights
       ↓
Request
       ↓
POST /api/orders
       ↓
12 seconds
       ↓
Dependencies
       ↓
SQL = 300ms
Service Bus = 100ms
Payment API = 11.2 sec
       ↓
Payment API
       ↓
Dependency
       ↓
SQL Query = 10.8 sec
       ↓
Azure Monitor
       ↓
SQL resource metrics
       ↓
Find bottleneck
       ↓
Fix SQL/index/query
       ↓
Create alert


Azure Service Bus

Microsoft Azure Service Bus documentation

Azure Service Bus — Complete Guide with C#

1. What is Azure Service Bus?

Azure Service Bus is a cloud-based message broker.

Its primary job is to allow applications and services to communicate without directly calling each other.

Instead of:

Order Service
     |
     | HTTP call
     v
Payment Service

we can use:

Order Service
     |
     | Message
     v
Azure Service Bus
     |
     | Message
     v
Payment Service

This creates loose coupling between services.

Azure Service Bus supports messaging features such as queues, topics/subscriptions, dead-lettering, duplicate detection, transactions, sessions and scheduled messages.


2. Why do we need Service Bus?

Suppose you have an e-commerce application:

Angular
   |
   v
Order API
   |
   +---- Payment Service
   |
   +---- Inventory Service
   |
   +---- Notification Service

The Order API directly calls all three services.

Imagine:

Payment Service     → 5 seconds
Inventory Service   → 2 seconds
Email Service       → 3 seconds

The Order API could end up waiting for multiple downstream services.

There are also other problems:

  • Payment service may be unavailable.

  • Inventory service may be overloaded.

  • Email service may be temporarily down.

  • Network failures can occur.

  • Services become tightly coupled.

Instead:

                 Order API
                    |
                    |
                    v
             Azure Service Bus
                    |
        +-----------+-----------+
        |           |           |
        v           v           v
    Payment     Inventory    Notification
    Service      Service       Service

Now the services communicate asynchronously.


3. What exactly is a message?

A message is simply a piece of data sent from one component to another.

For example:

{
    "OrderId": 1001,
    "CustomerId": 5001,
    "Amount": 2500.00
}

We can send that message to Service Bus.

The message could represent:

OrderCreated
PaymentRequested
InventoryReserved
EmailRequested
InvoiceGenerated

4. The most important Service Bus concepts

You need to understand:

Service Bus Namespace
        |
        +---- Queue
        |
        +---- Topic
                  |
                  +---- Subscription
                  +---- Subscription

Let's understand each.


5. Service Bus Namespace

A namespace is the container for your Service Bus messaging resources.

Think of it like:

Azure
 |
 +-- Service Bus Namespace
          |
          +-- orders queue
          +-- payments queue
          +-- order-events topic

Your application connects to the namespace and accesses queues/topics inside it.


6. Queue

A queue is used for one message → one consumer/processing operation.

Architecture:

Producer
   |
   v
+-------------------+
|    Orders Queue   |
+-------------------+
   |
   v
Consumer

Example:

Order API
    |
    v
Orders Queue
    |
    v
Order Processing Service

The producer doesn't have to wait for the consumer.


7. How a Queue Actually Works

Let's take:

Order API

Customer creates:

Order #1001

The API creates:

{
   "OrderId": 1001,
   "CustomerId": 50,
   "Amount": 5000
}

It sends this message to:

orders

Now:

Order API
    |
    | Message
    v
+--------------------+
| orders queue       |
|                    |
| Message #1001      |
+--------------------+

The message stays in the queue until a consumer receives/processes it.

Then:

Orders Queue
     |
     v
Order Processor

8. Important Concept: Producer and Consumer

Producer

The application that sends the message.

Order API

Consumer

The application that receives/processes the message.

Order Processing Service

So:

Producer
   |
   v
Service Bus
   |
   v
Consumer

9. Real-Time Example

Imagine Amazon-style order processing.

Customer clicks:

BUY NOW

Angular:

POST /api/orders

ASP.NET Core:

OrderController
     |
     v
OrderService
     |
     +---- Save order
     |
     +---- Send OrderCreated message
              |
              v
        Azure Service Bus
              |
              v
       Order Processor
              |
       +------+------+
       |             |
       v             v
   Inventory       Payment

This is a classic real-world use case.


10. Install the C# NuGet Package

For .NET:

dotnet add package Azure.Messaging.ServiceBus

Microsoft's current .NET SDK for Service Bus is Azure.Messaging.ServiceBus.


11. Sending a Message — C#

Suppose we have:

public class OrderCreatedEvent
{
    public int OrderId { get; set; }

    public int CustomerId { get; set; }

    public decimal Amount { get; set; }
}

Now create the sender.

using Azure.Messaging.ServiceBus;
using System.Text.Json;

public class OrderMessagePublisher
{
    private readonly ServiceBusSender _sender;

    public OrderMessagePublisher(ServiceBusClient client)
    {
        _sender = client.CreateSender("orders");
    }

    public async Task PublishAsync(OrderCreatedEvent order)
    {
        var json = JsonSerializer.Serialize(order);

        var message = new ServiceBusMessage(json);

        await _sender.SendMessageAsync(message);
    }
}

12. Register Service Bus in ASP.NET Core

In Program.cs:

using Azure.Messaging.ServiceBus;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<ServiceBusClient>(sp =>
{
    var configuration =
        sp.GetRequiredService<IConfiguration>();

    var connectionString =
        configuration["ServiceBus:ConnectionString"];

    return new ServiceBusClient(connectionString);
});

builder.Services.AddScoped<OrderMessagePublisher>();

var app = builder.Build();

app.Run();

Configuration:

{
  "ServiceBus": {
    "ConnectionString": "YOUR_CONNECTION_STRING"
  }
}

Don't put real production secrets in source control.

In production, prefer Managed Identity + Azure RBAC, with secrets/certificates handled through appropriate Azure security services.


13. Controller Sends Message

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    private readonly OrderMessagePublisher _publisher;

    public OrdersController(
        OrderMessagePublisher publisher)
    {
        _publisher = publisher;
    }

    [HttpPost]
    public async Task<IActionResult> CreateOrder(
        OrderCreatedEvent order)
    {
        // Save order to database first

        await _publisher.PublishAsync(order);

        return Accepted(new
        {
            Message = "Order accepted",
            order.OrderId
        });
    }
}

Notice:

return Accepted();

HTTP 202 Accepted is often appropriate when the request has been accepted for asynchronous processing but the downstream work is not necessarily complete yet.


14. Receiving the Message

Now let's create the consumer.

There are several ways to consume Service Bus messages. In a .NET worker or ASP.NET Core application, the ServiceBusProcessor is a common approach.

using Azure.Messaging.ServiceBus;
using System.Text.Json;

public class OrderMessageConsumer
{
    private readonly ServiceBusProcessor _processor;

    public OrderMessageConsumer(ServiceBusClient client)
    {
        _processor =
            client.CreateProcessor("orders");
    }

    public async Task StartAsync()
    {
        _processor.ProcessMessageAsync += ProcessMessage;
        _processor.ProcessErrorAsync += ProcessError;

        await _processor.StartProcessingAsync();
    }

    private async Task ProcessMessage(
        ProcessMessageEventArgs args)
    {
        var order =
            JsonSerializer.Deserialize<OrderCreatedEvent>(
                args.Message.Body.ToString());

        if (order == null)
            return;

        Console.WriteLine(
            $"Processing Order {order.OrderId}");

        // Business logic

        await args.CompleteMessageAsync(
            args.Message);
    }

    private Task ProcessError(
        ProcessErrorEventArgs args)
    {
        Console.WriteLine(args.Exception);

        return Task.CompletedTask;
    }
}

15. What happens internally?

Let's visualize it:

             Producer
                 |
                 |
                 | SendMessageAsync()
                 v
        +-------------------+
        |                   |
        |  Service Bus      |
        |                   |
        |  Orders Queue     |
        |                   |
        |  Message #1001    |
        |                   |
        +-------------------+
                 |
                 |
                 | Receive
                 v
             Consumer
                 |
                 v
          Process Order
                 |
                 v
       CompleteMessageAsync()

That last step is very important.


16. Complete Message

When processing succeeds:

await args.CompleteMessageAsync(args.Message);

This tells Service Bus:

"The consumer successfully processed this message."

The message is then removed from the queue.


17. What if Processing Fails?

Suppose:

Order #1001
     |
     v
Consumer
     |
     v
SQL Database
     |
     X
Database unavailable

If processing fails and the message isn't completed, Service Bus can make the message available again according to its delivery/lock behavior.

Conceptually:

Message
   |
Consumer
   |
Failure
   |
Retry
   |
Failure
   |
Retry
   |
Failure
   |
Dead Letter Queue

This is one of the most important concepts to understand.


18. Dead Letter Queue — DLQ

A Dead Letter Queue is a special subqueue for messages that can't be successfully processed.

Example:

Orders Queue
     |
     v
Function
     |
     X
Processing failed
     |
     v
Retry
     |
     X
Retry
     |
     X
Retry exhausted
     |
     v
Dead Letter Queue

Operations teams can inspect the DLQ and determine why the message failed.

Service Bus provides dead-lettering as part of its messaging capabilities.


19. Why is DLQ important?

Imagine you receive:

{
   "OrderId": 1001,
   "Amount": -500
}

This is invalid.

If you continually retry it:

Retry
Retry
Retry
Retry
Retry
...

you are wasting resources.

Instead:

Invalid Message
      |
      v
Dead Letter Queue

Then the team can inspect it.


20. Queue vs Topic

This is one of the most important interview questions.

Queue

One message is normally processed by one competing consumer.

Producer
   |
   v
Queue
   |
   +---- Consumer 1
   |
   +---- Consumer 2

Multiple consumers can compete for messages.


Topic

A topic is useful for publish/subscribe.

                Producer
                    |
                    v
              OrderCreated
                  Topic
                    |
       +------------+------------+
       |            |            |
       v            v            v
 Subscription   Subscription   Subscription
       |            |            |
       v            v            v
 Payment        Inventory      Notification

Each subscription can receive its own copy of the event.


21. Real-Time Topic Example

Suppose:

OrderCreated

Three systems need to know about it:

Payment
Inventory
Email

Don't create:

Order API
   |
   +---- Payment
   +---- Inventory
   +---- Email

Instead:

Order API
    |
    v
Service Bus Topic
    |
    +---- Payment Subscription
    |
    +---- Inventory Subscription
    |
    +---- Notification Subscription

Now each service receives the event independently.

This is publish/subscribe.


22. Queue vs Topic — Interview Answer

QueueTopic
Point-to-point messagingPublish/subscribe
One processing path per messageMultiple subscriptions can receive event
Good for work distributionGood for broadcasting events
Consumers compete for messagesEach subscription gets its own message stream

Interview answer:

"I use a queue when one processing operation needs to consume a message. I use a topic when multiple independent services need to react to the same event."


23. How Services Communicate Through Service Bus

Let's take:

Order Service
Payment Service
Inventory Service
Notification Service

Instead of direct HTTP calls:

Order
 |
 +----HTTP----> Payment
 |
 +----HTTP----> Inventory
 |
 +----HTTP----> Notification

we use:

                     Order Service
                           |
                           v
                    Service Bus Topic
                           |
            +--------------+--------------+
            |              |              |
            v              v              v
       Payment         Inventory      Notification
      Subscription    Subscription    Subscription

This creates loose coupling.


24. What does Loose Coupling mean?

Without Service Bus:

Order Service
     |
     | needs Payment API
     v
Payment Service

Order service knows:

  • Payment service URL

  • Payment API contract

  • Payment availability

  • Network connection

With Service Bus:

Order Service
     |
     v
Service Bus

The Order Service only needs to know:

"I need to publish an OrderCreated event."

It doesn't need to know which consumers are listening.

That's loose coupling.


25. Synchronous vs Asynchronous Communication

Synchronous

Order API
    |
    | HTTP
    v
Payment
    |
    | Response
    v
Order API

The caller waits.


Asynchronous

Order API
    |
    | Message
    v
Service Bus
    |
    v
Return response

Later:

Service Bus
    |
    v
Payment Service

The producer doesn't need to wait for the consumer to finish processing.


26. When Should You Use Synchronous Communication?

Use HTTP/API calls when the caller immediately needs a response.

Example:

GET /api/products/100

You need:

{
   "id": 100,
   "name": "Laptop"
}

That's naturally synchronous.


27. When Should You Use Service Bus?

Good examples:

Order processing
Payment processing
Email notification
Report generation
File processing
Background jobs
Integration between microservices
Long-running processing
Traffic spike absorption

28. Important: Service Bus Does NOT Replace HTTP

A common beginner mistake is:

"We have Service Bus, so we don't need REST APIs."

Wrong.

Use:

HTTP

for:

Request → Immediate Response

Use:

Service Bus

for:

Message → Asynchronous Processing

A real application often uses both.


29. Real Enterprise Architecture

Here's a strong architecture for an interview:

                      Angular
                         |
                         v
                  Azure API Management
                         |
                         v
                 ASP.NET Core API
                         |
                  +------+------+
                  |             |
                  v             v
              Azure SQL     Service Bus
                                |
                        OrderCreated Topic
                                |
             +------------------+----------------+
             |                  |                |
             v                  v                v
         Payment             Inventory      Notification
         Service             Service          Service
             |                  |                |
             v                  v                v
         Payment DB          Inventory DB     Email Provider

This is a classic event-driven microservices architecture.


30. C# Event Model

Instead of sending random strings, create event contracts.

public record OrderCreatedEvent(
    Guid EventId,
    int OrderId,
    int CustomerId,
    decimal Amount,
    DateTime CreatedAt);

Then:

var orderEvent = new OrderCreatedEvent(
    Guid.NewGuid(),
    order.Id,
    order.CustomerId,
    order.TotalAmount,
    DateTime.UtcNow);

Serialize:

var json =
    JsonSerializer.Serialize(orderEvent);

var message =
    new ServiceBusMessage(json);

31. Message Metadata

A Service Bus message isn't only a body.

You can attach metadata.

Example:

var message = new ServiceBusMessage(json)
{
    MessageId = orderEvent.EventId.ToString(),
    Subject = "OrderCreated",
    CorrelationId = order.Id.ToString(),
    ContentType = "application/json"
};

This is useful for tracing and troubleshooting.


32. MessageId

Suppose:

MessageId = ABC123

If the same message arrives again:

ABC123

your consumer can use this ID to implement idempotency.


33. CorrelationId

This is extremely useful in microservices.

Imagine:

API Request
CorrelationId = 12345

Then:

Order API
   |
   | CorrelationId 12345
   v
Service Bus
   |
   v
Payment
   |
   v
Inventory
   |
   v
Notification

Now you can search logs for:

CorrelationId = 12345

and follow the entire transaction.

For a Lead, distributed tracing/correlation is an important production topic.


34. Message Lock

When a consumer receives a message, Service Bus can lock that message temporarily so another consumer doesn't process it simultaneously.

Conceptually:

Queue
 |
 v
Consumer A
 |
Lock acquired
 |
Processing

If processing completes:

Complete

If processing doesn't complete successfully before the lock expires, the message can become available again.

This is one reason long-running processing needs careful design.


35. At-Least-Once Processing

In distributed messaging systems, you should design consumers expecting that a message may be delivered more than once.

Example:

Message
   |
Consumer
   |
Process payment
   |
Network failure
   |
Consumer doesn't successfully complete message
   |
Message becomes available again

Now:

Same message
      |
      v
Consumer again

Therefore:

Consumers should be idempotent.

This is a very important Lead-level concept.


36. Idempotency Example

Suppose:

OrderId = 1001

We maintain:

ProcessedMessages
-------------------------
MessageId
ProcessedAt

Before processing:

var exists =
    await db.ProcessedMessages
        .AnyAsync(x => x.MessageId == messageId);

if (exists)
{
    return;
}

Then:

Message
   |
Already processed?
  / \
Yes  No
 |    |
Stop  Process
      |
      v
Record MessageId

37. Important Production Problem: Database + Service Bus

Imagine:

API
 |
 +---- Save Order to SQL
 |
 +---- Send Service Bus Message

What happens if:

SQL Save → SUCCESS
Service Bus → FAILURE

Now your database says:

Order Created

but your message wasn't published.

This is called a dual-write consistency problem.


38. Outbox Pattern

For a Lead interview, this is a fantastic concept.

Instead of:

SQL
 |
 +---- Order
 |
 +---- Service Bus

we save both the order and an event/outbox record in the same database transaction:

SQL Transaction
     |
     +---- Order
     |
     +---- Outbox Event

Then a background publisher:

Outbox
   |
   v
Service Bus

Architecture:

                  API
                   |
                   v
             SQL Transaction
              /           \
             /             \
            v               v
        Orders          OutboxEvents
                            |
                            v
                     Outbox Publisher
                            |
                            v
                       Service Bus
                            |
                 +----------+----------+
                 |                     |
                 v                     v
             Payment               Inventory

This helps ensure that the database change and event publication are not accidentally separated.


39. Retry Strategy

Suppose Service Bus consumer calls SQL:

Function
   |
   v
Azure SQL
   |
   X
Temporary failure

You might retry:

Attempt 1
   ↓
wait
Attempt 2
   ↓
wait
Attempt 3

Use exponential backoff where appropriate.

For example:

1 second
2 seconds
4 seconds
8 seconds

Don't retry permanent errors indefinitely.

For example:

400 Bad Request
Invalid message
Invalid business rule

usually shouldn't be blindly retried.


40. Poison Messages

A poison message is a message that repeatedly causes processing failures.

Example:

{
    "OrderId": -1,
    "Amount": -5000
}

Consumer:

Message
   |
Validation
   |
FAIL
   |
Retry
   |
FAIL
   |
Retry
   |
FAIL
   |
DLQ

Then support staff can investigate.


41. Service Bus + Azure Function

This is an extremely common architecture:

ASP.NET Core API
      |
      v
Service Bus
      |
      v
Azure Function
      |
      v
Process Order

Function:

[Function("ProcessOrder")]
public async Task Run(
    [ServiceBusTrigger(
        "orders",
        Connection = "ServiceBusConnection")]
    string message)
{
    var order =
        JsonSerializer.Deserialize<OrderCreatedEvent>(
            message);

    await _orderService.ProcessAsync(order!);
}

This is a very common Azure/.NET combination.


42. Service Bus + Multiple Services

Suppose one event:

OrderCreated

needs three consumers.

Use a topic:

                Order API
                    |
                    v
           OrderCreated Topic
                    |
       +------------+-------------+
       |            |             |
       v            v             v
 Payment Sub   Inventory Sub   Email Sub
       |            |             |
       v            v             v
Payment Service Inventory     Notification

Each subscription can independently process the event.


43. How do services communicate?

This is probably the most important part of your question.

They don't necessarily communicate directly.

Instead:

Service A

Publishes:

OrderCreated

to:

Service Bus Topic

Service B

subscribes:

PaymentSubscription

Service C

subscribes:

InventorySubscription

Service D

subscribes:

NotificationSubscription

So:

                  Event
                    |
                    v
              Service Bus
                    |
       +------------+------------+
       |            |            |
       v            v            v
   Payment      Inventory     Notification

That is event-driven communication.


44. Request/Response vs Event-Based Communication

You should know both.

Request/Response

Order Service
     |
     | HTTP Request
     v
Payment Service
     |
     | HTTP Response
     v
Order Service

The caller expects an immediate answer.

Event-Based

Order Service
     |
     | OrderCreated
     v
Service Bus
     |
     +---- Payment
     +---- Inventory
     +---- Notification

The producer announces:

"An order has been created."

Consumers decide what to do.


45. When should you NOT use Service Bus?

This is also important in interviews.

Don't introduce messaging unnecessarily.

For example:

GET /api/products/100

You don't need:

API → Service Bus → Product Service

A synchronous API call is more appropriate.

Service Bus makes sense when you need:

  • Asynchronous processing

  • Decoupling

  • Work queues

  • Event distribution

  • Resilience against temporary downstream failures

  • Traffic buffering


46. Service Bus vs RabbitMQ

You might get this question.

Azure Service Bus

Best when you're heavily invested in Azure and want a managed Azure messaging platform.

RabbitMQ

An open-source message broker that can be self-managed or hosted through various providers.

For an Azure-native enterprise application:

ASP.NET Core
     |
     v
Azure Service Bus

is often an attractive choice because of Azure integration and managed operations.


47. Service Bus vs Storage Queue

Service BusStorage Queue
Enterprise messagingSimpler queue
Topics/subscriptionsQueue-focused
Rich messaging featuresSimpler model
SessionsNo equivalent feature set
Dead letteringDifferent capabilities
Duplicate detectionRicher messaging support
TransactionsMore advanced messaging scenarios

Interview answer

"If I need simple asynchronous work distribution, Storage Queue may be sufficient. If I need enterprise messaging features, topics/subscriptions, advanced delivery handling and richer messaging semantics, I would consider Service Bus."


48. Lead-Level Architecture

A strong .NET Lead architecture might look like:

                         CLIENT
                           |
                           v
                    Azure API Management
                           |
                           v
                    ASP.NET Core APIs
                           |
                +----------+----------+
                |                     |
                v                     v
           Azure SQL            Service Bus
                                     |
                             OrderCreated Topic
                                     |
               +---------------------+--------------------+
               |                     |                    |
               v                     v                    v
         Payment Service      Inventory Service     Notification
               |                     |                    |
               v                     v                    v
          Payment DB            Inventory DB         Email/SMS

                          +----------------+
                          |                |
                          v                v
                       Key Vault       App Insights
                                           |
                                           v
                                      Azure Monitor

49. What Would I Say in a Lead Interview?

If the interviewer asks:

"How do you use Azure Service Bus in your architecture?"

A strong answer would be:

"I use Azure Service Bus primarily for asynchronous communication and decoupling between services. For point-to-point workloads, I use queues. When multiple services need to react to the same business event, I use topics and subscriptions. For example, after an OrderCreated event, Payment, Inventory and Notification services can independently consume the event. I design consumers to be idempotent, use retries for transient failures, dead-letter poison messages, and use correlation IDs for distributed tracing. For database-plus-message consistency, I would consider the Outbox Pattern."

That is a very strong Lead-level answer.


50. Top Azure Service Bus Interview Questions

Beginner

  1. What is Azure Service Bus?

  2. What is a message broker?

  3. What is a Service Bus namespace?

  4. What is a queue?

  5. What is a topic?

  6. What is a subscription?

  7. What is a producer?

  8. What is a consumer?

  9. What is a message?

  10. What is a trigger?

Intermediate

  1. Queue vs Topic?

  2. Service Bus vs Storage Queue?

  3. Synchronous vs asynchronous communication?

  4. What is dead-lettering?

  5. What is message lock?

  6. What is message completion?

  7. What is message abandonment?

  8. What is duplicate detection?

  9. What is message ordering?

  10. What are competing consumers?

Advanced

  1. How do you make a consumer idempotent?

  2. How do you handle poison messages?

  3. How do you implement retries?

  4. How do you handle Service Bus downtime?

  5. How do you prevent duplicate payment?

  6. How do you maintain database/message consistency?

  7. What is the Outbox Pattern?

  8. How do you monitor Service Bus?

  9. How do you scale consumers?

  10. How do you control consumer concurrency?

Lead/Architect

  1. Design an event-driven e-commerce system.

  2. When would you choose Service Bus over REST?

  3. When would you NOT use Service Bus?

  4. Queue vs Topic in microservices?

  5. How would you guarantee business-level idempotency?

  6. How do you handle ordering requirements?

  7. How would you handle 1 million messages?

  8. How would you handle a slow consumer?

  9. How would you prevent SQL from being overwhelmed?

  10. How would you design disaster recovery?

  11. How would you secure Service Bus?

  12. Managed Identity vs connection string?

  13. How would you trace one transaction across five services?

  14. How would you handle schema evolution?

  15. How would you handle backward compatibility of events?


51. The Most Important Architecture to Remember

If you remember only one diagram, remember this:

                    Angular
                       |
                       v
                API Management
                       |
                       v
                Order API
                       |
                 Save Order
                       |
                       v
              OrderCreated Event
                       |
                       v
              Azure Service Bus
                       |
                 Topic
                       |
       +---------------+---------------+
       |               |               |
       v               v               v
   Payment         Inventory      Notification
   Subscription   Subscription    Subscription
       |               |               |
       v               v               v
 Payment Service   Inventory       Email Service
                       |
                       v
                   Databases

And remember these five words:

Queue → Topic → Subscription → Retry → DLQ

For a .NET Lead interview, add these five:

Idempotency → Outbox → Correlation → Scaling → Observability

Together, these concepts cover a large portion of the Azure Service Bus questions you'll encounter in real-world .NET microservices interviews.

Azure Functions

Azure Functions — Complete .NET Lead Guide

Official Microsoft Azure Functions documentation

1. What is Azure Functions?

Azure Functions is a serverless, event-driven compute service.

In simple terms:

You write a C# method that performs a task, and Azure runs that method when a particular event occurs.

You don't need to manage the underlying server infrastructure yourself.

For example:

Customer places order
        ↓
Order API
        ↓
Service Bus Queue
        ↓
Azure Function
        ↓
Process Order
        ↓
Azure SQL

The Function could be responsible for:

  • Sending emails

  • Processing orders

  • Processing files

  • Generating reports

  • Running scheduled jobs

  • Processing Service Bus messages

  • Responding to HTTP requests

  • Processing queue messages

  • Reacting to Blob Storage events

Azure Functions supports triggers such as HTTP, timers, queues, Blob Storage, Service Bus and others.


2. Why Azure Functions?

Imagine your company needs a background process that runs whenever an order arrives.

Without Functions:

Create VM
   ↓
Install OS
   ↓
Install .NET
   ↓
Create Windows Service
   ↓
Configure service
   ↓
Monitor service
   ↓
Patch server
   ↓
Scale server

With Azure Functions:

Service Bus
     ↓
Azure Function
     ↓
Process Order

Azure handles much of the infrastructure.

That's why we call it serverless.


3. Important Azure Functions Terminology

You should understand these terms for a Lead interview.

Function

The actual piece of code that performs a task.

public void ProcessOrder()
{
    // Business logic
}

Trigger

The event that causes the Function to execute.

Examples:

HTTP Request
Timer
Service Bus Message
Queue Message
Blob Created
Event Grid Event

Binding

Bindings simplify communication between the Function and external services.

For example:

Function
   |
   +---- Input Binding
   |
   +---- Output Binding

Function App

A container/environment that hosts one or more Functions.

Function App
   |
   +---- ProcessOrder
   +---- SendEmail
   +---- GenerateReport

4. Trigger vs Binding

This is an important interview question.

Trigger

A trigger starts the Function.

Example:

Service Bus message arrives
             ↓
       Function starts

Binding

A binding connects the Function to another resource.

For example:

Function
   |
   +---- Input Binding → Blob
   |
   +---- Output Binding → Queue

Easy way to remember

Trigger = Why did my Function run?

Binding = What external resource does my Function interact with?


5. Real-Time Example — E-Commerce Order Processing

Let's design a real-world system.

Suppose a customer purchases a laptop.

Customer
   |
   v
Angular Application
   |
   v
ASP.NET Core Web API
   |
   v
Azure SQL
   |
   v
Service Bus
   |
   v
Azure Function

The API shouldn't necessarily perform every operation synchronously.

Instead:

POST /api/orders
       |
       v
Save Order
       |
       v
Publish Message
       |
       v
Service Bus
       |
       v
Azure Function
       |
       +---- Payment
       |
       +---- Inventory
       |
       +---- Email

This gives us:

  • Loose coupling

  • Asynchronous processing

  • Better scalability

  • Better resilience

  • Independent deployment

  • Better fault isolation


6. Create a Function in C#

For modern .NET development, Azure Functions supports the isolated worker model, which provides a process boundary between the Functions host and your application code.

Azure Functions .NET isolated worker model

A basic Function could look like:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

public class ProcessOrderFunction
{
    private readonly ILogger<ProcessOrderFunction> _logger;

    public ProcessOrderFunction(
        ILogger<ProcessOrderFunction> logger)
    {
        _logger = logger;
    }

    [Function("ProcessOrder")]
    public void Run(
        [TimerTrigger("0 */5 * * * *")] TimerInfo timer)
    {
        _logger.LogInformation(
            "Order processing function executed.");
    }
}

The important part is:

[TimerTrigger("0 */5 * * * *")]

This tells Azure Functions to execute based on a timer schedule.


7. Timer Trigger

Timer triggers are useful for scheduled jobs.

Example:

Every day at 1 AM
       ↓
Azure Function
       ↓
Find expired orders
       ↓
Update database

C#:

[Function("CleanupExpiredOrders")]
public async Task Run(
    [TimerTrigger("0 0 1 * * *")] TimerInfo timer)
{
    await CleanupOrdersAsync();
}

The CRON expression:

0 0 1 * * *

means approximately:

01:00 every day

8. HTTP Trigger

You can also expose a Function through HTTP.

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;

[Function("GetCustomer")]
public async Task<HttpResponseData> Run(
    [HttpTrigger(
        AuthorizationLevel.Function,
        "get",
        Route = "customers/{id}")]
    HttpRequestData req,
    int id)
{
    var response =
        req.CreateResponse(HttpStatusCode.OK);

    await response.WriteAsJsonAsync(
        new
        {
            Id = id,
            Name = "John"
        });

    return response;
}

The endpoint could be conceptually:

GET /api/customers/100

9. When should you use HTTP-triggered Functions?

Good scenarios:

Webhook
Small API endpoint
Event receiver
Lightweight integration endpoint

But don't automatically replace an entire ASP.NET Core Web API with Functions.

For a large REST API with complex middleware, filters, authentication, versioning and domain logic, ASP.NET Core Web API hosted on App Service/AKS may be more appropriate.

That's a good Lead-level answer.


10. Service Bus Trigger — Most Important Real-World Example

This is one of the most valuable Functions scenarios for a .NET developer.

Architecture:

ASP.NET Core API
       |
       v
Service Bus Queue
       |
       v
Azure Function
       |
       v
Process Order

The API sends a message:

{
    "orderId": 1001,
    "customerId": 501,
    "amount": 2500
}

The Function receives it.


11. C# Service Bus Trigger

Using the Azure Functions isolated worker model:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

public class OrderProcessorFunction
{
    private readonly ILogger<OrderProcessorFunction> _logger;

    public OrderProcessorFunction(
        ILogger<OrderProcessorFunction> logger)
    {
        _logger = logger;
    }

    [Function("ProcessOrder")]
    public async Task Run(
        [ServiceBusTrigger(
            "orders",
            Connection = "ServiceBusConnection")]
        string message)
    {
        _logger.LogInformation(
            "Received order message: {Message}",
            message);

        // Deserialize message
        // Validate order
        // Process order

        await Task.CompletedTask;
    }
}

12. Deserialize JSON

A better implementation:

public class OrderMessage
{
    public int OrderId { get; set; }

    public int CustomerId { get; set; }

    public decimal Amount { get; set; }
}

Then:

[Function("ProcessOrder")]
public async Task Run(
    [ServiceBusTrigger(
        "orders",
        Connection = "ServiceBusConnection")]
    string message)
{
    var order =
        JsonSerializer.Deserialize<OrderMessage>(message);

    if (order == null)
    {
        throw new InvalidOperationException(
            "Invalid order message.");
    }

    _logger.LogInformation(
        "Processing Order {OrderId}",
        order.OrderId);

    await ProcessOrderAsync(order);
}

13. Real-Time Flow

Imagine an online shopping system.

Customer buys:

Laptop
₹60,000

The API performs:

1. Validate order
2. Save order
3. Publish event

Then:

             Order API
                 |
                 v
         Azure Service Bus
                 |
                 v
       ProcessOrder Function
                 |
        +--------+--------+
        |        |        |
        v        v        v
     Payment  Inventory  Email

Now the API doesn't have to wait for all these operations.


14. Why Asynchronous Processing?

Imagine:

Payment = 2 seconds
Inventory = 1 second
Email = 3 seconds

Synchronous API:

API
 |
 +-- Payment 2 sec
 |
 +-- Inventory 1 sec
 |
 +-- Email 3 sec
 |
 v
Response after ~6 sec

With asynchronous processing:

API
 |
 v
Service Bus
 |
 v
Return response

Background processing happens separately.

This improves:

  • Response time

  • Scalability

  • Reliability

  • Fault isolation


15. Azure Function + SQL Database

A Function can use EF Core just like an ASP.NET Core application.

For example:

public class OrderDbContext : DbContext
{
    public DbSet<Order> Orders { get; set; }

    public OrderDbContext(
        DbContextOptions<OrderDbContext> options)
        : base(options)
    {
    }
}

Then inject it into your service.

public class OrderService
{
    private readonly OrderDbContext _context;

    public OrderService(OrderDbContext context)
    {
        _context = context;
    }

    public async Task ProcessAsync(int orderId)
    {
        var order = await _context.Orders
            .FirstOrDefaultAsync(x => x.Id == orderId);

        if (order == null)
            return;

        order.Status = "Processed";

        await _context.SaveChangesAsync();
    }
}

16. Important: Don't Create DbContext Incorrectly

Avoid repeatedly creating expensive resources inside the Function unnecessarily.

Prefer dependency injection and appropriate lifetime management.

For example:

Function
   |
   v
Service
   |
   v
Repository
   |
   v
DbContext
   |
   v
Azure SQL

17. Dependency Injection in Azure Functions

In isolated worker:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        services.AddScoped<IOrderService, OrderService>();

        services.AddDbContext<OrderDbContext>(
            options =>
                options.UseSqlServer(
                    Environment.GetEnvironmentVariable(
                        "SqlConnection")));
    })
    .Build();

host.Run();

Then:

public class ProcessOrderFunction
{
    private readonly IOrderService _orderService;

    public ProcessOrderFunction(
        IOrderService orderService)
    {
        _orderService = orderService;
    }
}

This is much cleaner than putting all business logic inside the Function class.


18. Recommended Architecture

Don't create:

Function
   |
   +-- 500 lines of business logic

Instead:

Azure Function
      |
      v
Application Service
      |
      v
Domain Logic
      |
      v
Repository
      |
      v
Azure SQL

For a Lead-level design, you could use:

Function
   ↓
Application Layer
   ↓
Domain Layer
   ↓
Infrastructure Layer

This aligns well with Clean Architecture principles.


19. Azure Function + Blob Storage

Another very common real-world example.

Customer uploads:

invoice.pdf

Architecture:

Customer
   |
   v
Blob Storage
   |
   | Blob Created
   v
Azure Function
   |
   +---- Validate PDF
   |
   +---- Extract metadata
   |
   +---- Save metadata to SQL
   |
   +---- Send message

This is a classic event-driven architecture.


20. Azure Function + Blob Trigger

Conceptually:

[Function("ProcessInvoice")]
public async Task Run(
    [BlobTrigger(
        "invoices/{name}",
        Connection = "StorageConnection")]
    Stream blob,
    string name)
{
    _logger.LogInformation(
        "Processing invoice {Name}",
        name);

    // Read/process file
}

21. Real-Time File Processing Example

Suppose a bank receives:

Customer_1001.pdf
Customer_1002.pdf
Customer_1003.pdf

Files arrive in Blob Storage.

Blob Storage
     |
     +---- Customer_1001.pdf
     +---- Customer_1002.pdf
     +---- Customer_1003.pdf
             |
             v
        Azure Function
             |
       +-----+------+
       |            |
       v            v
    Validate      Extract
                     |
                     v
                Azure SQL

This is especially useful for the type of file-processing architecture you've been discussing.


22. Function + Key Vault

Don't store secrets directly in code.

Bad:

var password = "MyPassword123";

Bad:

ConnectionStrings:
    SqlPassword=xxxxx

Better:

Azure Function
       |
       v
Managed Identity
       |
       v
Azure Key Vault
       |
       v
Secret

Microsoft recommends managed identities as a way for Azure resources to authenticate to other Azure services without having to manage credentials in application code.


23. Function + Application Insights

For production systems, logging is critical.

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

_logger.LogWarning(
    "Order {OrderId} has no payment",
    orderId);

_logger.LogError(
    exception,
    "Failed to process Order {OrderId}",
    orderId);

You can then investigate:

Application Insights
       |
       +--- Requests
       +--- Exceptions
       +--- Dependencies
       +--- Logs
       +--- Traces

24. Error Handling

Suppose:

Function
   |
   v
SQL
   |
  FAIL

Don't simply swallow the exception.

Bad:

try
{
    await ProcessOrderAsync();
}
catch
{
    // Nothing
}

Better:

try
{
    await ProcessOrderAsync();
}
catch (Exception ex)
{
    _logger.LogError(
        ex,
        "Order processing failed.");

    throw;
}

Why rethrow?

Because the trigger infrastructure needs to know that processing failed so the message can be handled according to the configured retry/dead-letter behavior.


25. Retry and Dead-Letter Queue

This is very important for interviews.

Imagine:

Service Bus
     |
     v
Function
     |
     v
SQL
     |
     X
Failure

The message can be retried according to the messaging configuration.

Conceptually:

Message
   |
Function
   |
Failure
   |
Retry
   |
Failure
   |
Retry
   |
Failure
   |
Dead Letter Queue

The DLQ is useful for messages that cannot be successfully processed after the configured delivery attempts.


26. Idempotency — Very Important Lead Concept

Suppose the same message is delivered twice:

OrderId = 1001

Function receives:

Message #1 → Order 1001
Message #2 → Order 1001

If your Function charges the customer twice, that's a serious problem.

So you need idempotency.

Example:

var alreadyProcessed =
    await _context.ProcessedMessages
        .AnyAsync(x => x.MessageId == messageId);

if (alreadyProcessed)
{
    return;
}

Then process and record the message ID.

MessageId
    |
    v
Already processed?
   / \
 Yes  No
 |     |
Stop   Process
       |
       v
   Save MessageId

Interview statement

In event-driven systems, I design consumers to be idempotent because duplicate delivery can occur and business operations should not be executed multiple times unintentionally.

That's a strong Lead-level answer.


27. Function Timeout

Functions have execution-time considerations that depend on the hosting plan and configuration.

Therefore, don't design a Function like:

Process 10 million records
        |
        v
One Function invocation

Instead:

10 million records
       |
       v
Queue
       |
+------+------+------+
|      |      |      |
F1     F2     F3     F4

Break large workloads into manageable units.


28. Function Scaling

One of the biggest benefits of serverless architecture is automatic scaling depending on the hosting model and trigger/workload.

Conceptually:

Low traffic

Queue
 |
 v
Function Instance 1

Heavy traffic:

Queue
 |
 +---- Function 1
 |
 +---- Function 2
 |
 +---- Function 3
 |
 +---- Function 4

This is particularly useful for burst workloads.


29. Azure Functions Hosting Plans

At interview level, know the major concepts:

  • Flex Consumption

  • Consumption

  • Premium

  • Dedicated/App Service

  • Container Apps hosting

The exact feature set and behavior varies by plan, so don't memorize simplistic statements such as "Functions always have a five-minute timeout."

Azure Functions hosting options

A Lead should instead say:

I choose the hosting plan based on execution duration, scaling behavior, networking requirements, performance requirements, cold-start sensitivity and cost.

That's a much better answer.


30. Cold Start

A common interview question.

A cold start occurs when a Function needs to initialize before processing an invocation after a period without activity or when a new instance is created.

Conceptually:

Request
   |
   v
No active instance
   |
   v
Start Function Host
   |
   v
Load application
   |
   v
Execute Function

This can add latency.

For latency-sensitive workloads, consider appropriate hosting options and architecture.


31. Azure Functions vs ASP.NET Core Web API

Azure FunctionsASP.NET Core Web API
Serverless/event-drivenGeneral-purpose API framework
Great for background processingExcellent for REST APIs
Trigger-basedHTTP request-based
Automatic scaling optionsYou manage application hosting/scaling
Good for integrationsGood for complex APIs
Pay model depends on hostingHosting cost model differs
Functions can be short-lived/event-orientedOften long-running API process

Lead answer

Don't say:

Functions are better than Web API.

Instead:

I choose based on workload characteristics.


32. Azure Functions vs Logic Apps

Another interview question.

Functions

Best when:

Custom code
Complex logic
C#
Business processing
Algorithmic operations

Logic Apps

Best when:

Workflow orchestration
SaaS integrations
Low-code integration
Connectors
Business workflows

Example:

Receive Email
   ↓
Save Attachment
   ↓
Send Teams Notification
   ↓
Update CRM

This may be suitable for Logic Apps.

But:

Calculate complex pricing
Validate business rules
Perform custom C# processing

Functions are more natural.


33. Azure Functions vs WebJobs

You may encounter this question in interviews.

WebJobs are background tasks associated with App Service.

Functions provide a more complete event-driven serverless programming model with triggers, bindings and scaling options.

For a new event-driven workload, Functions are often the natural consideration.


34. Azure Functions vs AKS

This is a Lead-level architecture question.

Choose Functions

When:

Event-driven
Short processing
Serverless
Variable workload
Minimal infrastructure management

Choose AKS

When:

Complex microservices
Containers
Kubernetes requirements
Advanced orchestration
Custom infrastructure/runtime needs

35. Real-Time Enterprise Architecture

Here's a good architecture to discuss during an interview:

                     Angular
                        |
                        v
               Azure API Management
                        |
                        v
               ASP.NET Core Web API
                        |
                 Azure App Service
                        |
            +-----------+-----------+
            |                       |
            v                       v
       Azure SQL              Service Bus
                                    |
                  +-----------------+----------------+
                  |                 |                |
                  v                 v                v
             Order Function   Payment Function  Notification
                  |                 |                |
                  +-----------------+----------------+
                                    |
                                    v
                              Blob Storage

                          Azure Key Vault
                                |
                         Managed Identity

                       Application Insights
                                |
                           Azure Monitor

                         Azure DevOps
                                |
                        CI/CD Deployment

Now imagine an interviewer asks:

"Why did you use Functions?"

You can answer:

"The order processing, payment integration and notification workflows are asynchronous and event-driven. Rather than coupling the API to all downstream services, I use Service Bus to decouple them and Azure Functions to process those messages independently. This improves resilience, allows independent scaling and prevents slow downstream operations from unnecessarily increasing API response time."

That's a Lead-level answer.


36. Lead-Level Interview Questions

Basic

Q1. What is Azure Functions?

Answer:

Azure Functions is a serverless, event-driven compute service used to execute code in response to events such as HTTP requests, timers, Service Bus messages, queues and storage events.


Q2. What is a trigger?

A trigger defines the event that causes a Function invocation.

Examples:

HTTP
Timer
Service Bus
Blob
Queue
Event Grid

Q3. What is a binding?

A binding provides a declarative way for a Function to connect to input or output data sources without writing all connection-handling code manually.


Q4. What is a Function App?

A Function App is the Azure resource that provides the execution environment and configuration boundary for one or more Functions.


37. Intermediate Interview Questions

Q5. What is the difference between Trigger and Binding?

Trigger starts the Function. Binding connects the Function to an external resource.


Q6. Can one Function App contain multiple Functions?

Yes.

Function App
   |
   +-- ProcessOrder
   +-- SendEmail
   +-- GenerateReport
   +-- CleanupData

Q7. How do you handle exceptions?

Use:

Logging
+
Retry
+
Dead-lettering
+
Monitoring
+
Alerting

and don't silently swallow failures.


Q8. How do you secure Function applications?

Use:

  • Managed Identity

  • Azure Key Vault

  • RBAC

  • HTTPS

  • Authentication/authorization

  • Network controls

  • Private endpoints where appropriate

  • Least privilege


Q9. How do you monitor Functions?

Use:

Application Insights
+
Azure Monitor
+
Logs
+
Metrics
+
Alerts

38. Advanced Lead-Level Questions

Q10. How do you prevent duplicate processing?

Use idempotency.

For example:

Message ID
     |
     v
ProcessedMessages table
     |
     +---- Exists → Don't process
     |
     +---- Doesn't exist → Process

Q11. How would you design a Function for high-volume processing?

Answer:

I would use an asynchronous messaging architecture, such as Service Bus, and allow Functions to scale based on workload. I would make the consumer idempotent, configure retries and dead-letter handling, avoid expensive per-invocation initialization, monitor dependency performance, and ensure downstream systems such as SQL can handle the resulting concurrency.

Excellent Lead-level answer.


39. Q12. What if SQL goes down?

Don't just say "retry."

A better answer:

Function
   |
   v
SQL
   |
   X
Unavailable
   |
   v
Retry transient failures
   |
   v
If still unavailable
   |
   v
Message remains available / retry mechanism
   |
   v
Dead Letter if delivery attempts exhausted

Then:

Azure Monitor
      |
      v
Alert
      |
      v
Operations team

40. Q13. What if the Function is processing the same order twice?

Answer:

I would use an idempotency mechanism based on a unique business/message identifier. Before executing a non-idempotent operation, I would verify whether that message or business operation has already been processed.


41. Q14. How do you handle long-running operations?

Don't blindly keep one Function invocation running.

Consider:

Queue
 ↓
Small work items
 ↓
Multiple Functions

For complex orchestration, consider Durable Functions.

Azure Durable Functions documentation


42. Durable Functions

Durable Functions help implement stateful workflows on top of Azure Functions.

For example:

Order
 |
 +--> Validate
 |
 +--> Payment
 |
 +--> Inventory
 |
 +--> Generate Invoice
 |
 +--> Send Email

Workflow:

Orchestrator
     |
     +---- Activity 1
     |
     +---- Activity 2
     |
     +---- Activity 3
     |
     +---- Activity 4

This is useful for complex workflows where you need orchestration and state management.


43. Q15. How would you implement a retry policy?

At a conceptual level:

Operation
   |
   X
Failure
   |
   v
Wait 1 sec
   |
 Retry
   |
   X
Failure
   |
   v
Wait 2 sec
   |
 Retry

Use exponential backoff for appropriate transient failures.

Don't retry everything.

For example:

401 Unauthorized     → Don't blindly retry
400 Bad Request      → Don't retry
Validation failure   → Don't retry
Transient DB failure → Consider retry
Temporary network failure → Consider retry

That's a strong interview answer.


44. Q16. How would you prevent a Function from overwhelming SQL?

This is a very good Lead question.

Suppose:

Service Bus
   |
   +---- Function 1
   +---- Function 2
   +---- Function 3
   +---- ...
   +---- Function 100

Now 100 Functions hit SQL simultaneously.

Potential problem:

SQL
 ↓
Connection exhaustion
 ↓
Blocking
 ↓
Timeouts

Solutions can include:

  • Control concurrency

  • Batch processing where appropriate

  • Optimize SQL

  • Connection pooling

  • Appropriate indexing

  • Retry with backoff

  • Queue-based throttling

  • Scale database appropriately

  • Monitor database DTU/vCore/resource metrics

  • Avoid unnecessarily expensive queries

That's an excellent Lead-level discussion.


45. Q17. How do you implement CI/CD for Functions?

Typical pipeline:

Developer
   |
   v
Azure Repos
   |
   v
Azure DevOps Pipeline
   |
   +---- Restore
   +---- Build
   +---- Unit Test
   +---- Code Analysis
   +---- Security Scan
   |
   v
Deploy to Dev
   |
   v
Integration Test
   |
   v
QA
   |
   v
Production

Use environment-specific configuration and Key Vault/managed identity rather than putting secrets into the repository.


46. Q18. What would you log?

Don't log everything.

Good:

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

Error:

_logger.LogError(
    exception,
    "Failed to process Order {OrderId}",
    orderId);

Avoid:

Passwords
Tokens
Credit card information
Sensitive personal data
Secrets

47. Q19. How would you troubleshoot a Function that isn't executing?

Use this checklist:

1. Check Function App status
2. Check trigger configuration
3. Check Service Bus / Storage
4. Check connection configuration
5. Check application logs
6. Check Application Insights
7. Check deployment
8. Check dependencies
9. Check authentication
10. Check networking
11. Check scaling/host configuration
12. Check recent code/configuration changes

48. Q20. How would you explain Azure Functions to a non-technical manager?

A great answer:

"Instead of continuously running a server just waiting for work, we can run small pieces of code only when a specific event occurs. For example, when a customer uploads an invoice, Azure can automatically execute our code to validate the invoice and store the results. Azure manages the infrastructure and can scale the processing based on demand."


49. Most Important Interview Scenario

Interviewer:

"We have an ASP.NET Core order API. When an order is created, we need to update inventory, process payment and send an email. How would you design this?"

Weak answer:

"I'll call three APIs from the controller."

Strong Lead answer:

                Order API
                    |
                    v
               Azure SQL
                    |
                    v
               Service Bus
                    |
          +---------+---------+
          |         |         |
          v         v         v
      Payment    Inventory   Email
      Function   Function    Function

Then explain:

"I would persist the order and publish an event to Service Bus. Separate Functions would consume the appropriate messages. This reduces coupling and allows each operation to scale independently. I would implement retries for transient failures, dead-letter handling for poison messages, idempotency for duplicate delivery, structured logging, Application Insights and Azure Monitor for observability, and Managed Identity/Key Vault for secure access."

That answer demonstrates architecture, scalability, resilience, security and observability — exactly what a Lead interviewer wants.


50. Final Azure Functions Interview Cheat Sheet

Remember this:

                    AZURE FUNCTIONS
                           |
            +--------------+--------------+
            |              |              |
         Trigger        Binding        Function
            |              |              |
        Starts it      Connects it      Logic
            |
   +--------+---------+
   |        |         |
 HTTP     Timer    Service Bus
   |        |         |
   +--------+---------+
            |
            v
       Business Logic
            |
      +-----+------+
      |            |
      v            v
   Azure SQL    Blob Storage
      |
      v
   Service Bus

And for production:

Azure Functions
      |
      +---- Managed Identity
      |
      +---- Key Vault
      |
      +---- Service Bus
      |
      +---- Azure SQL
      |
      +---- Blob Storage
      |
      +---- Application Insights
      |
      +---- Azure Monitor
      |
      +---- Azure DevOps

The 10 concepts I would absolutely prepare before your Lead interview

  1. Triggers and Bindings

  2. Consumption/Premium/Dedicated/Flex hosting concepts

  3. Cold starts

  4. Scaling and concurrency

  5. Service Bus + Functions

  6. Retries + Dead Letter Queue

  7. Idempotency

  8. Managed Identity + Key Vault

  9. Application Insights + troubleshooting

  10. Durable Functions + orchestration

If you can explain those 10 concepts with the e-commerce example above, you will be in a much stronger position for Azure Functions Lead-level scenario questions.

Don't Copy

Protected by Copyscape Online Plagiarism Checker