📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are microservices? Describe their defining characteristics, the benefits they bring, the costs they impose (the distributed systems tax), and how you decide whether they fit a given organisation and system.

Defines microservices by their characteristics (independent deployability, data ownership, business alignment), weighs benefits against the operational and consistency costs, and gives criteria for when they fit.

Mid-Level Theory Intermediate architecture conways-law data-ownership devops distributed-systems microservices

🎯 Key points

  • Independently deployable services, each owning one business capability and its own data
  • Communicate over the network: HTTP/gRPC for requests, messaging (Azure Service Bus) for events; an API gateway (YARP, Azure API Management) as the single entry point; service discovery (Kubernetes DNS, Aspire/Microsoft.Extensions.ServiceDiscovery)
  • Benefits: independent deploys and scaling, team autonomy, fault isolation, technology choice per service
  • Distributed systems tax: network latency and failure, eventual consistency, sagas instead of transactions, versioned contracts
  • Security per hop: token validation at every service, managed identities and mTLS for service-to-service calls, least-privilege per service
  • Observability is mandatory: OpenTelemetry distributed tracing, correlation IDs, per-service SLOs and dashboards
  • Conway's law: boundaries mirror teams; fit when many teams need independent releases and boundaries are stable — otherwise start with a modular monolith
  • Anti-pattern: the distributed monolith — services that must deploy together or share a database

⏱ 30-second answer

