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

๐Ÿ“š Interview question

Your team wants to redesign a growing system around events: every service publishes what happened and the others react. When do events actually simplify a system, and when do they just hide the complexity somewhere harder to see? Walk me through how you would decide, what you would make event-driven and what you would keep as direct calls, and how you keep an event-driven design understandable and debuggable.

Event-driven design trade-offs: decoupling and temporal independence vs hidden flows, eventual consistency, ordering, duplicates and schema evolution; notification vs state-carried events; choreography vs orchestration; and keeping it observable on Azure.

Senior Architecture Advanced azure-service-bus event-driven messaging observability saga system-design

๐ŸŽฏ Key points

  • Events simplify when producers shouldn't know consumers: fan-out to many independent reactions, a queue that buffers sudden surges so consumers work at their own pace, services that keep working when others are down
  • Events hide complexity when a business process becomes an invisible chain of handlers nobody owns end to end
  • Keep direct calls (or a query) when the caller needs the answer now, e.g. price or stock check during checkout
  • Event types: notification (thin, consumer calls back), event-carried state transfer (fat, consumer keeps a copy), domain vs integration events
  • Choreography: each service reacts to events with no central owner — simple and loosely coupled, but the flow is implicit. Orchestration: a saga or Durable Functions sends commands and holds state — visible, with timeouts and compensations, but one more component
  • Non-negotiables: transactional outbox, idempotent consumers, per-key ordering (Service Bus sessions), dead-letter handling, versioned schemas
  • Make flows visible and testable: W3C trace context through messages, an event catalogue (AsyncAPI), contract tests for event schemas, integration tests with a real broker or emulator
  • Azure mapping: Service Bus for business commands and events, Event Grid for reactive notifications, Event Hubs for high-volume streams

โฑ 30-second answer

Events simplify a system when the producer shouldn't know who reacts: an OrderPlaced that triggers email, loyalty, analytics and fulfilment, each owned by a different team, each able to be down without stopping checkout, and with spikes absorbed by a queue. They hide complexity when a business process becomes an invisible chain of handlers โ€” nobody can say where an order is, failures disappear into dead-letter queues, and changing the flow means editing five services. I keep direct calls when the caller needs the answer now, use choreography for independent reactions and orchestration (a saga or Durable Functions) for processes with steps and compensations. Non-negotiables: outbox, idempotent consumers, ordering per key, versioned schemas and trace context through messages. The trade-off: decoupling in time and ownership in exchange for eventual consistency and harder debugging.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"I'd start by separating two things events give you. One is temporal decoupling: the producer doesn't wait, so checkout keeps working when the loyalty service is down and a spike becomes a queue instead of an outage. The other is ownership decoupling: the producer doesn't know who reacts, so a new team can subscribe to OrderPlaced without changing the order service. When you need both, events are a big simplification. When you need neither โ€” the caller needs the answer now, or there's exactly one consumer that's really the next step of the same process โ€” events just add a broker, a delay and a debugging problem.

The trap is the long choreographed chain. For example, at [company] we [had an order flow where Order published, Payment reacted, then Stock, then Shipping, each listening for the previous event]. Nobody owned the whole process, so when [orders got stuck] support couldn't tell where, and a change to the flow meant touching four services. I [replaced the chain with an orchestrated saga in the order service that sends commands and tracks state, while keeping events for the genuinely independent reactions like email and analytics], [and stuck-order investigations went from hours to a query]. That's my rule: choreography for independent reactions, orchestration when there's a process with an order, timeouts and compensations.

The mistake I see is adopting events without the plumbing that makes them safe: no outbox so events get lost, consumers that aren't idempotent so duplicates double-charge, no ordering per entity, no schema versioning, and no trace context, so the application map shows nothing. On Azure I use Service Bus for business events and commands, Event Grid for reactive notifications like blob-created, and Event Hubs only for high-volume streams. Events are a great way to decouple teams and time, and a terrible way to hide a process nobody owns."


When events help and when they hurt

Signal Events help Events hurt
Consumers Many, independent, owned by other teams One, and it's the next step of the same process
Caller needs a result No (fire and forget) Yes, now (price, stock, auth)
Availability Producer must keep working when consumers fail Process is useless unless every step succeeds now
Load Spiky; consumers can catch up Steady, low, latency-sensitive
Process visibility Reactions are independent Business needs to know where each instance is
Team maturity Outbox, idempotency, tracing in place None of that exists yet

Kinds of events

Kind Payload Consumer behaviour Risk
Notification Id + type (OrderPlaced { orderId }) Calls back for details Callback load, coupling at read time
Event-carried state transfer Full state needed Keeps a local copy Schema coupling, large messages, PII spread
Domain event In-process, inside a bounded context Same transaction or right after Leaking internal models if published
Integration event Cross-service, versioned contract Async, at least once Versioning discipline

