Thursday, August 20, 2026

Saga Design Pattern – Complete Guide with E-Commerce Example

1. What Problem Does Saga Solve?

Imagine an e-commerce application with these microservices:

                    E-Commerce Application
                            |
        +-------------------+-------------------+
        |                   |                   |
   Order Service       Payment Service     Inventory Service
        |                   |                   |
        +-------------------+-------------------+
                            |
                    Shipping Service

A customer places an order.

The business process might be:

Create Order
    ↓
Reserve Inventory
    ↓
Process Payment
    ↓
Create Shipment
    ↓
Order Completed

The problem is that each operation belongs to a different database.

For example:

Order Service       → OrderDB
Inventory Service   → InventoryDB
Payment Service     → PaymentDB
Shipping Service    → ShippingDB

We cannot normally use a single SQL transaction such as:

BEGIN TRANSACTION

OrderDB
InventoryDB
PaymentDB
ShippingDB

COMMIT

because these are independent microservices.

This is where Saga Pattern comes in.


2. What Is Saga Design Pattern?

A Saga is a sequence of local transactions where each microservice performs its own transaction.

If one transaction fails, previously completed transactions are compensated by executing corresponding compensating transactions.

Conceptually:

Transaction 1
     ↓
Transaction 2
     ↓
Transaction 3
     ↓
Transaction 4

If Transaction 3 fails:

Transaction 1 ✓
Transaction 2 ✓
Transaction 3 ✗

        ↓

Compensation 2
        ↓
Compensation 1

So instead of a traditional distributed ACID transaction, Saga provides eventual consistency using local transactions + compensation.


3. E-Commerce Example

Suppose customer places an order:

Order #1001

Product: Laptop
Quantity: 1
Price: ₹80,000

The workflow is:

Customer
   |
   ↓
Order Service
   |
   ↓
Inventory Service
   |
   ↓
Payment Service
   |
   ↓
Shipping Service
   |
   ↓
Order Completed

Let's define the transactions.

T1 – Create Order

Order Service:

Order Status = Pending

T2 – Reserve Inventory

Inventory Service:

Laptop Stock
100 → 99

T3 – Process Payment

Payment Service:

₹80,000 charged

T4 – Create Shipment

Shipping Service:

Shipment Created

Finally:

Order Status = Confirmed

4. What Happens If Payment Fails?

Suppose:

T1 Create Order        ✓
T2 Reserve Inventory   ✓
T3 Payment             ✗

We cannot simply rollback T1 and T2 using a normal database rollback because they happened in different databases.

Instead:

Payment Failed
      ↓
Release Inventory
      ↓
Cancel Order

So:

T1 Create Order ✓
       ↓
T2 Reserve Stock ✓
       ↓
T3 Payment ✗
       ↓
C2 Release Stock ✓
       ↓
C1 Cancel Order ✓

This is the core concept of Saga.


5. Saga Has Two Main Approaches

There are two major implementations.

Approach 1 – Choreography

Services communicate through events.

Order Service
     |
 OrderCreated
     ↓
Inventory Service
     |
InventoryReserved
     ↓
Payment Service
     |
PaymentCompleted
     ↓
Shipping Service

There is no central coordinator.


Approach 2 – Orchestration

A central Saga Orchestrator controls the workflow.

                 Saga Orchestrator
                        |
          +-------------+-------------+
          |             |             |
          ↓             ↓             ↓
      Order          Inventory      Payment
      Service         Service       Service
                                      |
                                      ↓
                                  Shipping

The orchestrator says:

Reserve inventory

then:

Process payment

then:

Create shipment

If something fails:

Release inventory
Cancel order

For an enterprise e-commerce application, orchestration is often easier to understand and manage, especially when the workflow becomes complex.


6. Which One Should We Use?

FeatureChoreographyOrchestration
Central controllerNoYes
Simple workflowsExcellentGood
Complex workflowsDifficultExcellent
DebuggingDifficultEasier
Business workflow visibilityLowerHigher
CouplingEvent-basedOrchestrator-based
Failure handlingDistributedCentralized
Large enterprise workflowsCan become complicatedOften preferable

For the example below, I'll use Saga Orchestration.


7. Overall Architecture

Let's design the system.

                         Client
                           |
                           ↓
                    API Gateway
                           |
                           ↓
                    Order Service
                           |
                           ↓
                  Saga Orchestrator
                           |
          +----------------+----------------+
          |                |                |
          ↓                ↓                ↓
     Inventory          Payment          Shipping
      Service           Service           Service
          |                |                |
      InventoryDB       PaymentDB       ShippingDB

Communication could use:

Azure Service Bus
Kafka
RabbitMQ

For an Azure-based .NET system, Azure Service Bus is a natural choice.


8. Database Design

An important Saga principle is:

Each microservice owns its own database.

Don't do this:

Order Service
       |
       ↓
Shared Database
       ↑
       |
Inventory Service

Instead:

Order Service
     ↓
OrderDB

Inventory Service
     ↓
InventoryDB

Payment Service
     ↓
PaymentDB

Shipping Service
     ↓
ShippingDB

9. Order Model

Order Service might have:

public class Order
{
    public Guid Id { get; set; }

    public Guid CustomerId { get; set; }

    public decimal TotalAmount { get; set; }

    public OrderStatus Status { get; set; }

    public DateTime CreatedAt { get; set; }
}

Status:

public enum OrderStatus
{
    Pending,
    InventoryReserved,
    PaymentProcessing,
    Confirmed,
    Failed,
    Cancelled
}

10. Order Items

public class OrderItem
{
    public Guid Id { get; set; }

    public Guid OrderId { get; set; }

    public Guid ProductId { get; set; }

    public int Quantity { get; set; }

    public decimal Price { get; set; }
}

11. Inventory Model

Inventory Service owns:

public class Inventory
{
    public Guid ProductId { get; set; }

    public int AvailableQuantity { get; set; }

    public int ReservedQuantity { get; set; }
}

Example:

Product       Available     Reserved

Laptop          100            0

After reservation:

Laptop           99            1

12. Inventory Reservation Model

We should maintain a separate reservation record.

public class InventoryReservation
{
    public Guid Id { get; set; }

    public Guid OrderId { get; set; }

    public Guid ProductId { get; set; }

    public int Quantity { get; set; }

    public ReservationStatus Status { get; set; }
}

Status:

public enum ReservationStatus
{
    Reserved,
    Released
}

Why?

Because Saga requires us to know:

What exactly should I compensate?


13. Payment Model

Payment Service:

public class Payment
{
    public Guid Id { get; set; }

    public Guid OrderId { get; set; }

    public decimal Amount { get; set; }

    public PaymentStatus Status { get; set; }

    public string TransactionReference { get; set; }
}

Status:

public enum PaymentStatus
{
    Pending,
    Completed,
    Failed,
    Refunded
}

14. Shipment Model

