Core Caching: In-Memory, Distributed Cache and Redis :👈 👉:N+1 query problem

ASP.NET Core Microservices Architecture

ASP.NET Core Microservices Architecture – Complete Implementation Guide

Table of Contents

  1. Introduction to Microservices Architecture
  2. Monolithic vs Microservices Architecture
  3. When to Use Microservices and When Not to Use Them
  4. Microservices Architecture Overview
  5. Real-World E-Commerce Application Example
  6. Core Components of Microservices
  7. Solution and Project Structure
  8. Creating ASP.NET Core Microservices
  9. Database per Microservice Pattern
  10. Entity Framework Core Integration
  11. Communication Between Microservices
  12. Synchronous Communication Using HTTP
  13. Asynchronous Communication Using Messaging
  14. RabbitMQ and Azure Service Bus
  15. YARP API Gateway
  16. Authentication and Authorization
  17. Inter-Service Security
  18. Distributed Transactions and Saga Pattern
  19. Event-Driven Architecture
  20. Redis Caching
  21. Resilience and Fault Tolerance
  22. Centralized Configuration and Secrets
  23. Logging, Monitoring and Distributed Tracing
  24. Health Checks
  25. Docker and Containerization
  26. Kubernetes and Azure Kubernetes Service
  27. CI/CD Pipeline
  28. Testing Microservices
  29. Performance Optimization
  30. Security Best Practices
  31. Production Deployment Architecture
  32. Common Microservices Mistakes
  33. Implementation Checklist
  34. Interview Questions

1. Introduction to Microservices Architecture

What Are Microservices?

Microservices architecture is an architectural approach in which a large application is divided into multiple small, independent services.

Each service is responsible for a specific business capability and can be developed, deployed, maintained and scaled independently.

Each microservice typically:

  • Owns a specific business responsibility.
  • Has its own business logic.
  • Owns its data and database.
  • Exposes APIs or messaging contracts.
  • Can be deployed independently.
  • Can be scaled independently.
  • Can be maintained by a separate development team.

Example

Consider an e-commerce application such as an online shopping platform.

Instead of developing one large application, divide it into the following services:

  • User Service: Manages customer registration, profiles and user information.
  • Product Service: Manages products, categories, prices and product information.
  • Order Service: Manages customer orders and order processing.
  • Payment Service: Handles payment processing and payment status.
  • Inventory Service: Manages stock availability and reservations.
  • Notification Service: Sends emails, SMS and notifications.

Each service performs its own responsibility and communicates with other services when necessary.

Basic Microservices Architecture

                    CLIENT APPLICATIONS
                  Web / Mobile / External
                            |
                            v
                     API GATEWAY
                            |
          +-----------------+-----------------+
          |                 |                 |
          v                 v                 v
     USER SERVICE     PRODUCT SERVICE    ORDER SERVICE
          |                 |                 |
          v                 v                 v
      USER DB           PRODUCT DB          ORDER DB
                            |
                            |
                     MESSAGE BROKER
                            |
              +-------------+-------------+
              |             |             |
              v             v             v
        PAYMENT SERVICE INVENTORY SERVICE NOTIFICATION
              |             |             |
              v             v             v
          PAYMENT DB     INVENTORY DB   NOTIFICATION DB

The API Gateway acts as an entry point for client requests. Individual services handle their own business operations and data.

2. Monolithic vs Microservices Architecture

Monolithic Architecture

In a monolithic application, multiple business functionalities are implemented inside one application and commonly deployed as one unit.

             MONOLITHIC APPLICATION
                       |
        +--------------+--------------+
        |              |              |
        v              v              v
   User Module    Product Module   Order Module
        |              |              |
        +--------------+--------------+
                       |
                  Payment Module
                       |
                    Database

Microservices Architecture

In microservices architecture, business functionalities are separated into independently deployable services.

       USER SERVICE       PRODUCT SERVICE
            |                   |
            v                   v
         USER DB             PRODUCT DB
       ORDER SERVICE      PAYMENT SERVICE
            |                   |
            v                   v
         ORDER DB            PAYMENT DB

Comparison

Feature Monolithic Microservices
Application Structure Single application Multiple independent services
Deployment Usually deployed together Services deployed independently
Scaling Usually scales the application as a whole Individual services can be scaled
Database Commonly shared database Database ownership per service
Communication Usually in-process method calls HTTP, gRPC or messaging
Technology Usually one technology stack Different technologies can be used
Complexity Generally simpler operationally Higher distributed-system complexity
Failure Handling Primarily application-level Requires distributed fault handling
Team Structure Teams may share application ownership Teams can own individual services

3. When to Use Microservices and When Not to Use Them

When to Use Microservices

  • Large enterprise applications with multiple business domains.
  • Applications requiring independent deployment.
  • Applications with different scaling requirements.
  • Systems maintained by multiple independent teams.
  • Applications with complex business capabilities.
  • Systems requiring independent technology choices.

When NOT to Use Microservices

  • Small applications with limited functionality.
  • Applications maintained by a small development team.
  • Systems without independent deployment requirements.
  • Applications where distributed complexity provides little benefit.
  • Projects without the infrastructure or operational maturity to manage distributed services.

Best Practice: Start with a well-structured modular monolith when the business requirements do not justify distributed services. Extract microservices when independent ownership, scaling or deployment provides a measurable benefit.

4. Microservices Architecture Overview

A production microservices system contains several architectural components.

Component Purpose Technology
API Gateway Single entry point for client requests YARP
Microservices Business functionality ASP.NET Core Web API
Database Persistent data storage SQL Server / PostgreSQL
ORM Database access Entity Framework Core
Message Broker Asynchronous communication RabbitMQ / Azure Service Bus
Cache Fast data access Redis
Authentication Identity verification OAuth 2.0 / OpenID Connect
Containerization Package applications Docker
Orchestration Manage containers Kubernetes / AKS
Monitoring Application observability OpenTelemetry / Azure Monitor
Configuration Centralized application configuration Azure App Configuration
Secrets Secure secret storage Azure Key Vault

5. Real-World E-Commerce Application Example

We will implement an e-commerce system using ASP.NET Core microservices.

Business Requirements

A customer should be able to:

  1. Register and log in.
  2. View available products.
  3. Search and select products.
  4. Add products to a shopping cart.
  5. Place an order.
  6. Make a payment.
  7. Check order status.
  8. Receive order notifications.

Services Required

Service Responsibilities Database
User Service Registration, profiles and customer information UserDB
Product Service Product catalogue, categories and pricing ProductDB
Cart Service Shopping cart management CartDB / Redis
Order Service Order creation and order lifecycle OrderDB
Payment Service Payment processing and status PaymentDB
Inventory Service Stock and reservations InventoryDB
Notification Service Email, SMS and push notifications NotificationDB