Azure mapping

Need Azure AWS note
Business events and commands, ordering, sessions, DLQ Service Bus (queues, topics) SQS / SNS, EventBridge
Reactive notifications from Azure resources or apps Event Grid EventBridge
High-volume telemetry / streams, replay Event Hubs (Kafka protocol) Kinesis, MSK
Orchestration Durable Functions, MassTransit / NServiceBus sagas Step Functions

Production example

Moving five independent post-order reactions to a Service Bus topic cut checkout p95 from [1.4 s] to [380 ms] and kept checkout available through [two] loyalty outages. Replacing the choreographed paymentโ€“stockโ€“shipping chain with an orchestrated saga reduced stuck orders found by customers from [~25] a week to [2], because the saga's timeouts raised them first.

๐Ÿ” What the interviewer is checking

Checks whether the candidate can judge where events help and where they hide complexity, and whether they know the mechanisms that make event-driven systems reliable and debuggable.

Green flags

  • Distinguishes temporal and ownership decoupling from request/response needs
  • Chooses choreography vs orchestration with reasons
  • Names outbox, idempotency, ordering, DLQ, schema versioning and trace propagation
  • Picks the right Azure service (Service Bus vs Event Grid vs Event Hubs)

Red flags

  • "Events decouple everything" with no downsides
  • Assumes exactly-once delivery
  • No answer for how to find a stuck process instance

๐Ÿ“š Learn in depth

1. Two forms of coupling

Synchronous:   checkout --HTTP--> loyalty          (checkout fails if loyalty is down)
Event-driven:  checkout --OrderPlaced--> [topic] --> loyalty (catches up later)
                                              \--> email
                                               \-> analytics

Events remove temporal coupling (both up at the same time) and knowledge coupling (producer knows consumers). They keep schema coupling: every consumer depends on the event contract, which is now a public API.

2. Choreography vs orchestration

Choreography:  Order -> (OrderPlaced) -> Payment -> (PaymentTaken) -> Stock -> (StockAllocated) -> Shipping
               no one knows the whole flow; state is spread across services

Orchestration: OrderSaga --PayCommand--> Payment
               OrderSaga <--PaymentTaken--
               OrderSaga --AllocateCommand--> Stock   (state + timeouts in one place)

Rule of thumb: if you need to answer "where is order 123 and why is it stuck?", you want an orchestrator with persisted state.

3. The plumbing that makes events safe

Problem Mechanism
Event lost when the process crashes after commit Transactional outbox, relay to the broker
Duplicate delivery (at-least-once) Idempotent consumer: processed-message table keyed by message id, or natural idempotency
Out-of-order processing Partition / session by entity id (Service Bus SessionId), version numbers
Poison messages Max delivery count โ†’ dead-letter queue, alerting, a replay tool
Schema change Additive changes only, version in the type name (OrderPlaced.v2), tolerant readers
Invisible flows W3C traceparent in message properties, OpenTelemetry instrumentation of the Service Bus SDK, AsyncAPI catalogue

4. Hidden complexity checklist

Ask of any event-driven design:

  1. Who owns the end-to-end business process?
  2. What happens if a consumer is down for six hours? For a week?
  3. How do you replay or repair after a bug in a consumer?
  4. How does a support person find the state of one instance?
  5. What PII is copied into events and to how many stores? (Privacy Act APP 11 applies to every copy.)

5. Event sourcing is a different thing