Shipping Service:

public class Shipment
{
    public Guid Id { get; set; }

    public Guid OrderId { get; set; }

    public string Address { get; set; }

    public ShipmentStatus Status { get; set; }
}

15. Saga State Model

The orchestrator should maintain Saga state.

For example:

public class OrderSaga
{
    public Guid SagaId { get; set; }

    public Guid OrderId { get; set; }

    public SagaStatus Status { get; set; }

    public bool OrderCreated { get; set; }

    public bool InventoryReserved { get; set; }

    public bool PaymentCompleted { get; set; }

    public bool ShipmentCreated { get; set; }

    public DateTime CreatedAt { get; set; }

    public DateTime UpdatedAt { get; set; }
}

This becomes very useful for:

  • monitoring

  • retries

  • recovery

  • debugging

  • compensation


16. Complete Saga Flow

Let's look at the complete process.

Customer
   |
   | Place Order
   ↓
Order Service
   |
   | Order Created
   ↓
Saga Orchestrator
   |
   | Reserve Inventory
   ↓
Inventory Service
   |
   | Inventory Reserved
   ↓
Saga Orchestrator
   |
   | Process Payment
   ↓
Payment Service
   |
   | Payment Completed
   ↓
Saga Orchestrator
   |
   | Create Shipment
   ↓
Shipping Service
   |
   | Shipment Created
   ↓
Saga Orchestrator
   |
   ↓
Order Confirmed

17. Step 1 – Customer Creates Order

Client:

POST /api/orders

Request:

{
  "customerId": "C001",
  "items": [
    {
      "productId": "P100",
      "quantity": 1
    }
  ]
}

Order Service creates:

OrderId = 1001
Status = Pending

Database:

Orders

1001 | C001 | 80000 | Pending

Then publish:

OrderCreated

Event:

public record OrderCreatedEvent(
    Guid OrderId,
    Guid CustomerId,
    decimal Amount);

18. Step 2 – Saga Starts

The orchestrator receives:

OrderCreated

It creates:

SagaId = S1001
OrderId = 1001
Status = Started

Then sends:

ReserveInventory

19. Step 3 – Inventory Reservation

Inventory Service receives:

{
  "sagaId": "S1001",
  "orderId": "1001",
  "productId": "P100",
  "quantity": 1
}

It executes a local database transaction.

For example:

BEGIN TRANSACTION

Check available stock

Available = Available - 1

Create Reservation

COMMIT

Database becomes:

Available = 99
Reserved = 1

Then publish:

InventoryReserved

20. Step 4 – Payment

Saga orchestrator receives:

InventoryReserved

Then sends:

ProcessPayment

Payment Service:

BEGIN TRANSACTION

Create Payment
Status = Processing

Call payment provider

Payment successful

Status = Completed

COMMIT

Then:

PaymentCompleted

21. Step 5 – Shipping

Saga receives:

PaymentCompleted

Then:

CreateShipment

Shipping Service creates:

ShipmentId = SH1001
OrderId = 1001
Status = Created

Then publishes:

ShipmentCreated

22. Step 6 – Complete Saga

Saga Orchestrator receives:

ShipmentCreated

Now:

OrderCreated       ✓
InventoryReserved  ✓
PaymentCompleted   ✓
ShipmentCreated    ✓

So:

Saga Status = Completed

And Order Service is instructed:

ConfirmOrder

Order:

1001 | Confirmed

23. What Happens When Payment Fails?

This is where Saga becomes interesting.

Suppose:

Order Created       ✓
Inventory Reserved  ✓
Payment             ✗

The orchestrator receives:

PaymentFailed

It knows:

InventoryReserved = true
PaymentCompleted = false

Therefore compensation is required.


24. Compensation Flow

The orchestrator sends:

ReleaseInventory

Inventory Service:

BEGIN TRANSACTION

Available = Available + 1

Reservation.Status = Released

COMMIT

Now:

Available = 100
Reserved = 0

Then orchestrator sends:

CancelOrder

Order Service:

Order.Status = Cancelled

Final state:

Order       = Cancelled
Inventory   = Released
Payment     = Failed
Saga        = Compensated

25. Important Point – Compensation Is NOT Rollback

This is one of the most important interview concepts.

Traditional transaction:

BEGIN

Operation A
Operation B
Operation C

ROLLBACK

Saga:

Operation A
Operation B
Operation C → FAILED

Compensation B
Compensation A

There is no global database rollback.

Instead:

A compensating transaction semantically reverses the business effect of a previous transaction.


26. Example: Payment Succeeds but Shipping Fails

Consider:

Order        ✓
Inventory    ✓
Payment      ✓
Shipping     ✗

Now we need to compensate.

Possible sequence:

Shipping Failed
       ↓
Refund Payment
       ↓
Release Inventory
       ↓
Cancel Order

So:

T1 Create Order       ✓
T2 Reserve Inventory  ✓
T3 Payment            ✓
T4 Shipping           ✗

C3 Refund Payment     ✓
C2 Release Inventory  ✓
C1 Cancel Order       ✓

Final:

Order = Cancelled
Inventory = Released
Payment = Refunded
Shipping = Failed

27. What If Compensation Also Fails?

This is a very important real-world scenario.

Suppose:

Payment Failed
      ↓
Release Inventory
      ↓
Inventory Service FAILED

Now:

Order = Pending
Inventory = Reserved
Payment = Failed

We cannot simply give up.

The Saga must retry the compensation.

ReleaseInventory
      ↓
FAILED
      ↓
Retry
      ↓
FAILED
      ↓
Retry
      ↓
SUCCESS

Therefore Saga implementations need:

  • Retry

  • Dead-letter queue

  • Idempotency

  • Timeout

  • Monitoring

  • Manual recovery


28. Retry Strategy

For example:

Attempt 1
   ↓
5 seconds
   ↓
Attempt 2
   ↓
30 seconds
   ↓
Attempt 3
   ↓
5 minutes

This is called exponential backoff.

For Azure Service Bus, failed messages can eventually be moved to a dead-letter queue.


29. Idempotency Is Extremely Important

Suppose:

ReserveInventory

message is delivered twice.

Without idempotency:

Message 1 → Reserve 1 item
Message 2 → Reserve another item

Incorrect:

Stock: 100 → 98

But we wanted:

Stock: 100 → 99

Therefore every command should have a unique identifier.

Example:

public class ProcessedMessage
{
    public Guid MessageId { get; set; }

    public DateTime ProcessedAt { get; set; }
}

Before processing:

Has MessageId already been processed?

If yes:

Ignore

Otherwise:

Process
Save MessageId

30. Better Idempotency Model

Instead of only MessageId, use a business operation ID.

Example:

SagaId = S1001
OrderId = 1001
Operation = ReserveInventory

Create unique constraint:

(SagaId, Operation)

Then duplicate commands cannot create duplicate reservations.


31. Transactional Outbox Pattern