Architecture Diagram

                       WEB / MOBILE CLIENT
                                |
                                v
                          YARP GATEWAY
                                |
             +------------------+------------------+
             |         |        |        |         |
             v         v        v        v         v
           USER     PRODUCT    CART    ORDER     PAYMENT
          SERVICE   SERVICE   SERVICE  SERVICE   SERVICE
             |         |        |        |         |
             v         v        v        v         v
           UserDB   ProductDB CartDB   OrderDB  PaymentDB
                                |
                         MESSAGE BROKER
                                |
                 +--------------+--------------+
                 |              |              |
                 v              v              v
             INVENTORY      NOTIFICATION    ANALYTICS
              SERVICE         SERVICE       CONSUMER
                 |              |
                 v              v
             InventoryDB   NotificationDB

Each service owns its business logic and database. Services communicate using HTTP APIs or asynchronous events, depending on the operation.

6. Core Components of Microservices

6.1 API Gateway

An API Gateway is an entry point between clients and backend microservices.

Instead of allowing the frontend to communicate directly with every microservice, the client sends requests through the gateway.

Responsibilities:

  • Request routing.
  • Authentication integration.
  • Rate limiting.
  • Request and response transformation where needed.
  • Centralized cross-cutting policies.
  • API version routing.

6.2 Microservices

Each service represents a business capability.

For example:

Product Service
    |
    +-- ProductController
    +-- ProductService
    +-- ProductRepository
    +-- ProductDbContext
    +-- Product Entity

6.3 Database per Service

Each microservice owns its data. Other services should not directly access its database tables.

For example, Order Service should obtain product information through an API or event contract rather than querying ProductDB directly.

6.4 Message Broker

A message broker enables asynchronous communication between microservices.

For example, after an order is created, Order Service publishes an OrderCreated event. Payment, Inventory and Notification services can consume that event independently.

7. Solution and Project Structure

A practical repository structure for an ASP.NET Core microservices solution is:

ECommerce/
|
+-- src/
|   |
|   +-- ApiGateway/
|   |   +-- ApiGateway.csproj
|   |   +-- Program.cs
|   |   +-- appsettings.json
|   |
|   +-- Services/
|   |   |
|   |   +-- UserService/
|   |   |   +-- UserService.Api/
|   |   |   +-- UserService.Application/
|   |   |   +-- UserService.Domain/
|   |   |   +-- UserService.Infrastructure/
|   |   |
|   |   +-- ProductService/
|   |   |   +-- ProductService.Api/
|   |   |   +-- ProductService.Application/
|   |   |   +-- ProductService.Domain/
|   |   |   +-- ProductService.Infrastructure/
|   |   |
|   |   +-- OrderService/
|   |   |   +-- OrderService.Api/
|   |   |   +-- OrderService.Application/
|   |   |   +-- OrderService.Domain/
|   |   |   +-- OrderService.Infrastructure/
|   |   |
|   |   +-- PaymentService/
|   |       +-- PaymentService.Api/
|   |       +-- PaymentService.Application/
|   |       +-- PaymentService.Domain/
|   |       +-- PaymentService.Infrastructure/
|   |
|   +-- BuildingBlocks/
|       +-- Contracts/
|       +-- Observability/
|       +-- Messaging/
|
+-- tests/
|   +-- UnitTests/
|   +-- IntegrationTests/
|   +-- ContractTests/
|
+-- deploy/
    +-- docker/
    +-- kubernetes/
    +-- helm/
    +-- pipelines/

Important: BuildingBlocks should contain genuinely shared technical abstractions or contracts. Avoid creating a common library that couples all services to the same domain model or database implementation.

8. Creating ASP.NET Core Microservices

We will use the Product Service as our first example.

Step 1: Install Required Tools

  • .NET SDK.
  • Visual Studio or Visual Studio Code.
  • Docker Desktop or another compatible container runtime.
  • SQL Server or PostgreSQL.
  • Git.
  • Azure CLI for Azure deployments.

Step 2: Create a Solution

dotnet new sln -n ECommerce

Step 3: Create Product Service Projects

dotnet new webapi -n ProductService.Api
dotnet new classlib -n ProductService.Application
dotnet new classlib -n ProductService.Domain
dotnet new classlib -n ProductService.Infrastructure
dotnet sln add ProductService.Api
dotnet sln add ProductService.Application
dotnet sln add ProductService.Domain
dotnet sln add ProductService.Infrastructure

Step 4: Add Project References

dotnet add ProductService.Application reference ProductService.Domain
dotnet add ProductService.Infrastructure reference ProductService.Domain
dotnet add ProductService.Infrastructure reference ProductService.Application
dotnet add ProductService.Api reference ProductService.Application
dotnet add ProductService.Api reference ProductService.Infrastructure

The dependency direction should keep the Domain layer independent of infrastructure and web frameworks.

Project Dependency Diagram

          PRODUCT SERVICE API
                  |
          +-------+-------+
          |               |
          v               v
    APPLICATION     INFRASTRUCTURE
          |               |
          v               v
        DOMAIN <-----------+

9. Creating the Product Domain Model

Domain entities represent the important business objects of a service.

Create Product.cs inside ProductService.Domain.

namespace ProductService.Domain.Entities;
public class Product
{
    public Guid Id { get; private set; }
    public string Name { get; private set; }
    public string Description { get; private set; }
    public decimal Price { get; private set; }
    public int StockQuantity { get; private set; }
    public DateTime CreatedAt { get; private set; }
    private Product()
    {
        Name = string.Empty;
        Description = string.Empty;
    }
    public Product(
        string name,
        string description,
        decimal price,
        int stockQuantity)
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new ArgumentException("Product name is required.");
        if (price <= 0)
            throw new ArgumentException("Price must be greater than zero.");
        if (stockQuantity < 0)
            throw new ArgumentException("Stock cannot be negative.");
        Id = Guid.NewGuid();
        Name = name;
        Description = description;
        Price = price;
        StockQuantity = stockQuantity;
        CreatedAt = DateTime.UtcNow;
    }
    public void UpdatePrice(decimal price)
    {
        if (price <= 0)
            throw new ArgumentException("Invalid price.");
        Price = price;
    }
}

Notice that important business validations are handled within the domain entity rather than relying entirely on controllers.

10. Database per Microservice Pattern

One of the most important microservices principles is database ownership.

Each microservice owns its data and controls how that data is accessed.

Example

Microservice Database Tables
User Service UserDB Users, Profiles
Product Service ProductDB Products, Categories
Order Service OrderDB Orders, OrderItems
Payment Service PaymentDB Payments, Transactions
Inventory Service InventoryDB Stock, Reservations

Database per service does not necessarily mean a separate physical database server for every service. Multiple databases or schemas can share infrastructure, provided ownership and access boundaries are maintained.

Why Should We Avoid a Shared Database?

  • Services become tightly coupled.
  • Schema changes can break multiple services.
  • Independent deployments become difficult.
  • Business ownership becomes unclear.
  • Scaling and database optimization become harder.

11. Entity Framework Core Integration

Entity Framework Core can be used to communicate with the database from each microservice.

Step 1: Install EF Core Packages

dotnet add ProductService.Infrastructure package Microsoft.EntityFrameworkCore
dotnet add ProductService.Infrastructure package Microsoft.EntityFrameworkCore.SqlServer
dotnet add ProductService.Infrastructure package Microsoft.EntityFrameworkCore.Design

Step 2: Create ProductDbContext

