AlgoDaily

Microservices Architecture

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Why This Matters

Microservices Architecture

Now that we've covered Introduction to CI/CD in Azure, Azure Cloud Overview, and Advanced C# Techniques, you're ready to connect those skills into a senior-level architecture conversation.

For a senior C# backend interview, microservices questions are rarely just: “What is a microservice?”

They are usually testing whether you can reason about:

  • Service boundaries: where one service ends and another begins
  • Deployment independence: how teams release safely without coordinating everything
  • Data ownership: avoiding shared database coupling
  • Communication tradeoffs: REST, messaging, events, consistency
  • Reliability: retries, timeouts, idempotency, observability
  • Azure implementation choices: App Service, AKS, Container Apps, Service Bus, API Management

The goal of this lesson is to give you an interview-ready mental model, not a buzzword list.

Why This Matters

Core Mental Model

What Microservices Really Mean

A microservices architecture structures a system as a set of independently deployable services, each responsible for a focused business capability.

A strong interview answer should include three ideas:

  1. Business ownership
    A service is not just a small project. It owns a meaningful business capability, such as Orders, Payments, Catalog, or Shipping.

  2. Independent change
    A team should be able to build, test, deploy, scale, and roll back a service without redeploying the whole system.

  3. Explicit contracts
    Services communicate through APIs, events, or messages — not by reaching into each other’s internal database tables.

A useful mental diagram:

Client
  |
  v
API Gateway / BFF
  |
  +--> Catalog Service  --> Catalog DB
  +--> Order Service    --> Order DB
  +--> Payment Service  --> Payment DB
  +--> Shipping Service --> Shipping DB

The important part is not that there are many boxes. The important part is that each box has a clear reason to exist.

Core Mental Model

Boundary Check

You are designing an e-commerce platform. Which is the strongest reason to split Payment into its own microservice?

Communication Choices

Synchronous vs Asynchronous Communication

In interviews, avoid saying “microservices use REST” as if that is the whole answer.

A senior answer compares communication styles:

Synchronous calls

Use when the caller needs an immediate answer.

Examples:

  • GET /products/{id} from Catalog
  • POST /orders/quote to calculate a quote
  • API Gateway calling a backend service

Tradeoff: simple request/response, but adds runtime coupling. If the downstream service is slow or unavailable, the caller feels it.

Asynchronous messaging

Use when work can happen later or when services should be loosely coupled.

Examples:

  • OrderPlaced event
  • PaymentAuthorized event
  • ShipmentRequested command

Tradeoff: better decoupling and resilience, but you must handle eventual consistency, duplicate messages, and monitoring.

In Azure, common choices include Azure Service Bus for enterprise messaging and Event Grid for event routing.

```csharp
using System;

public class Program
{
    public static void Main()
    {
        DescribeCommunication("GetProductDetails", needsImmediateAnswer: true);
        DescribeCommunication("SendWelcomeEmail", needsImmediateAnswer: false);
        DescribeCommunication("AuthorizePayment", needsImmediateAnswer: true);
        DescribeCommunication("PublishOrderPlaced", needsImmediateAnswer: false);
    }

    static void DescribeCommunication(string operation, bool needsImmediateAnswer)
    {
        var style = needsImmediateAnswer ? "Synchronous HTTP/gRPC" : "Asynchronous message/event";
        var risk = needsImmediateAnswer ? "watch timeouts and cascading failures" : "handle duplicates and eventual consistency";

        Console.WriteLine($"{operation}: use {style}; {risk}.");
    }
}
```

Size Is Not Enough

True or false: A service is a good microservice mainly because it is small and has few classes.

Data Ownership

The Database Rule

A common senior-level interview topic is data ownership.

In a healthy microservices architecture:

  • Each service owns its data model
  • Other services access that data through contracts, not table joins
  • Cross-service workflows use APIs, messages, or events
  • Some inconsistency is accepted temporarily and resolved through business processes

The phrase to remember is:

Do not split code while keeping one shared database as the real integration point.

That creates a distributed monolith: many deployable units that are still tightly coupled through schema changes.

Instead, services publish meaningful facts such as:

OrderPlaced
PaymentAuthorized
InventoryReserved
ShipmentCreated

This pushes the architecture toward explicit business events rather than hidden database dependencies.