There is another major problem.

Suppose Order Service does:

BEGIN TRANSACTION

Insert Order

COMMIT

Then:

Publish OrderCreated

What if the application crashes between these operations?

Database Insert ✓
Publish Event ✗

Now the order exists but Saga never receives the event.

This is where Transactional Outbox Pattern is commonly combined with Saga.


32. Outbox Table

Order Service database:

Orders
OutboxMessages

When creating the order:

BEGIN TRANSACTION

INSERT INTO Orders

INSERT INTO OutboxMessages

COMMIT

Both happen in the same local database transaction.

Example:

Orders

OrderId = 1001
Status = Pending

And:

OutboxMessages

MessageId = M1001
Type = OrderCreated
Payload = {...}
Published = false

A background publisher then reads:

Published = false

and sends the message.

After successful publishing:

Published = true

This greatly improves reliability.


33. Saga + Outbox Architecture

A robust architecture becomes:

                         Saga Orchestrator
                                |
                         Message Broker
                                |
          +---------------------+---------------------+
          |                     |                     |
          ↓                     ↓                     ↓
      Order Service        Inventory Service      Payment
          |                     |                     |
       OrderDB              InventoryDB           PaymentDB
          |                     |                     |
       Outbox                 Outbox                Outbox
          |                     |                     |
          +---------------------+---------------------+
                                |
                         Azure Service Bus

34. Commands vs Events

This distinction is important.

Command

A command tells another service:

Do something.

Examples:

CreateOrder
ReserveInventory
ProcessPayment
CreateShipment
RefundPayment
ReleaseInventory
CancelOrder

Event

An event says:

Something happened.

Examples:

OrderCreated
InventoryReserved
InventoryReservationFailed
PaymentCompleted
PaymentFailed
ShipmentCreated
ShipmentFailed

35. Example Command

public record ReserveInventoryCommand(
    Guid MessageId,
    Guid SagaId,
    Guid OrderId,
    Guid ProductId,
    int Quantity);

36. Example Event

public record InventoryReservedEvent(
    Guid MessageId,
    Guid SagaId,
    Guid OrderId);

Failure:

public record InventoryReservationFailedEvent(
    Guid MessageId,
    Guid SagaId,
    Guid OrderId,
    string Reason);

37. Saga State Machine

The orchestrator can be modeled as a state machine.

             OrderCreated
                  |
                  ↓
          InventoryPending
                  |
        +---------+---------+
        |                   |
     Success              Failure
        |                   |
        ↓                   ↓
 PaymentPending        CancelOrder
        |
   +----+----+
   |         |
Success     Failure
   |         |
   ↓         ↓
Shipping   ReleaseInventory
Pending       |
   |          ↓
Success    CancelOrder
   |
   ↓
Completed

This is a very good way to explain Saga in an interview.


38. Orchestrator Pseudocode

Conceptually:

public async Task Handle(OrderCreatedEvent message)
{
    await ReserveInventory(message);
}

When inventory succeeds:

public async Task Handle(InventoryReservedEvent message)
{
    await ProcessPayment(message);
}

Payment succeeds:

public async Task Handle(PaymentCompletedEvent message)
{
    await CreateShipment(message);
}

Shipment succeeds:

public async Task Handle(ShipmentCreatedEvent message)
{
    await ConfirmOrder(message);
}

Payment fails:

public async Task Handle(PaymentFailedEvent message)
{
    await ReleaseInventory(message);
    await CancelOrder(message);
}

39. Compensation Table

A useful way to design a Saga is to create a compensation matrix.

Forward TransactionCompensation
Create OrderCancel Order
Reserve InventoryRelease Inventory
Process PaymentRefund Payment
Create ShipmentCancel Shipment
Apply CouponRestore Coupon
Allocate Loyalty PointsReturn Loyalty Points

For every business transaction, ask:

If this succeeds and something later fails, how do I undo its business effect?

If you cannot answer that, your Saga design isn't complete.


40. Data Consistency

A common question is:

How does Saga maintain data consistency?

It does not provide immediate strong consistency across all databases like a single ACID transaction.

Instead it provides:

Eventual Consistency

For example:

Initially:

Order = Pending
Inventory = Reserved
Payment = Processing

After processing:

Order = Confirmed
Inventory = Reserved
Payment = Completed

Or if failure occurs:

Order = Cancelled
Inventory = Released
Payment = Failed

The system may temporarily have intermediate states, but eventually it reaches a valid business state.


41. Important: Don't Compensate Everything Blindly

Suppose:

Inventory reserved
Payment completed
Shipping failed

You shouldn't simply execute compensation commands without knowing the actual state.

Maintain Saga state:

InventoryReserved = true
PaymentCompleted = true
ShipmentCreated = false

Then compensation is based on completed steps.

if PaymentCompleted
    RefundPayment()

if InventoryReserved
    ReleaseInventory()

if OrderCreated
    CancelOrder()

42. Timeout Handling

Suppose Payment Service doesn't respond.

Payment Request
      ↓
Waiting...
      ↓
Waiting...
      ↓
Timeout

The orchestrator should not wait forever.

For example:

Payment timeout = 5 minutes

Then:

Payment Timeout
      ↓
Check payment status
      ↓
If unknown → retry/query provider
      ↓
If definitely failed → compensate

This is especially important with external payment gateways.


43. Why Payment Status Needs Special Care

Imagine:

Payment Service → Payment Gateway

Payment request is sent.

Gateway processes it.

But response is lost.

Your service sees:

Timeout

You must not automatically refund or retry blindly because the first payment might actually have succeeded.

You may accidentally charge the customer twice.

Instead use:

Idempotency Key

For example:

OrderId = 1001
PaymentAttempt = 1
IdempotencyKey = ORDER-1001-PAYMENT

The payment provider should treat repeated requests with the same key as the same logical operation where its API supports idempotency.


44. Handling Concurrent Orders

Suppose only one laptop remains.

Stock = 1

Two customers simultaneously order.

Customer A → Reserve
Customer B → Reserve

Inventory Service must use appropriate concurrency control.

For example:

UPDATE Inventory
SET AvailableQuantity = AvailableQuantity - 1
WHERE ProductId = @ProductId
AND AvailableQuantity >= 1;

Then check:

Rows affected = 1

Reservation succeeds.

If:

Rows affected = 0

reservation fails.

This prevents overselling.


45. Saga Failure Scenarios

Scenario 1

Order ✓
Inventory ✓
Payment ✓
Shipping ✓

Result:

Completed

Scenario 2

Order ✓
Inventory ✗

Compensation:

Cancel Order

Scenario 3

Order ✓
Inventory ✓
Payment ✗

Compensation:

Release Inventory
Cancel Order

Scenario 4

Order ✓
Inventory ✓
Payment ✓
Shipping ✗

Compensation:

Refund Payment
Release Inventory
Cancel Order