using Microsoft.EntityFrameworkCore;
using ProductService.Domain.Entities;
namespace ProductService.Infrastructure.Persistence;
public class ProductDbContext : DbContext
{
    public ProductDbContext(
        DbContextOptions<ProductDbContext> options)
        : base(options)
    {
    }
    public DbSet<Product> Products => Set<Product>();
    protected override void OnModelCreating(
        ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>(entity =>
        {
            entity.HasKey(x => x.Id);
            entity.Property(x => x.Name)
                .HasMaxLength(200)
                .IsRequired();
            entity.Property(x => x.Price)
                .HasPrecision(18, 2);
            entity.Property(x => x.Description)
                .HasMaxLength(1000);
        });
    }
}

Step 3: Configure Connection String

In appsettings.json:

{
  "ConnectionStrings": {
    "ProductDatabase": "Server=localhost;Database=ProductDB;Trusted_Connection=True;TrustServerCertificate=True"
  }
}

This is only a local development example. Production credentials should be supplied through secure configuration, not committed to source control.

Step 4: Register DbContext

In ProductService.Api Program.cs:

using Microsoft.EntityFrameworkCore;
using ProductService.Infrastructure.Persistence;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<ProductDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString(
            "ProductDatabase")));
var app = builder.Build();
app.MapControllers();
app.Run();

Step 5: Create Database Migration

dotnet ef migrations add InitialCreate \
  --project ProductService.Infrastructure \
  --startup-project ProductService.Api
dotnet ef database update \
  --project ProductService.Infrastructure \
  --startup-project ProductService.Api

For production, prefer a controlled migration process rather than automatically applying migrations during every application startup.

12. Communication Between Microservices

Microservices need to communicate with each other to complete business operations.

For example, when a customer places an order:

  1. Order Service receives the order request.
  2. Product Service provides product information when required.
  3. Inventory Service checks and reserves stock.
  4. Payment Service processes the payment.
  5. Notification Service sends an order confirmation.

There are two major communication approaches:

1. Synchronous Communication

The calling service sends a request and waits for a response.

Common technologies:

  • HTTP / REST APIs.
  • gRPC.
       ORDER SERVICE
             |
             | HTTP Request
             v
       PRODUCT SERVICE
             |
             | HTTP Response
             v
       ORDER SERVICE

2. Asynchronous Communication

The sending service publishes a message or event and continues processing without waiting for every receiving service to finish.

Common technologies:

  • RabbitMQ.
  • Azure Service Bus.
  • Apache Kafka.
          ORDER SERVICE
                |
                | OrderCreated Event
                v
           MESSAGE BROKER
                |
        +-------+-------+
        |       |       |
        v       v       v
     PAYMENT INVENTORY NOTIFICATION
     SERVICE  SERVICE   SERVICE

Synchronous vs Asynchronous Communication

Feature Synchronous Asynchronous
Communication Request and response Message or event based
Waiting Caller waits for response Caller generally does not wait for consumer processing
Coupling Runtime dependency between services Looser runtime coupling
Failure Handling Timeouts and retries Redelivery, retries and dead-letter handling
Example Get product details OrderCreated event

Best Practice: Use HTTP or gRPC when an immediate response is required. Use asynchronous messaging for business events, background processing and communication that should not depend on another service being immediately available.

13. Synchronous Communication Using HTTP

ASP.NET Core provides HttpClient for communicating with other services.

Consider the following scenario:

Order Service needs to retrieve product information from Product Service.

Step 1: Create a Product DTO

public record ProductDto(
    Guid Id,
    string Name,
    decimal Price);

Step 2: Create an HTTP Client Interface

public interface IProductApiClient
{
    Task<ProductDto?> GetProductAsync(
        Guid productId,
        CancellationToken cancellationToken);
}

Step 3: Implement HTTP Client

using System.Net.Http.Json;
public class ProductApiClient : IProductApiClient
{
    private readonly HttpClient _httpClient;
    public ProductApiClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }
    public async Task<ProductDto?> GetProductAsync(
        Guid productId,
        CancellationToken cancellationToken)
    {
        return await _httpClient.GetFromJsonAsync<ProductDto>(
            $"/api/products/{productId}",
            cancellationToken);
    }
}

Step 4: Register the Typed HTTP Client

In Program.cs:

builder.Services.AddHttpClient<IProductApiClient, ProductApiClient>(
    client =>
    {
        client.BaseAddress =
            new Uri("https://product-service");
    });

The base URL is an example. In production, use environment-specific configuration and service discovery or internal DNS.

Step 5: Use the Client in Order Service

public class OrderApplicationService
{
    private readonly IProductApiClient _productClient;
    public OrderApplicationService(
        IProductApiClient productClient)
    {
        _productClient = productClient;
    }
    public async Task<ProductDto?> GetProductAsync(
        Guid productId,
        CancellationToken cancellationToken)
    {
        return await _productClient.GetProductAsync(
            productId,
            cancellationToken);
    }
}

Important HTTP Communication Best Practices

  • Use IHttpClientFactory or typed HTTP clients.
  • Set appropriate timeouts.
  • Pass CancellationToken through requests.
  • Configure resilience policies.
  • Avoid long synchronous service-to-service call chains.
  • Validate downstream responses.
  • Do not expose internal service URLs to public clients unnecessarily.

14. Asynchronous Communication Using Messaging

Asynchronous messaging allows services to communicate without requiring the receiving service to process a message immediately.

Example: Order Creation

Suppose a customer places an order.

  1. Order Service creates an order with Pending status.
  2. Order Service publishes an OrderCreated event.
  3. Inventory Service receives the event and reserves stock.
  4. Payment Service receives the event and processes payment.
  5. Notification Service receives the event and sends a notification.
  6. Order Service receives the relevant results and updates the order status.
                  CUSTOMER
                     |
                     v
                ORDER SERVICE
                     |
                     v
                ORDER DATABASE
                     |
                     v
                MESSAGE BROKER
                     |
          +----------+----------+
          |          |          |
          v          v          v
       PAYMENT   INVENTORY  NOTIFICATION
       SERVICE    SERVICE     SERVICE
          |          |          |
          v          v          v
       Payment   Inventory   Notification
       Database  Database     Database

What Is an Event?

An event represents something that has already happened in a system.

Examples:

  • OrderCreated
  • PaymentCompleted
  • PaymentFailed
  • InventoryReserved
  • OrderCancelled
  • UserRegistered

Create an OrderCreated Event

public record OrderCreatedEvent(
    Guid EventId,
    Guid OrderId,
    Guid CustomerId,
    decimal TotalAmount,
    DateTime OccurredAt);

Integration events should be treated as versioned contracts. Avoid exposing internal domain entities directly as message payloads.

Command vs Event

Command Event
Requests an action. Reports something that happened.
Usually directed to one logical handler. Can be consumed by multiple subscribers.
Example: ProcessPayment Example: PaymentCompleted
Usually imperative. Usually describes a past fact.

15. RabbitMQ vs Azure Service Bus vs Kafka

These technologies provide different messaging capabilities.