```csharp
using System;
using System.Collections.Generic;

public record OrderPlaced(Guid OrderId, decimal Amount);

public class OrderService
{
    private readonly List<OrderPlaced> _outbox = new();

    public Guid PlaceOrder(decimal amount)
    {
        var orderId = Guid.NewGuid();
        _outbox.Add(new OrderPlaced(orderId, amount));
        Console.WriteLine($"OrderService: stored order {orderId} for {amount:C}");
        return orderId;
    }

    public IReadOnlyList<OrderPlaced> PullEvents() => _outbox;
}

public class PaymentService
{
    public void Handle(OrderPlaced message)
    {
        Console.WriteLine($"PaymentService: received OrderPlaced for {message.OrderId}; authorizing {message.Amount:C}");
    }
}

public class Program
{
    public static void Main()
    {
        var orders = new OrderService();
        var payments = new PaymentService();

        orders.PlaceOrder(129.99m);

        foreach (var evt in orders.PullEvents())
        {
            payments.Handle(evt);
        }
    }
}
```

Boundary Vocabulary

A service boundary should align with a business capability or domain area. In domain-driven design language, this is often called a ______ ______.

Reliability Patterns

Design For Failure

Microservices add network hops, independent deployments, and more runtime dependencies. That means failure is normal, not exceptional.

A strong senior answer mentions patterns like:

  • Timeouts: never wait forever for another service
  • Retries: retry transient failures, but with limits
  • Circuit breakers: stop calling a dependency that is clearly unhealthy
  • Fallbacks: return cached or degraded responses when appropriate
  • Idempotency: safely handle duplicate commands or messages
  • Observability: logs, metrics, traces, correlation IDs

From the earlier Advanced C# Techniques lesson, your async and diagnostics skills matter here. In production, async/await is not enough — you need cancellation, timeouts, and meaningful telemetry.

```csharp
using System;

public class Program
{
    private static int _attempts = 0;

    public static void Main()
    {
        var result = CallWithRetry(maxAttempts: 3);
        Console.WriteLine($"Final result: {result}");
    }

    static string CallWithRetry(int maxAttempts)
    {
        for (var attempt = 1; attempt <= maxAttempts; attempt++)
        {
            try
            {
                Console.WriteLine($"Calling Payment service, attempt {attempt}...");
                return CallPaymentService();
            }
            catch (TimeoutException ex)
            {
                Console.WriteLine($"Transient failure: {ex.Message}");

                if (attempt == maxAttempts)
                {
                    return "Fallback: payment status pending";
                }
            }
        }

        return "Unexpected state";
    }

    static string CallPaymentService()
    {
        _attempts++;
        if (_attempts < 3)
        {
            throw new TimeoutException("dependency timed out");
        }

        return "Payment authorized";
    }
}
```

Azure Implementation Map

Mapping Microservices To Azure

Use the Azure Cloud Overview lesson as your foundation: Azure gives you multiple compute and integration options. In an interview, do not claim there is one correct platform for all microservices.

A practical mapping:

Need Azure Option Simple hosted APIs Azure App Service Containerized services without full Kubernetes management Azure Container Apps Full orchestration and platform control Azure Kubernetes Service, AKS API gateway, routing, policies Azure API Management Enterprise messaging Azure Service Bus Event routing Azure Event Grid Secrets and certificates Azure Key Vault Logs, metrics, traces Azure Monitor + Application Insights

A good senior answer sounds like:

“I would choose the simplest Azure hosting model that satisfies scaling, networking, release, and operations requirements. I would not introduce AKS unless the team is ready to operate Kubernetes well.”

That answer shows architectural maturity.

Azure Implementation Map

Interview Cheat Sheet

Senior Microservices Cheat Sheet

Use this structure when answering architecture questions.

1. Start with tradeoffs

Microservices improve independent deployment, scaling, team autonomy, and fault isolation — but add operational complexity, distributed debugging, network failures, and data consistency challenges.

2. Define boundaries carefully

Good boundaries follow business capabilities. Avoid splitting by technical layers such as UserControllerService, UserRepositoryService, and UserDatabaseService.

3. Protect service autonomy

Each service should own its data and expose contracts. Shared databases are a common path to a distributed monolith.

4. Pick communication intentionally

Use synchronous calls for immediate answers. Use messaging/events for decoupling, long-running workflows, and resilience.

5. Make failure visible

Mention timeouts, retries, circuit breakers, idempotency, correlation IDs, distributed tracing, and dashboards.

6. Connect to delivery

Tie back to Introduction to CI/CD in Azure: independent services need independent pipelines, automated tests, quality gates, versioned contracts, and safe deployment patterns.

7. Connect to Azure

Tie back to Azure Cloud Overview: choose App Service, Container Apps, AKS, Service Bus, Event Grid, API Management, Key Vault, and Application Insights based on operational needs.

Next, the course moves into an Object Oriented Programming Refresher, which will sharpen how you explain encapsulation and design at the class level.

Interview Cheat Sheet

Open interactive view →