Event-driven communication between services is not event sourcing (storing an entity's state as its events). You can have either without the other; combining them by default doubles the learning curve.

6. Try it yourself

  1. Draw a current synchronous flow you know and mark each call: does the caller need the answer now? Which ones could be events?
  2. Build a Service Bus topic with two subscriptions in a test namespace, publish from an outbox, and kill one consumer for 10 minutes; watch it catch up.
  3. Send the same message twice and make the consumer idempotent with a processed-messages table and a unique index.
  4. Enable OpenTelemetry tracing for Azure.Messaging.ServiceBus and check the Application Insights application map shows producer โ†’ consumer.
  5. Write an AsyncAPI document for two events and generate documentation from it.

๐Ÿ’ป Code

An idempotent Service Bus consumer that keeps trace context, so an event-driven flow stays safe and visible.

namespace Loyalty.Consumers;

using Azure.Messaging.ServiceBus;
using Microsoft.EntityFrameworkCore;

public sealed record OrderPlaced(Guid OrderId, Guid CustomerId, decimal Total, int Version);

public sealed class ProcessedMessage
{
    public required string MessageId { get; init; } // unique index: a duplicate insert fails
    public DateTimeOffset ProcessedAt { get; init; } = DateTimeOffset.UtcNow;
}

public sealed class OrderPlacedConsumer(ServiceBusClient client, IServiceScopeFactory scopes,
                                        ILogger<OrderPlacedConsumer> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // Sessions keyed by CustomerId keep one customer's events in order.
        await using var processor = client.CreateSessionProcessor("orders", "loyalty",
            new ServiceBusSessionProcessorOptions { MaxConcurrentSessions = 16, AutoCompleteMessages = false });

        processor.ProcessMessageAsync += HandleAsync;
        processor.ProcessErrorAsync += e =>
        {
            // Called for any exception thrown by HandleAsync, and for connection errors.
            logger.LogError(e.Exception, "Service Bus error on {Entity} ({Source})", e.EntityPath, e.ErrorSource);
            return Task.CompletedTask;
        };

        await processor.StartProcessingAsync(stoppingToken);
        try { await Task.Delay(Timeout.Infinite, stoppingToken); }
        catch (OperationCanceledException) { }
        await processor.StopProcessingAsync(CancellationToken.None);
    }

    private async Task HandleAsync(ProcessSessionMessageEventArgs args)
    {
        // The SDK propagates W3C trace context through Diagnostic-Id, so this span links to the producer.
        var evt = args.Message.Body.ToObjectFromJson<OrderPlaced>()!;

        await using var scope = scopes.CreateAsyncScope();
        var db = scope.ServiceProvider.GetRequiredService<LoyaltyDbContext>();
        await using var tx = await db.Database.BeginTransactionAsync(args.CancellationToken);

        db.Processed.Add(new ProcessedMessage { MessageId = args.Message.MessageId });
        db.Points.Add(new PointsEntry(evt.CustomerId, evt.OrderId, (int)evt.Total));

        try
        {
            await db.SaveChangesAsync(args.CancellationToken); // effect + dedup record commit together
            await tx.CommitAsync(args.CancellationToken);
        }
        catch (DbUpdateException) when (await IsDuplicateAsync(args.Message.MessageId, args.CancellationToken))
        {
            // Already processed (duplicate delivery): safe to complete.
            logger.LogInformation("Duplicate {MessageId} ignored", args.Message.MessageId);
        }
        // Any other exception is not caught on purpose: the processor reports it to ProcessErrorAsync and
        // abandons the message, so it is retried and, after MaxDeliveryCount attempts, dead-lettered.
        // Nothing fails silently โ€” alert on dead-letter queue depth.

        await args.CompleteMessageAsync(args.Message, args.CancellationToken);
    }

    private async Task<bool> IsDuplicateAsync(string messageId, CancellationToken ct)
    {
        // Fresh scope: the failed DbContext still tracks the rejected entities.
        await using var scope = scopes.CreateAsyncScope();
        var db = scope.ServiceProvider.GetRequiredService<LoyaltyDbContext>();
        return await db.Processed.AsNoTracking().AnyAsync(p => p.MessageId == messageId, ct);
    }
}

โš  Common mistakes

  • Mistake: Making everything an event. Why it is wrong: When the caller needs the result now, an event adds latency, a broker and a correlation problem for no gain. Instead: Use direct calls or queries for request/response needs, events for independent reactions.
  • Mistake: Long choreographed chains for a business process. Why it is wrong: Nobody owns the flow, stuck instances are invisible and changes touch many services. Instead: Use an orchestrated saga (or Durable Functions) with persisted state and timeouts.
  • Mistake: Publishing without an outbox. Why it is wrong: A crash between commit and publish loses events silently. Instead: Write the event in the same transaction and relay it.
  • Mistake: Non-idempotent consumers. Why it is wrong: At-least-once delivery means duplicates; effects happen twice. Instead: Deduplicate by message id in the same transaction as the effect.
  • Mistake: Ignoring what users see while events are in flight. Why it is wrong: A user who just acted sees stale data and assumes it failed, then retries or calls support. Instead: Return a clear accepted / processing state, show their own change immediately, and notify on completion.
  • Mistake: Treating events as internal and changing them freely. Why it is wrong: An integration event is a public contract; breaking changes break consumers you don't know about. Instead: Version events, make additive changes, keep a catalogue (AsyncAPI) and contract tests.
  • Mistake: Testing handlers only with mocks. Why it is wrong: Ordering, duplicates, lock expiry and serialisation bugs appear only with a real broker. Instead: Add integration tests against the Service Bus emulator or a test namespace, including duplicate and out-of-order cases.
  • Mistake: Putting full customer records into every event. Why it is wrong: PII spreads to every consumer's store, widening breach scope under the Privacy Act. Instead: Carry only what consumers need; use ids and let them fetch sensitive data with authorisation.
  • Mistake: No tracing or lag metrics across the broker. Why it is wrong: The application map shows disconnected services, and growing queue age (a performance problem) goes unseen. Instead: Propagate W3C trace context, instrument the SDKs with OpenTelemetry, and alert on queue depth, message age and DLQ depth.