Feature RabbitMQ Azure Service Bus Kafka
Type Message broker Managed cloud message broker Distributed event streaming platform
Queue Yes Yes Topic partitions
Publish/Subscribe Yes Topics and subscriptions Yes
Message Retention Depends on queue configuration Depends on entity and message lifecycle Configurable retention
Dead Letter Supported through dead-letter exchanges and queues Built-in dead-letter subqueues Usually implemented with retry and dead-letter topics
Azure Integration Self-managed or hosted Native Azure managed service Self-managed or managed offerings
Typical Use Application messaging Enterprise application integration High-volume event streaming

When to Choose Which?

  • RabbitMQ: When you need flexible queues, exchanges and routing.
  • Azure Service Bus: When building enterprise messaging solutions on Azure.
  • Kafka: When you need durable event streams, replay and high-throughput event processing.

Azure Service Bus: Queue vs Topic

  • Queue: Point-to-point communication. A message is normally processed by one competing consumer.
  • Topic: Publish/subscribe communication. Multiple subscriptions can receive their own copy of a message.
                 ORDER SERVICE
                       |
                       v
                 ORDER CREATED
                       |
                       v
                 SERVICE BUS TOPIC
                       |
           +-----------+-----------+
           |           |           |
           v           v           v
       PAYMENT     INVENTORY   NOTIFICATION
     SUBSCRIPTION SUBSCRIPTION SUBSCRIPTION

Azure Service Bus Reliability

  • Use Peek-Lock for reliable message processing where redelivery is acceptable.
  • Complete a message only after successful processing.
  • Use dead-letter queues for messages that cannot be processed.
  • Use idempotent consumers to prevent duplicate business effects.
  • Use duplicate detection to reduce duplicate sends.
  • Use message sessions when ordered processing is required.
  • Monitor active messages and dead-letter counts.

16. YARP API Gateway Implementation

YARP stands for Yet Another Reverse Proxy.

It is a reverse proxy toolkit built on ASP.NET Core. It can be used to create an API Gateway for routing requests to backend microservices.

Why Do We Need an API Gateway?

Without an API Gateway:

       WEB APPLICATION
              |
       +------+------+------+
       |      |      |      |
       v      v      v      v
      User  Product Order Payment
      API     API    API    API

The frontend must know the address of every service.

With an API Gateway:

       WEB APPLICATION
              |
              v
         API GATEWAY
              |
       +------+------+------+
       |      |      |      |
       v      v      v      v
      User  Product Order Payment
      API     API    API    API

The frontend communicates through one gateway endpoint.

Step 1: Create API Gateway

dotnet new web -n ApiGateway
cd ApiGateway
dotnet add package Yarp.ReverseProxy

Step 2: Configure Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddReverseProxy()
    .LoadFromConfig(
        builder.Configuration.GetSection("ReverseProxy"));
var app = builder.Build();
app.MapReverseProxy();
app.Run();

Step 3: Configure appsettings.json

{
  "ReverseProxy": {
    "Routes": {
      "user-route": {
        "ClusterId": "user-cluster",
        "Match": {
          "Path": "/api/users/{**catch-all}"
        }
      },
      "product-route": {
        "ClusterId": "product-cluster",
        "Match": {
          "Path": "/api/products/{**catch-all}"
        }
      },
      "order-route": {
        "ClusterId": "order-cluster",
        "Match": {
          "Path": "/api/orders/{**catch-all}"
        }
      }
    },
    "Clusters": {
      "user-cluster": {
        "Destinations": {
          "destination1": {
            "Address": "http://user-service:8080/"
          }
        }
      },
      "product-cluster": {
        "Destinations": {
          "destination1": {
            "Address": "http://product-service:8080/"
          }
        }
      },
      "order-cluster": {
        "Destinations": {
          "destination1": {
            "Address": "http://order-service:8080/"
          }
        }
      }
    }
  }
}

Step 4: Test Gateway Routes

GET https://localhost:7000/api/users
GET https://localhost:7000/api/products
GET https://localhost:7000/api/orders

YARP forwards the requests to the configured backend services.

Additional API Gateway Responsibilities

  • Authentication and authorization policies.
  • Rate limiting.
  • Request logging.
  • Routing and path transformation.
  • API version routing.
  • Forwarding correlation and tracing information.

Important: An API Gateway should not become a place for all business logic. Keep business rules inside their respective microservices.

17. Authentication and Authorization

Security is critical in microservices because multiple independently deployed services communicate over a network.

Authentication

Authentication verifies who the user is.

Authorization

Authorization determines what an authenticated user is allowed to do.

JWT Authentication Flow

          CLIENT APPLICATION
                  |
                  v
             LOGIN REQUEST
                  |
                  v
           IDENTITY PROVIDER
                  |
                  v
             ACCESS TOKEN
                  |
                  v
              API GATEWAY
                  |
           TOKEN VALIDATION
                  |
                  v
           BACKEND MICROSERVICE
                  |
          CLAIMS / POLICY CHECK
                  |
                  v
             API RESPONSE

Recommended Identity Technologies

  • Microsoft Entra ID.
  • OAuth 2.0.
  • OpenID Connect.
  • JWT Bearer Authentication.

Step 1: Install JWT Authentication Package

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 2: Configure JWT Authentication

Example Program.cs:

using Microsoft.AspNetCore.Authentication.JwtBearer;
var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority =
            builder.Configuration["Authentication:Authority"];
        options.Audience =
            builder.Configuration["Authentication:Audience"];
        options.RequireHttpsMetadata = true;
    });
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

The Authority and Audience values must correspond to your actual identity provider and API registration. This configuration validates externally issued tokens; it does not create a token issuer.

Step 3: Protect an API

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    [Authorize]
    [HttpGet]
    public IActionResult GetOrders()
    {
        return Ok("Authorized user can access orders.");
    }
    [Authorize(Roles = "Admin")]
    [HttpDelete("{id}")]
    public IActionResult DeleteOrder(Guid id)
    {
        return Ok("Order deletion authorized.");
    }
}

Security Best Practices

  • Validate issuer, audience, signature and token lifetime.
  • Use HTTPS for all external and internal API traffic where appropriate.
  • Use short-lived access tokens according to security requirements.
  • Never store access tokens in application logs.
  • Use least-privilege authorization policies.
  • Do not trust a request merely because it came through the API Gateway.
  • Validate authorization independently in each protected service.

18. Inter-Service Security

Microservices must authenticate and authorize communication between themselves, not just communication from users.

Common approaches include:

  • Managed identities in Azure.
  • OAuth 2.0 client credentials for machine-to-machine access.
  • Mutual TLS where appropriate.
  • Workload identity in AKS.
  • Network policies and private networking.

For Azure-hosted services, prefer managed identity or workload identity over storing long-lived client secrets in application configuration.

19. Distributed Transactions and Saga Pattern

In a monolithic application, multiple database operations may be handled within one database transaction.

In microservices, each service owns a separate database. A single traditional database transaction generally cannot safely cover the entire business operation across all services.

For this reason, distributed workflows often use the Saga Pattern.

Example: Order Processing

Suppose a customer places an order.

  1. Order Service creates the order.
  2. Inventory Service reserves the stock.
  3. Payment Service processes the payment.
  4. Order Service marks the order as confirmed.