Microservices are small, independently deployable services, each owning one business capability and its own data, talking over the network via APIs or messages.

  • Benefits: independent deployment and scaling, team autonomy, fault isolation, technology choice per service.
  • The distributed systems tax: network latency and partial failure, eventual consistency and sagas instead of transactions, versioned contracts, distributed tracing, and many pipelines and on-call rotations.
  • They mainly solve an organisational problem: many teams needing to release without coordinating (Conway's law).

They fit when you have several teams, stable boundaries and mature DevOps. Otherwise a modular monolith gives most of the benefits for a fraction of the cost. The worst outcome is a distributed monolith: all the cost, none of the independence.

🗣 Full answer (senior)

How I would answer this in an interview

"A microservice architecture splits a system into small services that are independently deployable, each owning one business capability and — crucially — its own data. Orders, Payments and Inventory each have their own database and talk over HTTP or gRPC for requests and over a broker like Azure Service Bus for events. The defining test is: can this team deploy their service on a Tuesday afternoon without coordinating with anyone? If not, it isn't really a microservice.

The benefits are real: teams release independently, you scale the hot part rather than everything, a failure in recommendations doesn't take down checkout, and a service can use the right technology. But you pay the distributed systems tax. Every in-process call becomes a network call that can be slow or fail, so you need timeouts, retries and circuit breakers. You lose cross-service transactions, so you need sagas, outboxes and idempotent consumers, and your users see eventual consistency. Debugging needs distributed tracing with OpenTelemetry. And each service has its own pipeline, alerts and on-call. For example, at [company] we [split a monolith into N services]; [deployment frequency rose from X to Y], but [our incident count from cross-service timeouts doubled until we invested in resilience and tracing].

The mistake I see is adopting microservices for technical reasons with one or two teams. Microservices are mainly an answer to an organisational scaling problem — many teams stepping on each other. If you don't have that problem, a modular monolith gets you clean boundaries without the tax. And if your services share a database or must release together, you've built a distributed monolith, which is the worst of both worlds."


Characteristics

Characteristic What it means How to check
Independently deployable Release one service without others Can you deploy it alone, today?
Owns its data Database per service; no shared writes Does any other service connect to its database?
Business-aligned Organised around a capability (Payments), not a layer Can you name its business outcome?
Owned by one team "You build it, you run it" Is there exactly one owning team on-call?
Smart endpoints, dumb pipes Logic in services, not in the broker Is there routing or business logic in an ESB?

Benefits vs costs

Benefit Matching cost
Independent deployment Contract versioning, backward compatibility, consumer-driven contract tests
Independent scaling Network latency (1–5 ms per hop in-region), serialisation, more infrastructure
Fault isolation Partial failure everywhere: timeouts, retries, circuit breakers, bulkheads
Team autonomy Duplicated effort, platform team needed, consistency of practices
Data ownership No joins or transactions across services: sagas, outbox, eventual consistency, reporting pipelines

Decision table

Factor Microservices fit Prefer modular monolith
Teams 5+ teams blocked by shared releases 1–4 teams
Boundaries Stable, proven (ideally already modules) Still being discovered
Scale profile Parts with very different load Uniform load
DevOps maturity Automated pipelines, IaC, tracing, on-call per team Manual or shared deployments
Consistency needs Business accepts eventual consistency Strong cross-entity consistency everywhere

Production example

A retailer moved checkout, catalogue and recommendations into separate services on Azure Kubernetes Service. During a Black Friday peak, recommendations failed under load, but because checkout called it with a 300 ms timeout and a fallback to "popular items", checkout stayed at 99.95% availability. The same failure in the old monolith had taken the whole site down for 40 minutes the year before.

🔍 What the interviewer is checking

Checks that the candidate understands microservices as a trade-off with a real organisational driver, and can name concrete costs and fit criteria.

Green flags

  • Defines them by independent deployability and data ownership
  • Names specific costs: eventual consistency, sagas, tracing, versioning, operational load
  • Mentions Conway's law or team structure as a driver
  • Recommends a modular monolith when the fit is weak, and knows the distributed monolith anti-pattern

Red flags

  • "Microservices are small services" with no mention of data or deployment
  • Claims they are always more scalable
  • Ignores operational and consistency costs

📚 Learn in depth

1. The shape

                 +-------------+
  Browser -----> | API gateway |  (YARP / Azure API Management)
                 +------+------+
          +-------------+--------------+
          v             v              v
   +-----------+  +-----------+  +-------------+
   |  Orders   |  | Payments  |  | Inventory   |
   |  service  |  |  service  |  |  service    |
   +-----+-----+  +-----+-----+  +------+------+
         |              |               |
     [orders db]   [payments db]   [inventory db]
         \______________|_______________/
                        v
              [ Azure Service Bus topics ]   (OrderPlaced, PaymentCaptured ...)

2. The fallacies of distributed computing

Peter Deutsch's list (1994) is why the tax exists. The network is not reliable, latency is not zero, bandwidth is not infinite, the network is not secure, topology does change, there is not one administrator, transport cost is not zero, and the network is not homogeneous. Each fallacy maps to work: retries and idempotency, timeouts, payload design, mTLS and managed identity, service discovery, ownership, cost monitoring, and contract standards.

3. Consistency without transactions

Placing an order that reserves stock and takes payment spans three databases. Options:

  • Saga (orchestrated or choreographed) with compensating actions.
  • Outbox in each service so state change and event publication are atomic.
  • Inbox / idempotent consumers because delivery is at-least-once.

Users see intermediate states ("Payment pending"), so the UX must be designed for it.

4. Latency compounds

If a request fans out sequentially to 5 services at 20 ms p50 each, p50 is 100 ms; but tail latency compounds worse: if each call has a 1% chance of exceeding 500 ms, the chance at least one of 5 does is about 4.9%. Parallel calls, caching and asynchronous messaging are how you fight this.

5. Conway's law

"Organisations design systems that mirror their communication structure" (Melvin Conway, 1968). Microservices work when each service maps to one team. If two teams must change a service together, the boundary is wrong; if one team owns 12 services, the overhead dominates. The inverse Conway manoeuvre shapes teams to get the architecture you want.

6. The distributed monolith

Symptoms: services share a database, must be deployed in a fixed order, call each other synchronously in long chains, or share a "common" library with domain types that forces lock-step upgrades. Fix by consolidating services that change together, giving each its own data, and moving to events.

7. Platform prerequisites

Before splitting: CI/CD per service, infrastructure as code (Bicep/Terraform), centralised logging and OpenTelemetry tracing (Application Insights / Azure Monitor), health checks, secrets in Key Vault with managed identity, and an on-call model. .NET Aspire helps locally with orchestration, service defaults and telemetry, but doesn't replace production platform work.

Try it yourself

  1. Build two Minimal API services where one calls the other; add a 2-second delay to the callee and watch the caller's thread and latency behaviour without a timeout.
  2. Add AddStandardResilienceHandler() and repeat.
  3. Add OpenTelemetry tracing to both and view the trace in the Aspire dashboard.
  4. Calculate the probability of a slow request for 3, 5 and 10 sequential calls at a 1% per-call tail.
  5. Map your organisation's teams against your services and find any service with two owners or none.

💻 Code

A service-to-service call with the minimum production hygiene: a typed client, resilience, a timeout, a fallback and tracing.

// Checkout service: calling the Recommendations service
namespace Checkout.Recommendations;

using System.Net.Http.Json;

public sealed record ProductSuggestion(string Sku, string Name);

public sealed class RecommendationsClient(HttpClient http, ILogger<RecommendationsClient> logger)
{
    private static readonly ProductSuggestion[] Popular = [new("SKU-1", "Gift card"), new("SKU-2", "Tote bag")];

    public async Task<IReadOnlyList<ProductSuggestion>> GetForBasketAsync(Guid basketId, CancellationToken ct)
    {
        try
        {
            return await http.GetFromJsonAsync<ProductSuggestion[]>($"suggestions/{basketId}", ct) ?? Popular;
        }
        catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or Polly.CircuitBreaker.BrokenCircuitException)
        {
            // Recommendations are non-critical: degrade instead of failing checkout.
            logger.LogWarning(ex, "Recommendations unavailable for basket {BasketId}; using fallback", basketId);
            return Popular;
        }
    }
}
// Program.cs
using Checkout.Recommendations;
using Microsoft.Extensions.Http.Resilience;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient<RecommendationsClient>(c =>
        c.BaseAddress = new Uri("https+http://recommendations")) // service discovery name (Aspire / Microsoft.Extensions.ServiceDiscovery)
    .AddStandardResilienceHandler(o =>
    {
        o.AttemptTimeout.Timeout = TimeSpan.FromMilliseconds(300);   // per try
        o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(1);     // whole call including retries
        o.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(10); // must be >= 2x attempt timeout
    });