๐Ÿ› Senior insight: trade-offs

Events are an organisational tool as much as a technical one: they let teams evolve independently. The senior judgement is to use them where independence is valuable, and to keep a visible owner for every business process. Before going event-driven, check the team has the plumbing: outbox, idempotency, DLQ alerting, tracing and schema governance. Without them, events turn bugs into silent data drift.

Style When it fits Cost When not to
Direct call (HTTP/gRPC) Caller needs an answer now Temporal coupling, cascading failure Fan-out to many independent consumers
Choreographed events Independent reactions, many teams Hidden flows, harder debugging Multi-step process with compensations
Orchestrated saga Ordered process, timeouts, compensations Orchestrator to build and run Simple notifications
Event streaming (Event Hubs/Kafka) High volume, replay, analytics Ops, partition management Low-volume business workflows

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions domain events or integration events Why: Checks they know the difference and when each is dispatched
    How to answer

    A domain event records something meaningful that happened inside one bounded context, such as OrderPlaced. It is raised by an aggregate, handled in-process by other parts of the same model, and uses domain types freely. An integration event is a published contract for other services or modules: serialised, versioned and owned by the publisher.

    • Domain events are dispatched inside the unit of work (just before or as part of SaveChanges), so their side effects commit or roll back together.
    • Integration events must only leave after the commit. You write them to an outbox table in the same transaction, and a relay publishes them to Azure Service Bus.

    The trade-off: domain events give you strong consistency in one context; integration events give you decoupling at the cost of eventual consistency and at-least-once delivery.

  2. When: Candidate mentions an order flow across services Why: Checks they can apply events and sagas to a full order management design
    How to answer

    I model the order as an explicit state machine owned by the Order service, with Payment, Inventory, Fulfilment and Shipping each owning their own data. Services communicate with events and commands over Azure Service Bus, published through a transactional outbox so a state change and its event commit together. The multi-step flow is an orchestrated saga: the Order service sends commands, waits for replies, applies timeouts, and runs compensations (void the payment, release stock) when a step fails. Delivery is at-least-once, so every consumer is idempotent, and sessions keyed by OrderId keep one order's messages in order. Customer service reads a tracking projection built from the events. The trade-off: no distributed transactions means eventual consistency, so you design for stuck and out-of-order states explicitly.

  3. When: Candidate mentions storing events or replaying them Why: Checks they can tell event-driven communication apart from event sourcing
    How to answer

    Event sourcing stores every state change as an immutable event in an append-only stream per aggregate, and derives current state by replaying those events. The event log is the source of truth; tables you query are projections built from it. Appends use the expected stream version for optimistic concurrency. Snapshots speed up replay for long streams, and events are evolved by additive changes and upcasting, never by editing history.

    It's worth it when the history itself is valuable: audit, temporal queries ("what did we know on 1 July?"), complex behaviour. It's a poor fit for CRUD and for teams new to it, because you pay in eventual consistency, schema evolution and harder queries.

๐Ÿ›  Real-world problems: how you handle them

A choreographed order chain where nobody could find stuck orders
Situation
[Retail] platform with [6] services; payment, stock and shipping reacted to each other's events in a chain over [Azure Service Bus], [~20,000] orders a day.
Signals
[~25] customer complaints a week about orders stuck in 'processing'; growing dead-letter queues nobody watched; support escalations taking [hours] to trace.
Investigation
Traced a sample of stuck orders through logs in each service (no end-to-end trace existed); found messages dead-lettered after a schema change and a consumer that silently dropped out-of-order events; Application Insights application map showed services disconnected at the broker.
Resolution
Immediately replayed dead-lettered messages with a fixed consumer and added DLQ alerts. Then built an orchestrated order saga with persisted state and timeouts, kept events only for independent reactions, added the outbox and propagated trace context through messages.
Prevention
Saga timeout alerts, DLQ depth alerts, an AsyncAPI event catalogue reviewed in pull requests, contract tests for event schemas, and an ADR on choreography vs orchestration.

How to tell it (STAR)

**S:** Our order flow was a chain of services reacting to each other's events, and orders kept getting stuck where nobody could see them. **T:** I was asked to make the flow reliable and supportable. **A:** I traced stuck orders, found dead-lettered messages and out-of-order drops, replayed them and added alerts; then I moved the core process into an orchestrated saga with timeouts and kept events for independent reactions like email. **R:** Customer-found stuck orders went from [~25] a week to [2], and support could answer 'where is my order' with one query.

More in Senior Design Focus

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me