What happens if payment fails after inventory has been reserved?

The system needs a compensating action to release the reserved stock.

Saga Flow

             CREATE ORDER
                  |
                  v
            RESERVE STOCK
                  |
                  v
            PROCESS PAYMENT
                  |
             +----+----+
             |         |
           SUCCESS   FAILURE
             |         |
             v         v
        CONFIRM      RELEASE
         ORDER        STOCK
             |         |
             v         v
          COMPLETE   CANCEL ORDER

Two Saga Approaches

1. Choreography

Each service publishes events and other services react to those events.

 OrderCreated
      |
      v
 Inventory Service
      |
 StockReserved
      |
      v
 Payment Service
      |
 PaymentCompleted
      |
      v
 Order Service

2. Orchestration

A central workflow coordinator tells each service which operation to perform.

             SAGA ORCHESTRATOR
                     |
          +----------+----------+
          |          |          |
          v          v          v
       ORDER     INVENTORY   PAYMENT
       SERVICE    SERVICE    SERVICE
Choreography Orchestration
Services react to events. Coordinator manages workflow.
No central workflow controller. Central workflow controller.
Can become difficult to understand with many events. Workflow is easier to visualize centrally.
Suitable for simpler event-driven workflows. Suitable for complex workflows with multiple steps.

Important: Saga transactions use local transactions and compensating actions. A compensation is a new business operation, not a database rollback of every previous service.

20. Event-Driven Architecture

Event-driven architecture allows services to react to events generated by other services.

Example:

          ORDER SERVICE
                |
                v
          OrderCreated Event
                |
                v
           MESSAGE BROKER
                |
       +--------+--------+
       |        |        |
       v        v        v
    PAYMENT INVENTORY NOTIFICATION
    SERVICE  SERVICE   SERVICE

Benefits

  • Loose coupling between services.
  • Independent event consumers.
  • Better support for background processing.
  • Ability to add new subscribers without changing the publisher's business logic.
  • Improved scalability for asynchronous workloads.

Important Event-Driven Concepts

Concept Explanation
Event Something that has already happened.
Publisher Service that publishes an event.
Subscriber Service that consumes an event.
Broker Transfers and distributes messages.
Consumer Application that processes messages.
Dead Letter Queue Stores messages that cannot be processed successfully.
Idempotency Repeated processing does not create additional business effects.
Eventual Consistency Related service data becomes consistent over time.

21. Transactional Outbox Pattern

One important problem in event-driven microservices is the dual-write problem.

Suppose Order Service performs two operations:

  1. Saves an order in the database.
  2. Publishes an OrderCreated event to the message broker.

What happens if the database save succeeds but publishing the event fails?

The order exists, but other services never receive the event.

The Transactional Outbox Pattern solves this by storing the business change and the event record in the same local database transaction.

             ORDER SERVICE
                   |
                   v
             DATABASE TRANSACTION
                   |
           +-------+-------+
           |               |
           v               v
       ORDERS TABLE    OUTBOX TABLE
           |               |
           +-------+-------+
                   |
              COMMIT
                   |
                   v
             OUTBOX WORKER
                   |
                   v
              MESSAGE BROKER
                   |
                   v
              EVENT CONSUMERS

Outbox Table Example

public class OutboxMessage
{
    public Guid Id { get; set; }
    public string EventType { get; set; } = "";
    public string Payload { get; set; } = "";
    public DateTime OccurredAt { get; set; }
    public DateTime? ProcessedAt { get; set; }
}

When creating an order, save the order and outbox message together:

await using var transaction =
    await dbContext.Database.BeginTransactionAsync(
        cancellationToken);
dbContext.Orders.Add(order);
dbContext.OutboxMessages.Add(
    new OutboxMessage
    {
        Id = Guid.NewGuid(),
        EventType = "OrderCreated",
        Payload = JsonSerializer.Serialize(orderEvent),
        OccurredAt = DateTime.UtcNow
    });
await dbContext.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);

A background worker reads unpublished outbox records and publishes them to the broker.

Important: The publisher can fail after the broker accepts a message but before the outbox record is marked as processed. Therefore, consumers must still support duplicate messages through idempotent processing.

22. Redis Caching

Redis is an in-memory data store commonly used for distributed caching.

It can reduce database load and improve response times for frequently accessed data.

Example

Suppose Product Service receives thousands of requests for the same product.

Without caching:

       CLIENT REQUEST
             |
             v
        PRODUCT API
             |
             v
          DATABASE
             |
             v
          RESPONSE

With Redis:

       CLIENT REQUEST
             |
             v
        PRODUCT API
             |
             v
          REDIS CACHE
             |
        +----+----+
        |         |
       HIT       MISS
        |         |
        v         v
      RETURN   DATABASE
        |         |
        |         v
        |      REDIS SET
        |         |
        +----+----+
             |
             v
          RESPONSE

Install Redis Cache Package

dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

Configure Redis

In Program.cs:

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration =
        builder.Configuration.GetConnectionString("Redis");
    options.InstanceName = "ProductService:";
});

Use IDistributedCache

using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
public class ProductCacheService
{
    private readonly IDistributedCache _cache;
    public ProductCacheService(IDistributedCache cache)
    {
        _cache = cache;
    }
    public async Task SetProductAsync(
        Guid id,
        ProductDto product,
        CancellationToken cancellationToken)
    {
        var json = JsonSerializer.Serialize(product);
        await _cache.SetStringAsync(
            $"product:{id}",
            json,
            new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow =
                    TimeSpan.FromMinutes(10)
            },
            cancellationToken);
    }
    public async Task<ProductDto?> GetProductAsync(
        Guid id,
        CancellationToken cancellationToken)
    {
        var json = await _cache.GetStringAsync(
            $"product:{id}",
            cancellationToken);
        return json is null
            ? null
            : JsonSerializer.Deserialize<ProductDto>(json);
    }
}

Redis Best Practices

  • Use appropriate cache expiration.
  • Choose meaningful cache key naming conventions.
  • Implement cache invalidation when data changes.
  • Avoid storing sensitive information unnecessarily.
  • Monitor memory usage and eviction policies.
  • Handle cache outages gracefully.
  • Prevent cache stampedes for frequently accessed keys.
  • Do not use Redis as the only permanent store for critical business data unless specifically designed and operated for that purpose.

23. Resilience and Fault Tolerance

In microservices architecture, network failures, service outages and temporary infrastructure problems are normal possibilities.

Resilience ensures that the system handles failures gracefully.

Important Resilience Patterns

1. Retry Pattern

Retries a failed operation when the failure is likely to be temporary.

2. Circuit Breaker Pattern

Temporarily stops calls to a failing service to prevent continuous failures.

3. Timeout Pattern

Stops waiting when a request takes longer than the allowed duration.

4. Bulkhead Pattern

Isolates resources so that failure in one area does not consume all application resources.

5. Fallback Pattern

Returns an alternative response when the primary operation is unavailable, where the business operation permits it.