builder.Services.AddOpenTelemetry()
    .WithTracing(t => t.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation());

var app = builder.Build();
app.MapGet("/checkout/{basketId:guid}/suggestions", (Guid basketId, RecommendationsClient client, CancellationToken ct) =>
    client.GetForBasketAsync(basketId, ct));
app.Run();

Packages: Microsoft.Extensions.Http.Resilience, Microsoft.Extensions.ServiceDiscovery and OpenTelemetry.Extensions.Hosting with the ASP.NET Core and HTTP instrumentation packages.

⚠ Common mistakes

  • Mistake: Adopting microservices with one or two teams "to be scalable". Why it is wrong: you pay the full operational and consistency tax without the organisational benefit. Instead: start with a modular monolith and extract services when a real need appears.
  • Mistake: Sharing one database between services. Why it is wrong: schema changes force coordinated releases, so services aren't independent. Instead: database per service; share data through APIs or events.
  • Mistake: Long chains of synchronous calls. Why it is wrong: latency and failure probability compound with every hop. Instead: use events, caching, parallel calls and timeouts with fallbacks.
  • Mistake: No timeouts or resilience on service calls. Why it is wrong: one slow dependency exhausts threads and connections and cascades. Instead: typed clients with AddStandardResilienceHandler, sensible timeouts and fallbacks for non-critical calls.
  • Mistake: Splitting by technical layer (a "data service", a "validation service"). Why it is wrong: every feature still touches every service. Instead: split by business capability.
  • Mistake: A shared library of domain types used by all services. Why it is wrong: it forces lock-step upgrades — a distributed monolith. Instead: share contracts via schemas and let each service own its own types.
  • Mistake: Skipping observability. Why it is wrong: without distributed tracing, cross-service incidents take hours to diagnose. Instead: OpenTelemetry tracing, correlation IDs and per-service dashboards from day one.

🏛 Senior insight: trade-offs

Microservices are an organisational architecture first: they let many teams ship without a release train. That's worth the tax only when the coordination cost of a shared codebase is higher than the cost of distributed systems. I look at evidence — deploy queues, merge conflicts across teams, parts with very different load — before recommending a split, and I insist on platform basics first.

Those basics are concrete. Edge and discovery: an API gateway (YARP or Azure API Management) for routing, auth offload and rate limits, and service discovery so services find each other by name. Security: every service validates tokens itself (zero trust inside the cluster), service-to-service calls use managed identities or mTLS, and each service gets least-privilege access to only its own database and queues — this lines up with ACSC Essential Eight expectations on restricting privileges. Observability: OpenTelemetry traces, metrics and logs exported to Application Insights / Azure Monitor, a correlation ID on every message, and per-service SLOs with alerts on burn rate. Without tracing, a cross-service incident that takes 10 minutes to diagnose in a monolith takes hours.

Option When it fits Cost When not to
Modular monolith 1–4 teams, evolving domain Boundary discipline Teams blocked on each other's releases
A few services around a monolith One part needs independent scale or cadence Some distributed complexity No such part exists
Full microservices Many teams, stable boundaries, mature platform High: ops, security per hop, consistency, tracing, contracts Small org, unclear boundaries