Scenario 5

Compensation fails

Solution:

Retry
 ↓
Retry
 ↓
Dead Letter Queue
 ↓
Operational Alert
 ↓
Manual Recovery

46. Azure Implementation

Since you're working with Azure/.NET, one possible architecture is:

ASP.NET Core
      |
      ↓
Order Service
      |
      ↓
Azure Service Bus
      |
      ↓
Saga Orchestrator
      |
      +----------------+
      |                |
      ↓                ↓
Inventory          Payment
Service            Service
      |                |
      ↓                ↓
 Azure SQL          Azure SQL

And:

Shipping Service
       |
       ↓
   Azure SQL

For monitoring:

Application Insights
Azure Monitor

For secrets:

Azure Key Vault

47. Azure Service Bus Structure

You might design:

Topic: ecommerce-events

Subscriptions:

order
inventory
payment
shipping
saga

Or use separate command queues:

inventory-commands
payment-commands
shipping-commands
order-commands

For orchestration, a command queue per service plus an event topic is often a clean conceptual model.


48. Message Flow

Example:

Order Service
     |
     | OrderCreated
     ↓
Service Bus
     |
     ↓
Saga Orchestrator
     |
     | ReserveInventory
     ↓
Inventory Queue
     |
     ↓
Inventory Service
     |
     | InventoryReserved
     ↓
Service Bus
     |
     ↓
Saga
     |
     | ProcessPayment
     ↓
Payment Queue

And so on.


49. Database Transactions Are Still Used

This is another important point.

Saga does not mean:

Don't use database transactions.

Each microservice should still use normal local transactions.

For example:

Inventory Service

BEGIN TRANSACTION

UPDATE Inventory

INSERT Reservation

INSERT OutboxMessage

COMMIT

This is a local ACID transaction.

Saga coordinates these local transactions.


50. The Golden Rule

Think about Saga like this:

Saga
 =
Multiple Local Transactions
 +
Messages
 +
State Machine
 +
Compensating Transactions
 +
Retry
 +
Idempotency
 +
Timeout Handling
 +
Observability

That is a much more accurate real-world definition than simply saying:

Saga is rollback for microservices.

It is not a distributed rollback mechanism.


51. Complete E-Commerce Flow

Here's the complete picture:

                         CUSTOMER
                            |
                            ↓
                       API Gateway
                            |
                            ↓
                     ORDER SERVICE
                            |
                       Create Order
                            |
                            ↓
                      OrderCreated
                            |
                            ↓
                   SAGA ORCHESTRATOR
                            |
                    Reserve Inventory
                            |
                            ↓
                   INVENTORY SERVICE
                            |
                   Inventory Reserved
                            |
                            ↓
                   SAGA ORCHESTRATOR
                            |
                     Process Payment
                            |
                            ↓
                    PAYMENT SERVICE
                            |
                     Payment Success
                            |
                            ↓
                   SAGA ORCHESTRATOR
                            |
                     Create Shipment
                            |
                            ↓
                   SHIPPING SERVICE
                            |
                    Shipment Created
                            |
                            ↓
                   SAGA ORCHESTRATOR
                            |
                            ↓
                     Confirm Order

Failure:

Payment Failed
      |
      ↓
Saga Orchestrator
      |
      +------→ Release Inventory
      |
      +------→ Cancel Order
      |
      ↓
Saga Compensated

52. Production-Grade Saga Checklist

When implementing Saga in a real application, consider all of these:

  • Saga ID

  • Correlation ID

  • Message ID

  • Idempotency

  • Saga state persistence

  • Local database transactions

  • Transactional Outbox

  • Reliable messaging

  • Retries

  • Exponential backoff

  • Timeouts

  • Dead-letter queues

  • Compensating transactions

  • Concurrency control

  • Optimistic/pessimistic locking where appropriate

  • Observability

  • Distributed tracing

  • Audit logging

  • Manual recovery

  • Poison message handling


53. Saga vs Two-Phase Commit

A common interview question is:

2PC

Coordinator
    |
    +--- DB1
    +--- DB2
    +--- DB3

Prepare
Prepare
Prepare

Commit
Commit
Commit

It attempts to provide distributed transactional atomicity, but can introduce blocking, coordination overhead, and operational complexity.

Saga:

Local Transaction
      ↓
Message
      ↓
Local Transaction
      ↓
Message

Failure:

Compensating Transaction

Saga is generally better suited to independently deployable microservices where business operations can be compensated.


54. Interview Answer

If an interviewer asks:

"Explain Saga Design Pattern with an e-commerce example."

A strong answer would be:

"Saga is a distributed transaction pattern used in microservices where a business transaction is divided into a sequence of local transactions. Each service commits its own transaction independently. If a later transaction fails, the Saga executes compensating transactions for the previously completed operations.

For example, in an e-commerce system, placing an order may involve creating the order, reserving inventory, processing payment, and creating a shipment. If payment fails after inventory has been reserved, the Saga doesn't perform a database rollback across services. Instead, it executes a compensating transaction to release the inventory and then cancels the order.

Saga can be implemented using choreography, where services communicate through events, or orchestration, where a central Saga orchestrator manages the workflow. In a production system, I would also use an outbox pattern, idempotent message processing, retries, timeouts, dead-letter queues, correlation IDs, and persistent Saga state to achieve reliable eventual consistency."


55. Recommended .NET Architecture

For a production .NET implementation, I would structure it approximately like this:

src
│
├── OrderService
│   ├── Controllers
│   ├── Domain
│   ├── Application
│   ├── Infrastructure
│   └── Messaging
│
├── InventoryService
│   ├── Domain
│   ├── Application
│   ├── Infrastructure
│   └── Messaging
│
├── PaymentService
│   ├── Domain
│   ├── Application
│   ├── Infrastructure
│   └── Messaging
│
├── ShippingService
│   ├── Domain
│   ├── Application
│   ├── Infrastructure
│   └── Messaging
│
└── OrderSaga
    ├── StateMachine
    ├── Commands
    ├── Events
    ├── Consumers
    └── Persistence

A particularly robust combination is:

Microservices
     +
Saga Orchestration
     +
Azure Service Bus
     +
Transactional Outbox
     +
Idempotent Consumers
     +
Retry/Timeout
     +
Dead Letter Queue
     +
Azure SQL
     +
Application Insights

The key idea to remember is:

Saga does not make multiple databases behave like one database. It coordinates independent local transactions and uses compensating actions to bring the overall business process to a consistent state.


Azure AI Search: Complete Guide with a Real-Time .NET Example

 

Introduction

Modern applications generate and consume enormous amounts of information—PDFs, Word documents, web pages, product catalogs, support tickets, database records, manuals, and knowledge-base articles.

Traditional database queries work well when users know the exact keywords they are looking for. But modern applications increasingly need to understand meaning and intent, not just exact words.

This is where Azure AI Search becomes extremely useful.