Circuit Breaker Flow

           SERVICE REQUEST
                 |
                 v
            CIRCUIT CLOSED
                 |
          Request failures
                 |
                 v
            CIRCUIT OPEN
                 |
        Requests temporarily
             rejected
                 |
                 v
          CIRCUIT HALF-OPEN
                 |
          Test request succeeds
                 |
                 v
            CIRCUIT CLOSED

Configure HTTP Resilience in ASP.NET Core

Install the standard resilience package:

dotnet add package Microsoft.Extensions.Http.Resilience

Register the resilience handler:

builder.Services
    .AddHttpClient<IProductApiClient, ProductApiClient>()
    .AddStandardResilienceHandler(options =>
    {
        options.TotalRequestTimeout.Timeout =
            TimeSpan.FromSeconds(20);
        options.AttemptTimeout.Timeout =
            TimeSpan.FromSeconds(5);
    });

This adds a standard resilience pipeline. Review its retry, timeout and circuit-breaker settings for your particular workload.

Important: Do not blindly retry non-idempotent operations such as payment creation. Use idempotency keys and business-level duplicate protection before retrying operations that could produce duplicate effects.

24. Centralized Configuration and Secrets

Configuration Management

Microservices need configuration values such as:

  • Database connection settings.
  • Redis endpoints.
  • Message broker settings.
  • Service URLs.
  • Feature flags.

Azure App Configuration can centralize application settings and feature flags.

Secret Management

Secrets include:

  • Database passwords.
  • API keys.
  • Certificates.
  • External service credentials.

Use Azure Key Vault to securely manage secrets and certificates.

Recommended Azure Approach

             AZURE ENVIRONMENT
                    |
          +---------+---------+
          |                   |
          v                   v
   APP CONFIGURATION      KEY VAULT
          |                   |
          v                   v
    Application Settings   Secrets
          |                   |
          +---------+---------+
                    |
                    v
               AKS PODS
                    |
             WORKLOAD IDENTITY
  • Use Managed Identity for supported Azure services.
  • Use AKS Workload Identity for workloads that need Azure resource access.
  • Use least-privilege access policies or Azure RBAC.
  • Rotate credentials and certificates according to policy.
  • Never hardcode production secrets in source code.
  • Never commit production credentials to Git.

25. Logging, Monitoring and Distributed Tracing

In microservices, a single business request may travel through multiple services.

For example:

          CUSTOMER REQUEST
                 |
                 v
             API GATEWAY
                 |
                 v
            ORDER SERVICE
                 |
                 v
           PAYMENT SERVICE
                 |
                 v
          INVENTORY SERVICE
                 |
                 v
         NOTIFICATION SERVICE

If the order fails, identifying the failing service requires visibility across the entire request flow.

Three Pillars of Observability

Pillar Meaning Example
Logs Records of application events. Payment processing failed.
Metrics Numerical measurements over time. API response time: 250 ms.
Traces Shows how a request travels across services. Gateway → Order → Payment.

Distributed Tracing

Distributed tracing follows a request across multiple services using trace identifiers and spans.

              TRACE ID: ABC123
                     |
                     v
                API GATEWAY
                Span 1: 20ms
                     |
                     v
                ORDER SERVICE
                Span 2: 50ms
                     |
                     v
                PAYMENT SERVICE
                Span 3: 150ms
                     |
                     v
               INVENTORY SERVICE
                Span 4: 30ms

This helps identify which service or dependency contributes to latency.

OpenTelemetry Integration

Install the required packages according to the telemetry signals you want to export.

dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Instrumentation.Http
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol

Configure basic tracing in Program.cs:

using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource =>
        resource.AddService("OrderService"))
    .WithTracing(tracing =>
    {
        tracing
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddOtlpExporter();
    });
var app = builder.Build();
app.MapControllers();
app.Run();

Configure the OTLP exporter endpoint using environment-specific configuration and ensure an OpenTelemetry-compatible collector or backend is available.

Common Monitoring Tools

  • Azure Monitor.
  • Application Insights.
  • Log Analytics Workspace.
  • OpenTelemetry Collector.
  • Prometheus.
  • Grafana.

26. Health Checks

Health checks help determine whether an application or its dependencies are functioning properly.

Types of Health Checks

  • Liveness: Determines whether the application process should be restarted.
  • Readiness: Determines whether the application is ready to receive traffic.
  • Startup: Allows time for an application to initialize before other probes are evaluated.

Install Health Checks Package

dotnet add package AspNetCore.HealthChecks.SqlServer

Configure Health Checks

builder.Services
    .AddHealthChecks()
    .AddSqlServer(
        builder.Configuration.GetConnectionString("ProductDatabase")!);
var app = builder.Build();
app.MapHealthChecks("/health");
app.MapHealthChecks("/health/ready");
app.Run();

This is a basic example. For production, configure separate health-check tags and predicates for readiness and liveness. Do not make liveness depend on external databases or brokers, because a dependency outage could otherwise cause unnecessary application restarts.

Example Health Endpoints

GET /health/live
GET /health/ready

27. Docker and Containerization

Docker packages an application and its runtime dependencies into a container image.

Each microservice can have its own Docker image.

Example Dockerfile for ASP.NET Core

FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY . .
RUN dotnet restore ProductService.Api/ProductService.Api.csproj
RUN dotnet publish ProductService.Api/ProductService.Api.csproj \
    -c Release \
    -o /app/publish
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
WORKDIR /app
COPY --from=build /app/publish .
EXPOSE 8080
ENTRYPOINT ["dotnet", "ProductService.Api.dll"]

The .NET 10 image tags are examples for a .NET 10 project. Select an SDK and runtime version supported by your application.

Build Docker Image

docker build -t product-service:v1 .

Run Docker Container

docker run -d \
  -p 8080:8080 \
  --name product-service \
  product-service:v1

Check Running Containers

docker ps

View Container Logs

docker logs product-service

28. Docker Compose for Local Microservices

Docker Compose can run multiple related services locally.

Example docker-compose.yml:

services:
  product-service:
    build:
      context: ./ProductService
    ports:
      - "7001:8080"
    depends_on:
      - product-db
  order-service:
    build:
      context: ./OrderService
    ports:
      - "7002:8080"
    depends_on:
      - order-db
  product-db:
    image: mcr.microsoft.com/mssql/server:2022-latest
    environment:
      ACCEPT_EULA: "Y"
      MSSQL_SA_PASSWORD: "${PRODUCT_DB_PASSWORD}"
    volumes:
      - product-data:/var/opt/mssql
  order-db:
    image: mcr.microsoft.com/mssql/server:2022-latest
    environment:
      ACCEPT_EULA: "Y"
      MSSQL_SA_PASSWORD: "${ORDER_DB_PASSWORD}"
    volumes:
      - order-data:/var/opt/mssql
volumes:
  product-data:
  order-data:

The passwords should be provided through an appropriately protected local environment file or secret mechanism. Do not commit real passwords.

Start the services:

docker compose up -d

Stop the services:

docker compose down

29. Kubernetes and Azure Kubernetes Service (AKS)

Kubernetes orchestrates containers and manages their deployment, scaling, networking and recovery.

Azure Kubernetes Service provides a managed Kubernetes platform in Azure.

Important Kubernetes Components