I'd measure success with DORA metrics per team (deploy frequency, lead time, change failure rate, time to restore) and cost per service, not with the number of services.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate suggests starting with a monolith. Why: Checks whether they know what makes a monolith modular enough to split later.
    How to answer

    A modular monolith is one deployable split into modules aligned to business capabilities — Orders, Billing, Catalogue — each with hard boundaries.

    • Each module owns its data: its own schema and DbContext, no cross-module joins or foreign keys.
    • Modules talk only through a public contract (an interface and DTOs) or integration events; everything else is internal.
    • Boundaries are enforced: separate projects, internal types, architecture tests, even per-schema database permissions.

    You get microservice-style boundaries with monolith-style operations: one pipeline, in-process calls, easy refactoring. The trade-off: one runtime, one release and one scaling unit, and it only works if the boundaries are enforced — otherwise it decays into a big ball of mud.

  2. When: Candidate mentions sagas or losing cross-service transactions. Why: Checks whether they can design a saga with compensations and timeouts.
    How to answer

    A saga replaces a distributed transaction with a sequence of local transactions, one per service, coordinated by messages. Each step has a compensating action that semantically undoes it: release the stock, refund the payment. Compensation isn't a rollback, because other parties may already have seen or acted on the intermediate state.

    • Choreography: services react to each other's events. It's simple for two or three steps, but the flow is implicit.
    • Orchestration: a state machine (such as a MassTransit saga) sends commands, persists its state per correlation id, and handles failures. The flow is explicit and observable.

    Design points: put the irreversible step last, make every step idempotent, add scheduled timeouts, and handle late replies (payment succeeds after a timeout cancelled the order, so refund it). The trade-off is availability and autonomy against eventual consistency and more complex failure handling.

  3. When: Candidate mentions cascading failures or timeouts between services. Why: Checks practical resilience design with timeouts, circuit breakers and bulkheads.
    How to answer

    Unrelated requests failing means the slow API exhausted a shared resource: usually database connections held while waiting, sockets, or thread-pool threads (from sync-over-async).

    Diagnose: Application Insights dependency durations, then dotnet-counters for the thread pool, SqlClient pool and HTTP connections, then dotnet-dump to see what requests are waiting on. Look for the 100 s HttpClient default timeout multiplied by retries.

    Mitigate: a feature flag that switches to a fallback (flat-rate shipping).

    Fix:

    • Timeouts: 2 s per attempt, 5 s total.
    • One jittered retry, outside a circuit breaker tuned to the traffic.
    • A bulkhead: a concurrency limit on the shipping client.
    • No external calls inside DB transactions.
    • Liveness checks that don't include the third party.

    The trade-off is a slightly degraded feature against a whole service going down.

🛠 Real-world problems: how you handle them

Distributed monolith: services that can only deploy together
Situation
A [freight booking] platform split into [9] services over [a year], owned by [2] teams, on AKS in Australia East. Releases were still monthly and coordinated.
Signals
Every release needed a [6-step] ordered deployment runbook; [4] services connected to the same SQL database; a shared `Freight.Common` NuGet package with domain types forced simultaneous upgrades; change failure rate [~30%].
Investigation
Built a dependency map from the Application Insights application map and connection strings; counted co-changes in git (services changed in the same PRs); reviewed DORA metrics per service; listed tables written by more than one service via Query Store.
Resolution
Short term: merged the four services sharing the database back into one deployable with modules. Long term: gave the remaining services their own data, replaced synchronous chains with Service Bus events, and replaced `Freight.Common` with published contract schemas.
Prevention
Architecture fitness functions: no shared connection strings, no shared domain packages; consumer-driven contract tests in each pipeline; an ADR with criteria for creating a new service; quarterly co-change review.

How to tell it (STAR)

**S:** At [company] we had [9] services but still released monthly with a [6-step] runbook. **T:** As [tech lead], I needed to get us to independent releases. **A:** I mapped co-changes and shared databases and showed that four services were really one. I wrote an ADR proposing we merge them into a modular service, give the rest their own data and move to events, ran a two-week spike to prove the contract-testing approach, and got buy-in from both teams. **R:** We went from [monthly] to [several deploys a day], and change failure rate dropped from [30%] to [8%].

↩ Usually asked after

More in Application Architectures

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me