Azure AI Search is a managed search and retrieval service from Microsoft Azure that supports traditional full-text search, vector search, hybrid search, semantic ranking, and generative-AI/RAG scenarios. (Microsoft Learn)

A typical modern architecture looks like this:

                User
                  |
                  v
        Angular / Web / Mobile
                  |
                  v
          ASP.NET Core API
                  |
        +---------+---------+
        |                   |
        v                   v
 Azure AI Search       Azure OpenAI
        |                   |
        |<--- Context ------|
        |
        v
   Search Results
        |
        +--------> LLM
                    |
                    v
              Final Answer

This article explains Azure AI Search from the fundamentals through an end-to-end ASP.NET Core + Azure AI Search + Azure OpenAI RAG application.


1. What Is Azure AI Search?

Azure AI Search is Microsoft's cloud-based search-as-a-service platform.

It allows applications to:

  • Store searchable documents

  • Search text

  • Search using keywords

  • Search by semantic meaning

  • Perform vector similarity searches

  • Perform hybrid searches

  • Apply filters

  • Sort and facet results

  • Re-rank search results using semantic ranking

  • Retrieve grounding information for RAG applications

Microsoft documentation currently describes Azure AI Search as supporting text, vector, and multimodal content for traditional and generative search scenarios. (Microsoft Learn)

Think of it as:

Traditional Database
        |
        | Exact data retrieval
        v
     SQL Query

Azure AI Search
        |
        | Intelligent information retrieval
        v
 Keyword + Semantic + Vector + Hybrid Search

2. Why Do We Need Azure AI Search?

Suppose a company has:

100,000 PDF documents
50,000 Word documents
1 million support tickets
500,000 product descriptions

A user asks:

"How can I reset my corporate VPN password?"

A traditional SQL query might search for:

WHERE Description LIKE '%VPN%'
AND Description LIKE '%password%'

But the user could ask:

"I forgot the credentials needed to connect remotely."

The words are completely different.

A semantic/vector search engine can recognize that:

"forgot credentials"

is related to:

"reset VPN password"

This is one of the major advantages of vector and semantic search.


3. Azure AI Search vs SQL Server

Azure AI Search does not replace SQL Server.

They solve different problems.

SQL ServerAzure AI Search
Transactional dataSearch/retrieval
INSERT/UPDATE/DELETEIndexing/search
RelationshipsSearch indexes
JoinsSearch queries
ACID transactionsRelevance ranking
Structured dataText/vector content
Business transactionsInformation retrieval

A common architecture is:

SQL Server
   |
   | Product / Customer / Order data
   |
   v
ASP.NET Core
   |
   +------> SQL Server
   |
   +------> Azure AI Search

4. Important Azure AI Search Concepts

Before implementing Azure AI Search, understand these concepts.

4.1 Search Service

The Azure AI Search service is the Azure resource that provides the search engine.

For example:

my-company-search.search.windows.net

Applications communicate with this service through:

  • REST API

  • Azure SDK

  • .NET SDK

  • Python SDK

  • JavaScript/TypeScript SDK

  • Java SDK

Microsoft provides official SDKs and samples for these languages. (Microsoft Learn)


5. Search Index

A search index is similar conceptually to a database table, but it is designed specifically for search.

For example:

ProductIndex

could contain:

ProductId
ProductName
Description
Category
Price
Availability
DescriptionVector

Example:

{
  "ProductId": "P1001",
  "ProductName": "Laptop",
  "Description": "Business laptop with 16GB RAM",
  "Category": "Computer",
  "Price": 75000
}

6. Search Fields

Each index contains fields.

For example:

ProductId
ProductName
Description
Category
Price
DescriptionVector

Different fields can have different capabilities.

For example:

ProductName
    searchable

Description
    searchable

Category
    filterable

Price
    filterable
    sortable

DescriptionVector
    vector searchable

7. Documents

A document represents one searchable item inside an index.

For example:

{
    "id": "101",
    "title": "Azure AI Search",
    "content": "Azure AI Search provides intelligent search capabilities.",
    "category": "Azure"
}

Another document might represent:

PDF chunk
Product
Customer FAQ
Support ticket
Knowledge-base article
Web page

8. Full-Text Search

Traditional full-text search searches words contained in documents.

For example:

Search:
Azure Service Bus

Azure AI Search looks for matching terms in searchable fields.

This approach is particularly useful for:

  • Product codes

  • Names

  • Exact terminology

  • IDs

  • Dates

  • Specialized technical terms

Microsoft notes that keyword search can be particularly useful where exact matching matters. (Microsoft Learn)


9. Vector Search

Vector search is one of the most important capabilities for modern AI applications.

An embedding model converts text into a numerical representation called a vector.

For example:

"How do I reset my password?"

might become conceptually:

[0.021, -0.192, 0.442, ...]

The vector represents semantic information rather than simply storing individual keywords.

The user's question is also converted into a vector.

Then Azure AI Search finds documents whose vectors are mathematically similar.

Microsoft describes vector search as useful for conceptual similarity and multilingual or multimodal scenarios. (Microsoft Learn)


10. Why Vector Search Is Powerful

Consider these two sentences:

Document:
"Employees can change their credentials from the security portal."

User:
"Where can I update my password?"

There may be no exact keyword match for every word.

But semantically:

change credentials
        ≈
update password

Vector search can identify that relationship.


11. What Is an Embedding?

An embedding is a numerical representation of content.

For example:

Text
 |
 v
Embedding Model
 |
 v
Vector

Conceptually:

"Azure Functions"
        |
        v
[0.12, -0.44, 0.72, ...]

The actual vector has many dimensions.

The application stores this vector in a vector field in Azure AI Search.


12. Hybrid Search

Hybrid search combines:

Keyword Search
       +
Vector Search

in a single request.

Azure AI Search executes the text and vector searches and merges their results using Reciprocal Rank Fusion (RRF). (Microsoft Learn)

Conceptually:

                User Query
                    |
          +---------+---------+
          |                   |
          v                   v
     Keyword Search      Vector Search
          |                   |
          v                   v
      Results A           Results B
          |                   |
          +---------+---------+
                    |
                    v
                   RRF
                    |
                    v
             Combined Results

This is often a strong choice for enterprise search.


13. Semantic Ranking

Semantic ranking provides another relevance layer.

The initial results can be reranked using Microsoft's language-understanding models.

For example:

Query:
"How can I work remotely?"

Result A:
"Remote working policy..."

Result B:
"Office parking policy..."

Result C:
"VPN remote access instructions..."

Semantic ranking can identify which results are most relevant to the meaning of the query.

Microsoft describes semantic ranker as a secondary ranking stage over an initial BM25 or RRF result set. (Microsoft Learn)


14. Search Architecture