Component Purpose
Cluster Collection of Kubernetes nodes.
Node Machine that runs Pods.
Pod Smallest deployable unit containing one or more containers.
Deployment Manages application Pod replicas and updates.
ReplicaSet Maintains the desired number of Pod replicas.
Service Provides a stable network endpoint for Pods.
Ingress Manages external HTTP/HTTPS routing through an ingress controller.
ConfigMap Stores non-sensitive configuration.
Secret Stores sensitive configuration data, subject to appropriate protection.
Namespace Provides logical separation of Kubernetes resources.

AKS Architecture

                    AZURE
                      |
                      v
              AZURE KUBERNETES
                 SERVICE
                      |
                AKS CLUSTER
                      |
           +----------+----------+
           |                     |
           v                     v
        NODE 1                NODE 2
           |                     |
      +----+----+           +----+----+
      |         |           |         |
      v         v           v         v
    USER     PRODUCT      ORDER    PAYMENT
    POD       POD          POD      POD
      |         |           |         |
      v         v           v         v
   CONTAINER CONTAINER   CONTAINER CONTAINER

Step 1: Login to Azure

az login

Step 2: Create AKS Cluster

az aks create \
  --resource-group MyResourceGroup \
  --name MyAKSCluster \
  --node-count 2 \
  --generate-ssh-keys

This is a simplified learning example. Production cluster sizing, identity, networking, security and availability settings require workload-specific planning.

Step 3: Connect to AKS

az aks get-credentials \
  --resource-group MyResourceGroup \
  --name MyAKSCluster

Step 4: Check Nodes

kubectl get nodes

Step 5: Check Pods

kubectl get pods -A

Step 6: Check Pod Details

kubectl describe pod <pod-name>

Step 7: Check Pod Logs

kubectl logs <pod-name>

30. Kubernetes Deployment YAML

Example deployment for Product Service:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: product-service
spec:
  replicas: 3
  selector:
    matchLabels:
      app: product-service
  template:
    metadata:
      labels:
        app: product-service
    spec:
      containers:
        - name: product-service
          image: myregistry.azurecr.io/product-service:v1
          ports:
            - containerPort: 8080
          resources:
            requests:
              cpu: "100m"
              memory: "128Mi"
            limits:
              cpu: "500m"
              memory: "512Mi"
          readinessProbe:
            httpGet:
              path: /health/ready
              port: 8080
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /health/live
              port: 8080
            periodSeconds: 20

Apply Deployment

kubectl apply -f product-deployment.yaml

Check Deployment

kubectl get deployments

Scale Deployment

kubectl scale deployment product-service --replicas=5

Kubernetes attempts to maintain five desired replicas.

Rolling Update

kubectl set image deployment/product-service \
  product-service=myregistry.azurecr.io/product-service:v2

Rollback

kubectl rollout undo deployment/product-service

Check Rollout Status

kubectl rollout status deployment/product-service

31. CI/CD Pipeline

CI/CD automates building, testing, packaging and deploying microservices.

Continuous Integration

  • Developer commits code.
  • Pipeline restores dependencies.
  • Application is built.
  • Unit tests execute.
  • Code quality checks run.
  • Container image is built.
  • Image is scanned and published to a container registry.

Continuous Deployment

  • Deploy to development.
  • Execute integration tests.
  • Deploy to QA or staging.
  • Run acceptance and security tests.
  • Deploy progressively to production.
  • Monitor deployment health.
  • Promote or roll back based on health criteria.

CI/CD Flow

           DEVELOPER
               |
               v
          GIT COMMIT
               |
               v
          CI PIPELINE
               |
       +-------+-------+
       |       |       |
       v       v       v
      BUILD   TEST   SCAN
       |       |       |
       +-------+-------+
               |
               v
         DOCKER IMAGE
               |
               v
          ACR REGISTRY
               |
               v
        CD DEPLOYMENT
               |
               v
              AKS
               |
               v
           MONITORING

Azure Container Registry (ACR) stores private container images that can be deployed to AKS.

32. Testing Microservices

Testing is essential because microservices contain independently deployed components that communicate over networks.

Types of Testing

Testing Type Purpose Example
Unit Testing Test individual business logic. Product price validation.
Integration Testing Test interactions with infrastructure. API with database.
Contract Testing Validate communication contracts. Order Service and Product Service API contract.
Component Testing Test one service as a component. Product Service with its dependencies.
End-to-End Testing Test complete business workflows. Customer places an order.
Performance Testing Measure performance under load. Thousands of order requests.
Resilience Testing Validate behavior during failures. Payment Service becomes unavailable.

Unit Test Example Using xUnit

using Xunit;
public class ProductTests
{
    [Fact]
    public void Product_ShouldHaveCorrectPrice()
    {
        var product = new Product(
            "Laptop",
            "Business Laptop",
            50000,
            10);
        Assert.Equal(50000, product.Price);
    }
}

Integration Testing

ASP.NET Core provides WebApplicationFactory for testing API applications in an integration-test environment.

public class ProductApiTests :
    IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;
    public ProductApiTests(
        WebApplicationFactory<Program> factory)
    {
        _client = factory.CreateClient();
    }
    [Fact]
    public async Task GetProducts_ReturnsSuccess()
    {
        var response =
            await _client.GetAsync("/api/products");
        response.EnsureSuccessStatusCode();
    }
}

Use an isolated test database or suitable test containers for realistic integration tests. Do not accidentally connect integration tests to production databases.

33. Performance Optimization

Microservices performance depends on application code, database operations, network communication, messaging and infrastructure.

Application-Level Optimization

  • Use asynchronous programming for I/O operations.
  • Avoid unnecessary object allocations.
  • Use efficient serialization.
  • Use pagination for large datasets.
  • Use caching for frequently accessed data.
  • Avoid unnecessary database queries.
  • Use connection pooling appropriately.
  • Profile before optimizing.

Database Optimization

  • Create indexes based on actual query patterns.
  • Use AsNoTracking for read-only EF Core queries where appropriate.
  • Avoid N+1 query problems.
  • Select only required columns.
  • Use pagination.
  • Review execution plans.
  • Monitor connection pool utilization.

Network Optimization

  • Reduce unnecessary service-to-service calls.
  • Prefer coarse-grained API operations over many tiny calls.
  • Use HTTP connection pooling.
  • Consider gRPC for suitable internal communication.
  • Use asynchronous messaging for decoupled operations.
  • Avoid long synchronous dependency chains.

Important Performance Metrics

Metric Meaning
Response Time Time required to complete a request.
Throughput Requests processed per second.
Error Rate Percentage of failed requests.
CPU Usage Processor consumption.
Memory Usage Memory consumption.
Database Latency Time spent executing database operations.
Queue Depth Number of pending messages.
Consumer Lag Delay between event production and consumption.