A modern Azure AI Search application can look like this:

                  Documents
                     |
       +-------------+-------------+
       |             |             |
       v             v             v
     PDF          Database       Website
       |             |             |
       +-------------+-------------+
                     |
                     v
              Data Processing
                     |
                     v
              Chunking / Cleaning
                     |
                     v
               Embeddings
                     |
                     v
             Azure AI Search
                     |
              Search Index
                     |
                     v
                 User Query
                     |
          +----------+----------+
          |                     |
          v                     v
       Keyword               Vector
       Search                Search
          |                     |
          +----------+----------+
                     |
                     v
                    RRF
                     |
                     v
              Semantic Ranker
                     |
                     v
                Top Results
                     |
                     v
                Azure OpenAI
                     |
                     v
               Final Response

15. What Is RAG?

RAG means:

Retrieval-Augmented Generation

Instead of asking an LLM to answer only from its trained knowledge, we first retrieve relevant information from our own data.

The process is:

User Question
      |
      v
Azure AI Search
      |
      v
Relevant Documents
      |
      v
Prompt + Retrieved Context
      |
      v
Azure OpenAI
      |
      v
Final Answer

Microsoft describes RAG as a pattern that grounds LLM responses in proprietary content. (Microsoft Learn)


16. Real-Time Example: Employee Knowledge Assistant

Let's build a realistic enterprise application.

Imagine a company has:

HR Policies
IT Policies
Leave Policies
Travel Policies
Insurance Documents
Employee Handbook
Security Guidelines

Employees can ask:

"How many days of annual leave can I take?"

or:

"What is the process for claiming travel expenses?"

or:

"How do I reset my VPN password?"

Instead of manually searching hundreds of documents, the application retrieves the relevant information automatically.


17. Complete Architecture

Our solution will use:

Angular
   |
   v
ASP.NET Core Web API
   |
   +--------------------+
   |                    |
   v                    v
Azure AI Search      Azure OpenAI
   |
   v
Search Index

Documents:

Azure Blob Storage
       |
       v
Document Processing
       |
       v
Chunking
       |
       v
Embeddings
       |
       v
Azure AI Search

18. Step 1 – Create Azure AI Search

In Azure Portal:

Azure Portal
     |
     v
Create a resource
     |
     v
Search service

Configure:

Subscription
Resource Group
Service Name
Region
Pricing Tier

After deployment, you will have an Azure AI Search service.


19. Step 2 – Create Azure OpenAI

Create an Azure OpenAI resource and deploy appropriate models for:

Chat / generation
+
Embeddings

The embedding model is used to convert content and queries into vectors.

The chat model generates the final response.


20. Step 3 – Store Documents

Suppose we have:

EmployeeHandbook.pdf
LeavePolicy.pdf
TravelPolicy.pdf
SecurityPolicy.pdf

A common architecture is:

Azure Blob Storage
        |
        v
Document Processing
        |
        v
Azure AI Search

Microsoft's .NET RAG tutorial similarly demonstrates a solution using Azure OpenAI, Azure AI Search, storage, and an application layer. (Microsoft Learn)


21. Step 4 – Chunk Documents

Large documents should normally be divided into smaller pieces.

For example:

LeavePolicy.pdf

        |
        v

Chunk 1
Introduction

Chunk 2
Annual Leave

Chunk 3
Sick Leave

Chunk 4
Approval Process

Chunk 5
Carry Forward Policy

Why?

Because sending an entire 100-page document to an LLM for every question is inefficient.

Instead, retrieve only the relevant chunks.


22. Example Search Document

Our index could contain:

{
  "id": "leave-001",
  "title": "Annual Leave Policy",
  "content": "Employees are entitled to annual leave according to company policy...",
  "category": "HR",
  "documentName": "LeavePolicy.pdf",
  "contentVector": [ ... ]
}

The important fields are:

id
title
content
category
documentName
contentVector

23. Create a .NET Project

Create an ASP.NET Core Web API:

dotnet new webapi -n EnterpriseSearch.Api

Install the Azure AI Search SDK:

dotnet add package Azure.Search.Documents

The official .NET SDK package is Azure.Search.Documents. (Microsoft Learn)


24. Configuration

appsettings.json:

{
  "AzureSearch": {
    "Endpoint": "https://YOUR-SEARCH-SERVICE.search.windows.net",
    "IndexName": "employee-knowledge"
  }
}

For production, avoid storing secrets directly in configuration files.

Prefer:

Managed Identity
+
Microsoft Entra ID
+
Azure Key Vault

Microsoft's current .NET RAG tutorial demonstrates managed identities for passwordless service-to-service authentication. (Microsoft Learn)


25. Create Search Service Class

Example:

using Azure;
using Azure.Search.Documents;
using Azure.Search.Documents.Models;

public class SearchService
{
    private readonly SearchClient _searchClient;

    public SearchService(
        IConfiguration configuration)
    {
        var endpoint =
            configuration["AzureSearch:Endpoint"];

        var indexName =
            configuration["AzureSearch:IndexName"];

        var credential =
            new Azure.Identity.DefaultAzureCredential();

        _searchClient =
            new SearchClient(
                new Uri(endpoint!),
                indexName,
                credential);
    }

    public async Task<List<SearchDocument>> SearchAsync(
        string query)
    {
        var options = new SearchOptions
        {
            Size = 5
        };

        options.Select.Add("id");
        options.Select.Add("title");
        options.Select.Add("content");
        options.Select.Add("documentName");

        var response =
            await _searchClient.SearchAsync<SearchDocument>(
                query,
                options);

        var results = new List<SearchDocument>();

        await foreach (var result in response.Value.GetResultsAsync())
        {
            results.Add(result.Document);
        }

        return results;
    }
}

26. Create the API Controller

[ApiController]
[Route("api/search")]
public class SearchController : ControllerBase
{
    private readonly SearchService _searchService;

    public SearchController(SearchService searchService)
    {
        _searchService = searchService;
    }

    [HttpGet]
    public async Task<IActionResult> Search(
        string query)
    {
        var results =
            await _searchService.SearchAsync(query);

        return Ok(results);
    }
}

Now the API can be called like:

GET /api/search?query=annual leave

27. Example Response

The API could return:

[
  {
    "title": "Annual Leave Policy",
    "content": "Employees are entitled to annual leave...",
    "documentName": "LeavePolicy.pdf"
  },
  {
    "title": "Employee Handbook",
    "content": "Leave requests must be submitted...",
    "documentName": "EmployeeHandbook.pdf"
  }
]

28. Adding Vector Search

For vector search, the index contains a vector field.

Conceptually:

content
contentVector

The process is:

User Query
     |
     v
Embedding Model
     |
     v
Query Vector
     |
     v
Azure AI Search
     |
     v
Similar Document Vectors

29. Hybrid Search Query

A hybrid query contains both:

search
+
vectorQueries

Conceptually:

{
  "search": "How do I apply for annual leave?",
  "vectorQueries": [
    {
      "kind": "vector",
      "vector": [ ... ],
      "fields": "contentVector",
      "k": 5
    }
  ],
  "top": 5
}

Azure AI Search executes both searches and combines their results using RRF. (Microsoft Learn)


30. Semantic Hybrid Search

For high-quality retrieval, you can combine:

Keyword
+
Vector
+
Semantic Ranking

Conceptually:

User Query
    |
    +----> Keyword Search
    |
    +----> Vector Search
              |
              v
             RRF
              |
              v
       Semantic Ranker
              |
              v
       Best Documents

This is an especially useful architecture for RAG applications. Microsoft documentation highlights hybrid search with semantic ranking as a strong relevance strategy. (Microsoft Learn)


31. Complete RAG Flow

Let's walk through an actual question.

User asks:

"How many days of annual leave can I take?"

Step 1

Angular sends:

POST /api/chat

Request:

{
  "question": "How many days of annual leave can I take?"
}

Step 2

ASP.NET Core receives the question.

Step 3

The application sends the question to the retrieval layer.

Step 4

The query is converted into a vector.

Step 5

Azure AI Search performs:

Keyword Search
+
Vector Search

Step 6

Results are merged using RRF.

Step 7

Semantic ranking can further improve ordering.

Step 8

Top relevant chunks are returned.

Example:

Annual Leave Policy
-------------------

Employees are entitled to 20 days
of annual leave per calendar year.

Step 9

The application builds a prompt:

Answer the user's question using
only the following company policy.

Context:
Employees are entitled to 20 days
of annual leave per calendar year.

Question:
How many days of annual leave can I take?

Step 10

Azure OpenAI generates:

According to the Annual Leave Policy,
employees are entitled to 20 days of
annual leave per calendar year.

32. Why RAG Is Better Than Sending Everything to the LLM

Without RAG:

User
 |
 v
LLM
 |
 v
Possible hallucination

With RAG:

User
 |
 v
Azure AI Search
 |
 v
Company Documents
 |
 v
Relevant Context
 |
 v
LLM
 |
 v
Grounded Answer

RAG doesn't automatically guarantee that every answer is correct, but it gives the model relevant source material from your organization's data.


33. Adding Citations

A production enterprise application should ideally tell users where an answer came from.

For example:

According to the Annual Leave Policy,
employees are entitled to 20 days of annual leave.

Source:
LeavePolicy.pdf
Page 4

Your index can store metadata such as:

documentName
pageNumber
chunkId
sourceUrl
department

Then your API can return:

{
  "answer": "Employees are entitled to 20 days of annual leave.",
  "sources": [
    {
      "document": "LeavePolicy.pdf",
      "page": 4
    }
  ]
}

This greatly improves trust and auditability.


34. Security in Azure AI Search

Enterprise search must consider authorization.

Suppose:

HR Documents
Finance Documents
Engineering Documents

An Engineering employee should not automatically retrieve confidential HR documents.

A production architecture should therefore consider:

User Identity
     |
     v
Authorization
     |
     v
Security Filter
     |
     v
Azure AI Search

Metadata can include:

department
userId
role
securityGroup
accessLevel

Then search filters can restrict what users are allowed to retrieve.


35. Azure AI Search and Managed Identity

For production applications, avoid this:

API Key stored in appsettings.json

Prefer:

ASP.NET Core
     |
     v
Managed Identity
     |
     v
Microsoft Entra ID
     |
     v
Azure AI Search

This eliminates the need to distribute long-lived secrets between Azure services.


36. Common Real-Time Use Cases

Azure AI Search can be used for:

Enterprise Knowledge Search

Company Documents
       |
       v
AI Search
       |
       v
Employee Assistant

E-Commerce

Products
   |
   v
AI Search
   |
   +--> Keyword
   +--> Semantic
   +--> Vector

Example:

"Find lightweight laptops for programming."

Customer Support

Support Tickets
Knowledge Base
Product Manuals
       |
       v
Azure AI Search
       |
       v
Support Copilot

Legal Document Search

Contracts
Policies
Agreements
       |
       v
Search + RAG

Healthcare Knowledge Systems

For appropriate authorized environments:

Clinical documents
Research documents
Policies
       |
       v
Search

Sensitive applications require strong access control, privacy, compliance, and human oversight.


37. Azure AI Search in Microservices Architecture

For a microservices application:

                    API Gateway
                         |
          +--------------+--------------+
          |              |              |
          v              v              v
     Product Service  Order Service  Customer Service
          |              |              |
          +--------------+--------------+
                         |
                         v
                  Search Service
                         |
                         v
                 Azure AI Search

I recommend keeping search concerns separate from transactional services.

For example:

Product Service
      |
      v
Product Database

Search Indexing Service
      |
      v
Azure AI Search

When product data changes:

Product Updated
      |
      v
Event / Message
      |
      v
Search Indexing Service
      |
      v
Azure AI Search

This avoids tightly coupling every service to the search engine.


38. Event-Driven Indexing

For large systems:

Product Service
      |
      v
Azure Service Bus
      |
      v
Search Index Worker
      |
      v
Azure AI Search

For example:

ProductUpdatedEvent

could contain:

{
  "productId": "P1001",
  "operation": "Updated"
}

The indexing worker then updates the corresponding Azure AI Search document.


39. Azure AI Search vs Elasticsearch

FeatureAzure AI SearchElasticsearch
Azure integrationExcellentGood
Microsoft ecosystemExcellentGood
Vector searchYesYes
Hybrid searchYesYes
Semantic rankingYesDifferent approach
Azure OpenAI integrationExcellentPossible
Managed Azure serviceYesDepends on offering
.NET integrationExcellentExcellent

If your application is already heavily invested in Azure, Azure AI Search is often a natural choice.


40. Azure AI Search vs Database LIKE

Bad approach for large-scale AI search:

SELECT *
FROM Documents
WHERE Content LIKE '%password%';

Better:

Azure AI Search
      |
      +-- Full Text
      +-- Vector
      +-- Hybrid
      +-- Semantic Ranking

41. Common Mistakes

Mistake 1 – Indexing entire documents as one chunk

Instead:

Document
   |
   v
Meaningful chunks

Mistake 2 – Using only vector search

Vector search is powerful, but exact keywords can be important.

For example:

INC-45872

A keyword search may be more useful than semantic similarity.

Therefore:

Keyword + Vector

is often preferable.


Mistake 3 – Sending too many search results to the LLM

Don't retrieve hundreds of chunks.

Instead:

Retrieve
   |
   v
Rank
   |
   v
Top relevant chunks
   |
   v
LLM

Mistake 4 – Ignoring security

Never assume:

"If the document is indexed,
every user can see it."

Security trimming and authorization must be designed into the solution.


Mistake 5 – Storing secrets in source code

Avoid:

const string apiKey = "xxxxxxxx";

Use:

Managed Identity
Azure Key Vault
Microsoft Entra ID