34. Security Best Practices

  1. Use OAuth 2.0 and OpenID Connect for identity management.
  2. Validate JWT tokens in every protected API.
  3. Use HTTPS and appropriate internal network protections.
  4. Use Azure Key Vault for secrets.
  5. Use Managed Identity and Workload Identity where supported.
  6. Apply least-privilege access permissions.
  7. Validate and sanitize incoming data.
  8. Protect against SQL injection through parameterized queries and safe ORM usage.
  9. Apply rate limiting to public APIs.
  10. Scan container images for vulnerabilities.
  11. Keep dependencies updated.
  12. Use network policies to restrict unnecessary communication.
  13. Do not expose internal services publicly without a valid requirement.
  14. Never log passwords, access tokens or sensitive personal information.
  15. Maintain audit logs for important business operations.

35. Production Deployment Architecture on Azure

A possible production architecture using Azure services is shown below.

INTERNET AZURE FRONT DOOR API GATEWAY / YARP AZURE KUBERNETES SERVICE (AKS) USER SERVICE PRODUCT SERVICE ORDER SERVICE AZURE SQL DB User Database AZURE SQL DB Product Database AZURE SQL DB Order Database Asynchronous messaging AZURE SERVICE BUS PAYMENT SERVICE INVENTORY SERVICE NOTIFICATION SERVICE PAYMENT DATABASE INVENTORY DATABASE NOTIFICATION STORAGE SUPPORTING AZURE SERVICES Azure Container Registry Azure Key Vault Azure App Configuration Azure Monitor Application Insights Log Analytics Azure Managed Redis

This is an example architecture. Actual service selection, network boundaries, ingress, database topology and availability configuration depend on workload requirements.

Azure Services and Their Responsibilities

Azure Service Responsibility
AKS Container orchestration.
Azure Container Registry Stores container images.
Azure Service Bus Asynchronous messaging.
Azure SQL Database Relational data storage.
Azure Managed Redis Distributed caching.
Azure Key Vault Secret and certificate management.
Azure App Configuration Centralized application configuration.
Azure Monitor Monitoring and alerting.
Application Insights Application performance monitoring.
Azure Front Door Global HTTP/HTTPS entry point and routing.

36. Common Microservices Architecture Mistakes

Mistake Why It Is a Problem Better Approach
Sharing one database across all services Creates tight coupling. Maintain service-owned data.
Too many small services Increases operational complexity. Design around business boundaries.
Excessive HTTP calls Increases latency and dependencies. Use appropriate asynchronous communication.
No distributed tracing Makes debugging difficult. Implement OpenTelemetry.
No retry strategy Transient failures can interrupt operations. Use bounded retries and resilience.
Blind retries Can create duplicate business operations. Use idempotency.
No health probes Unhealthy containers may receive traffic. Configure appropriate probes.
Hardcoded secrets Creates security risks. Use Key Vault and workload identity.
Shared domain models Creates deployment and model coupling. Use service-specific models and versioned contracts.
No contract testing Changes can break consumers. Validate API and event contracts.

37. Complete Implementation Checklist

Architecture

  • Define business capabilities and bounded contexts.
  • Identify service ownership boundaries.
  • Define service communication contracts.
  • Decide synchronous and asynchronous communication.
  • Define database ownership.

ASP.NET Core Development

  • Create independent Web API projects.
  • Implement domain and application logic.
  • Configure dependency injection.
  • Integrate EF Core.
  • Implement validation and exception handling.
  • Configure structured logging.
  • Add health checks.

Communication

  • Configure typed HTTP clients.
  • Implement message publishing and consuming.
  • Define event contracts.
  • Implement idempotent consumers.
  • Configure retries and dead-letter handling.
  • Implement the Outbox Pattern where needed.

Security

  • Configure identity provider.
  • Implement JWT validation.
  • Configure authorization policies.
  • Secure service-to-service communication.
  • Configure Key Vault and workload identity.

Infrastructure

  • Create Dockerfiles.
  • Build and scan container images.
  • Push images to ACR.
  • Create AKS resources.
  • Configure Kubernetes deployments and services.
  • Configure ingress and networking.
  • Configure autoscaling where appropriate.

Monitoring and Deployment

  • Implement distributed tracing.
  • Configure metrics and centralized logs.
  • Create health-based alerts.
  • Build CI/CD pipelines.
  • Run automated tests.
  • Implement progressive deployments.
  • Define rollback procedures.

38. ASP.NET Core Microservices Interview Questions

Basic Questions

  1. What is microservices architecture?
  2. What is the difference between monolithic and microservices architecture?
  3. What are the advantages and disadvantages of microservices?
  4. What is a bounded context?
  5. What is database per service?
  6. What is an API Gateway?
  7. What is service discovery?
  8. What is the difference between synchronous and asynchronous communication?
  9. What is a message broker?
  10. What is eventual consistency?

Intermediate Questions

  1. How do microservices communicate with each other in ASP.NET Core?
  2. How do you implement HttpClientFactory?
  3. What is the difference between RabbitMQ and Azure Service Bus?
  4. What is the Saga Pattern?
  5. What is the Transactional Outbox Pattern?
  6. How do you implement distributed caching using Redis?
  7. How do you implement JWT authentication in microservices?
  8. What is distributed tracing?
  9. What is the difference between liveness and readiness probes?
  10. How does Kubernetes manage failed Pods?

Advanced Questions

  1. How do you handle distributed transactions?
  2. How do you prevent duplicate message processing?
  3. How do you implement idempotency?
  4. How do you handle message ordering?
  5. How do you implement service-to-service authentication?
  6. How do you prevent cascading failures?
  7. How do you troubleshoot high latency across multiple microservices?
  8. How do you implement zero-downtime deployments?
  9. How do you handle database schema changes across independent services?
  10. How do you monitor microservices running in AKS?

39. Recommended Learning and Implementation Order

If you are implementing microservices for the first time, follow this sequence rather than trying to implement every technology simultaneously.

  1. Step 1: Understand monolithic architecture and microservices fundamentals.
  2. Step 2: Build a Product Service using ASP.NET Core Web API.
  3. Step 3: Integrate EF Core and SQL Server.
  4. Step 4: Build User Service and Order Service independently.
  5. Step 5: Implement HTTP communication using HttpClientFactory.
  6. Step 6: Implement YARP API Gateway.
  7. Step 7: Implement JWT authentication and authorization.
  8. Step 8: Introduce RabbitMQ or Azure Service Bus.
  9. Step 9: Implement Saga and Outbox patterns.
  10. Step 10: Integrate Redis caching.
  11. Step 11: Implement logging, metrics and distributed tracing.
  12. Step 12: Containerize services using Docker.
  13. Step 13: Deploy services to AKS.
  14. Step 14: Implement CI/CD and production monitoring.

40. Official Microsoft Documentation and Learning Resources

Conclusion

ASP.NET Core microservices architecture helps build independently deployable, scalable and maintainable applications by separating business capabilities into individual services.

A successful implementation requires more than creating multiple Web APIs. It requires careful service boundaries, independent data ownership, reliable communication, security, observability, resilience, automated deployment and operational monitoring.

Recommended starting architecture: ASP.NET Core Web API + EF Core + SQL Server + YARP + Azure Service Bus + Redis + Docker. Once the application works locally, introduce AKS, CI/CD, OpenTelemetry and production-grade security.

🔙
Core Caching: In-Memory, Distributed Cache and Redis :👈 👉:N+1 query problem