42. Performance Optimization

Important considerations include:

Chunk Size

Avoid extremely large chunks.

Use logically meaningful sections.

Top K

Retrieve a controlled number of candidates.

For example:

Top 5
Top 10
Top 20

depending on the workload.

Hybrid Search

Use hybrid retrieval when both exact matching and semantic matching matter.

Semantic Ranking

Use semantic ranking when better relevance justifies its additional cost/latency.

Filters

Apply metadata filters when possible.

For example:

department = 'IT'

or:

documentType = 'Policy'

Monitoring

Monitor:

Latency
Query volume
Failed queries
Search relevance
Token usage
LLM latency
Cost

43. Production Architecture

A more complete enterprise implementation might look like:

                    Users
                      |
                      v
                 Azure Front Door
                      |
                      v
                API Management
                      |
                      v
              ASP.NET Core API
                      |
          +-----------+-----------+
          |                       |
          v                       v
 Azure AI Search             Azure OpenAI
          |
          |
    +-----+------+
    |            |
    v            v
Vector Index   Text Index
    |
    v
Blob Storage
    |
    v
Documents

Supporting services:

Azure Key Vault
Azure Monitor
Application Insights
Azure Service Bus
Microsoft Entra ID

44. Monitoring

Use Azure monitoring tools to observe:

Search latency
Request count
Errors
Throttling
Application latency
AI model latency
Token usage

Application Insights can help trace:

HTTP Request
     |
     v
Search Query
     |
     v
Azure OpenAI
     |
     v
Response

This is especially valuable when debugging slow RAG applications.


45. How to Design a Production RAG Pipeline

A recommended pipeline is:

1. Collect documents
        |
2. Extract text
        |
3. Clean text
        |
4. Split into chunks
        |
5. Generate embeddings
        |
6. Store chunks + vectors
        |
7. Build search index
        |
8. User asks question
        |
9. Retrieve candidates
        |
10. Hybrid search
        |
11. Semantic reranking
        |
12. Security filtering
        |
13. Build context
        |
14. Call Azure OpenAI
        |
15. Return answer + sources

46. Classic RAG vs Agentic Retrieval

Azure AI Search now also provides agentic retrieval capabilities.

Classic RAG generally follows:

Question
   |
   v
Search
   |
   v
Results
   |
   v
LLM

Agentic retrieval can use an LLM to help understand and decompose more complex queries before retrieval.

Microsoft currently documents agentic retrieval as a newer retrieval approach, with some capabilities available in preview depending on the API/features used. (Microsoft Learn)

For a first production implementation, classic hybrid RAG is often easier to understand, test, and operate.


47. Recommended Technology Stack

For a Microsoft-based enterprise application:

Frontend
    Angular

Backend
    ASP.NET Core Web API

Search
    Azure AI Search

LLM
    Azure OpenAI

Embeddings
    Azure OpenAI embedding model

Storage
    Azure Blob Storage

Database
    Azure SQL

Messaging
    Azure Service Bus

Secrets
    Azure Key Vault

Identity
    Microsoft Entra ID

Monitoring
    Application Insights
    Azure Monitor

Deployment
    Azure App Service / AKS

48. Complete Request Flow

Let's summarize the complete request:

                    USER
                      |
                      v
                Angular App
                      |
                      v
              ASP.NET Core API
                      |
                      v
               User Question
                      |
                      v
             Query Processing
                      |
             +--------+--------+
             |                 |
             v                 v
        Keyword Search    Vector Search
             |                 |
             +--------+--------+
                      |
                      v
                     RRF
                      |
                      v
              Semantic Ranking
                      |
                      v
              Security Filtering
                      |
                      v
              Top Relevant Chunks
                      |
                      v
                 Prompt Builder
                      |
                      v
                Azure OpenAI
                      |
                      v
                Final Answer
                      |
                      v
             Answer + Citations
                      |
                      v
                    USER

49. Key Interview Questions

If you are preparing for a .NET/Azure interview, these are important questions.

Q1. What is Azure AI Search?

A managed Azure service for information retrieval supporting full-text, vector, hybrid, semantic, and generative-AI search scenarios.

Q2. What is vector search?

Searching for documents based on vector similarity rather than only exact keywords.

Q3. What is hybrid search?

Combining keyword/full-text and vector search in the same request and merging their rankings using RRF. (Microsoft Learn)

Q4. What is semantic ranking?

A second-stage relevance process that reranks an initial result set using language understanding models. (Microsoft Learn)

Q5. Why use Azure AI Search with Azure OpenAI?

Azure AI Search retrieves enterprise-specific information, while Azure OpenAI generates a natural-language response based on that retrieved context.

Q6. What is RAG?

Retrieval-Augmented Generation: retrieve relevant external knowledge and provide it to an LLM as context for generating an answer.

Q7. Why chunk documents?

To retrieve smaller, relevant pieces of information instead of sending entire documents to the LLM.

Q8. What is RRF?

Reciprocal Rank Fusion is used to combine rankings from multiple search result sets, including hybrid search results. (Microsoft Learn)

Q9. How do you secure Azure AI Search?

Use Microsoft Entra ID, managed identities, RBAC, and security-aware filtering/authorization appropriate to the application.

Q10. How would you integrate Azure AI Search into a .NET microservices architecture?

Use a dedicated search/indexing component, publish domain events through messaging when data changes, and update the search index asynchronously.


50. Final Takeaway

Azure AI Search is much more than a traditional search engine.

It can provide:

Traditional Search
       +
Vector Search
       +
Hybrid Search
       +
Semantic Ranking
       +
RAG Retrieval
       +
Enterprise Security

The most important architecture to remember is:

              YOUR DATA
                  |
                  v
          Azure AI Search
                  |
        +---------+---------+
        |                   |
   Keyword Search      Vector Search
        |                   |
        +---------+---------+
                  |
                 RRF
                  |
          Semantic Ranking
                  |
                  v
          Relevant Context
                  |
                  v
            Azure OpenAI
                  |
                  v
          Grounded Response

For a .NET developer, a particularly powerful enterprise stack is:

Angular
   ↓
ASP.NET Core
   ↓
Azure AI Search
   ↓
Azure OpenAI
   ↓
Azure SQL / Blob Storage
   ↓
Azure Service Bus
   ↓
Key Vault + Managed Identity
   ↓
Application Insights

This architecture can be used to build enterprise knowledge assistants, customer-support copilots, product search, document search, internal AI assistants, and RAG-based applications.

Microsoft also provides an official .NET RAG sample that combines Azure AI Search and Azure OpenAI, including document indexing and managed-identity-based authentication. (Microsoft Learn)

Official Microsoft References

In one sentence: Azure AI Search is the retrieval layer that helps your application find the right information, while Azure OpenAI is the generation layer that turns that information into a useful natural-language answer.

Don't Copy

Protected by Copyscape Online Plagiarism Checker