Event-Driven Architecture and Asynchronous Messaging Questions
Designing systems around events and message passing: publish/subscribe, message queues, event streaming, choreography versus orchestration, and decoupling producers from consumers. Covers delivery semantics (at-least-once, at-most-once), ordering, backpressure, dead-letter handling, and the operational tradeoffs of asynchronous flows. Includes async processing patterns for offloading slow work.
Outline a migration strategy from RabbitMQ to Kafka for a complex microservices ecosystem that depends on message ordering, per-tenant isolation, and transactional semantics. Include compatibility layers, dual-writing or bridging approaches, testing strategy, cutover plan, rollback strategy, and operational runbooks for both systems during the migration.
Sample Answer
Direct answer
Migrating RabbitMQ to Kafka while preserving ordering, per-tenant isolation, and transactional semantics means treating the two brokers' delivery models as genuinely different, not just the same thing from a different vendor. Bridge the two with a service that mirrors traffic and preserves per-tenant ordering into Kafka's partitioning model, cut consumers over in a tested, reversible sequence, and keep runbooks for both systems live until the migration is fully complete, not just for Kafka.
Structured elaboration
flowchart LR
PROD[Producers] --> BRIDGE[Bridging Service]
BRIDGE -->|mirror| RMQ[(RabbitMQ: legacy)]
BRIDGE -->|mirror, preserve key order| KAFKA[(Kafka: target, partitioned by tenant+order key)]
RMQ --> LEGACYCONS[Legacy Consumers]
KAFKA --> MIGRATEDCONS[Migrated Consumers]
KAFKA --> PARITY[Parity Checker]
PARITY -->|drift detected| ALERT2[Rollback to RabbitMQ-only]
Why this is not a drop-in swap. RabbitMQ's model is queues with routing (exchanges, routing keys, per-queue ordering). Kafka's model is partitioned, replayable logs, ordering is per-partition, not global, and consumers track their own offset rather than the broker tracking per-consumer delivery state. "Preserve ordering" and "preserve per-tenant isolation" both become a partitioning-key decision in Kafka: map RabbitMQ's per-tenant queue, or routing key, to a Kafka partition key of tenant id, or tenant id plus a business ordering key like order id if ordering needs to be finer than per-tenant, so messages for a given tenant land on the same partition and are consumed in the order they were produced, mirroring the guarantee the RabbitMQ queue gave for free.
Compatibility layers and bridging. A bridging service consumes from RabbitMQ and republishes into Kafka (or, as a dual-write approach, has producers dual-write to both brokers directly, if producers can be changed first), translating routing-key-based addressing into partition-key addressing, and preserving message metadata, correlation ids, tenant id, that downstream consumers depend on. This bridge is itself infrastructure that needs its own ordering guarantee end to end: if it reads from RabbitMQ multithreaded without care, it can reorder messages before they ever reach Kafka, undermining the whole point of the migration.
Transactional semantics. If producers currently rely on RabbitMQ publisher confirms, plus in some designs a local outbox pattern, for effectively-exactly-once publishing, the Kafka side needs an equivalent: an outbox table plus a Kafka producer configured for idempotent, in-order writes to the target partition, so "did this transactional write actually get published" has the same answer under the new broker as it did under the old one. This is a conceptual carry-over of the guarantee the application needs, not a claim about Kafka's own broker-internals transaction protocol, which is out of scope here.
Testing strategy. Contract tests against both message shapes (what a RabbitMQ consumer expected versus what the same logical consumer, now reading from Kafka, receives through the compatibility layer); an ordering-verification test that publishes a known sequence per tenant and asserts the same sequence is observed on read; and a per-tenant isolation test that confirms one tenant's traffic never lands on another tenant's partition, even under partition-count changes.
Cutover plan. Mirror traffic through the bridge first, RabbitMQ remains the system of record, Kafka is a shadow target, to validate under real load, then migrate consumers tenant cohort by tenant cohort, smallest, lowest-risk tenants first, to read from Kafka instead of RabbitMQ, with each cohort's ordering and isolation tests re-run against production traffic before being called done.
Rollback strategy. While any cohort's producers still dual-publish to RabbitMQ, rolling that cohort's consumers back to RabbitMQ is a configuration change. The rollback window closes only once dual-publishing stops for that cohort, so dual-publish stays active until the cohort is fully validated, not stopped early for convenience.
Operational runbooks for both systems. During the migration, on-call needs a runbook for RabbitMQ issues (queue depth, consumer lag, a stuck queue from a slow consumer) and a separate runbook for Kafka issues (consumer lag per partition, under-replicated partitions, a stuck bridge), because both systems are live simultaneously for the length of the migration. An on-call engineer with only the new system's runbook is unprepared for half the incidents that can happen during the transition window.
Worked example
Trace tenant ordering through the bridge. Tenant acme-42 publishes order events E1, E2, E3 in that order to RabbitMQ. The bridge reads them off RabbitMQ's per-tenant queue, which guarantees first-in-first-out (FIFO) order for that queue, and publishes each to Kafka using partition key acme-42. Because all three share a partition key, Kafka routes them to the same partition, and a Kafka consumer reading that partition sees them in the same E1, E2, E3 order they were produced in. The ordering guarantee is preserved by the deliberate partition-key mapping decision, not by anything automatic about switching brokers.
Trade-offs and pitfalls
- Assuming RabbitMQ's per-queue FIFO ordering carries over to Kafka automatically, without a deliberate partition-key decision, is the single most common mistake in this exact migration. Ordering has to be re-derived, not assumed.
- A multithreaded bridge that does not preserve read-then-publish order per tenant can silently reorder messages for exactly the tenants the migration promised to protect.
- Running only Kafka's runbook during the transition, because it is the new system, leaves on-call blind to RabbitMQ-side incidents that are just as real until the old system is fully decommissioned.
- Declaring the migration done once traffic is flowing through Kafka, without keeping dual-publish active through a full validated bake period per cohort, removes the rollback safety net before it is actually earned.
Design graceful degradation strategies for an event-driven notification subsystem when downstream push services (APNs/FCM/email API) are rate-limited or unavailable. Include queueing, prioritization, circuit breakers, fallbacks, retry policies, and how to communicate delays to users and product teams.
Sample Answer
Direct answer
When downstream push providers, the Apple Push Notification service (APNs), Firebase Cloud Messaging (FCM), or an email API, are rate-limited or down, the notification subsystem should queue rather than drop, prioritize what gets sent first, trip a circuit breaker so a struggling provider is not hammered by continued retries, fall back to an alternate channel where one exists, and communicate the delay honestly to both the end user and the team that will get paged about it.
Structured elaboration
| Provider signal | Mechanism | Behavior |
|---|---|---|
| Rate-limited (429 or a backoff header) | Retry with capped exponential backoff and jitter | Requeue with a delay; do not hammer a provider that is telling you to slow down. |
| Sustained failures (a run of consecutive failures) | Circuit breaker opens | Stop sending to that provider for a cooldown window; redirect new sends to queue-and-wait or a fallback channel. |
| Provider fully unavailable | Queue with priority lanes | Critical notifications (security alerts, payment failures) are preserved and retried first once the provider recovers; low-priority notifications (marketing) are shed or deferred longest. |
| Breaker cooldown elapsed (half-open) | Canary a small fraction of traffic | Confirm real recovery before resuming full volume; avoids re-tripping immediately. |
Queueing and prioritization. Tier notifications at publish time (critical/transactional versus informational/marketing), and give the critical tier its own queue or a priority field so degradation sheds the low-priority tier first when the backlog needs to be bounded, the same principle as general backpressure design, tuned here to notification-specific business tiers rather than message size or type.
Circuit breakers. Track failure rate per downstream provider independently, APNs failing does not mean FCM is failing, open the breaker on a sustained failure rate over a short window, and use a half-open state that only lets a small canary volume through before fully reopening the gate. This avoids an immediate re-trip the instant a provider blips back to life.
Fallbacks. Define a real fallback path, not just "retry harder." If push fails and the notification matters, fall back to email (or SMS for the most critical class); if the fallback channel is also degraded, the message stays queued for the original channel with a bounded retry window rather than looping forever.
Retry policy. Capped exponential backoff with jitter, so retries spread out over time instead of synchronizing into a new burst against a provider that is already struggling, and a maximum retry count or time window after which the message moves to a dead-letter queue for manual or delayed reprocessing.
Communicating delays. To end users, this typically means an honest, generic in-app state ("notifications may be delayed") rather than silence, especially for anything the user is actively waiting on. To the product team, it means a dashboard and an alert channel showing current breaker state, queue depth by priority tier, and the estimated time to drain the backlog, so a rate-limit incident is visible as a known, bounded event rather than something someone has to reconstruct from logs afterward.
Worked example
backoff schedule (s):1,2,4,8,16,30capWith a circuit breaker configured to open after 5 consecutive failures within a 60-second window, and a 60-second cooldown before moving to half-open: a sustained APNs outage produces at most 5 failed attempts against the provider, roughly 1+2+4+8+16 = 31 seconds of retry spacing, before the breaker opens and sending stops. From that point, the queue simply holds critical-tier messages for retry once the breaker's half-open canary confirms recovery, rather than continuing to retry against a provider that has already signaled it is down.
Trade-offs and pitfalls
- Retrying without backoff or a circuit breaker turns a provider rate-limit into a self-inflicted denial-of-service against your own outbound traffic, and can get an account or IP range throttled or blocked further.
- Treating all notifications as equally important during degradation means low-value marketing pushes consume the same retry budget as a security alert. Tiering has to exist before the incident, not be improvised during it.
- A fallback channel with no cap of its own can silently overload email, or SMS, which usually carries a real per-message cost, the moment push degrades. Size and rate-limit the fallback too.
- Silence to the user reads as though the notification never happened. Even a generic delay indicator is better than nothing, but overpromising a specific recovery timeline the system cannot guarantee just moves the trust problem downstream.
Compare synchronous REST and asynchronous messaging for inter-service communication. For each approach explain: failure semantics, coupling, observability, latency, consistency guarantees, and operational complexity. Provide examples of when you'd prefer one over the other.
Sample Answer
Direct answer
Synchronous REST and asynchronous messaging differ on every axis that matters for inter-service communication: failure semantics, coupling, observability, latency, consistency guarantees, and operational complexity. REST gives an immediate, explicit success/failure answer at the cost of temporal coupling; asynchronous messaging decouples caller and callee at the cost of an implicit, eventually-resolved answer. Prefer REST when the caller needs a definitive result to proceed; prefer messaging when the interaction can tolerate delay and the two sides should be able to fail, scale, and deploy independently.
Structured elaboration
Take each axis for both approaches directly:
| Axis | Synchronous REST | Asynchronous messaging |
|---|---|---|
| Failure semantics | Caller gets an explicit HTTP status (2xx/4xx/5xx) or a timeout; failure is immediate and attributable to one call. | Failure is implicit and delayed: a message can fail after N retries and land in a dead-letter queue (DLQ), discovered later by whoever monitors the DLQ, not by the original producer. |
| Coupling | Temporal coupling (both services must be up simultaneously) plus contract coupling to the exact response shape and latency. | Only schema coupling to the message contract; producer and consumer need not be online at the same time, and consumers can be added without producer changes. |
| Observability | A single request/response pair is easy to trace with standard distributed tracing (a request ID follows one call stack). | Requires correlating a message across an asynchronous boundary (a shared correlation ID propagated through message headers) and tracking consumer lag, queue depth, and DLQ growth as first-class signals, since "is this working" is no longer visible in a single trace. |
| Latency | Bounded by the caller's timeout; the caller experiences the callee's latency directly, and a slow callee makes the caller slow. | The producer's latency is just "message accepted by the broker," typically single-digit milliseconds; end-to-end processing latency is decoupled from the producer and instead depends on consumer throughput and backlog. |
| Consistency guarantees | Strong consistency is achievable at the call boundary: the caller knows the callee's result before proceeding. | Eventual consistency: the caller only knows the message was durably accepted, not that the consumer has processed it; there is a window, bounded by consumer lag, during which downstream state has not caught up. |
| Operational complexity | Lower: no broker to run, fewer moving parts, well-understood tooling (load balancers, HTTP status codes, standard retries). | Higher: a broker (or managed equivalent) to operate or pay for, plus delivery-semantics decisions (at-least-once handling), consumer-side idempotency, ordering/partition-key design, and DLQ/retry policy to build and monitor. |
Worked example
A ride-hailing platform's "request ride" endpoint needs to synchronously call a pricing service, because the rider must see a confirmed price before confirming the ride; if pricing is slow or down, the request should fail fast rather than silently succeed with an unknown price, so REST with a tight timeout (e.g., 500ms) and a clear 503 on failure is the right fit here: failure semantics are explicit, and the caller cannot proceed without the answer. In contrast, once the ride completes, updating the driver's lifetime earnings dashboard and running fraud-pattern analysis on the trip do not gate anything the rider or driver is waiting on; publishing a "ride.completed" event lets those two consumers process independently, at their own pace, and a backlog in the fraud-analysis consumer (say, several minutes of lag during a traffic spike) has zero effect on ride completion, which is exactly the isolation asynchronous messaging is bought for.
Trade-offs and pitfalls
The common wrong turn is treating this as an architecture-wide choice ("we are a REST shop" or "we are event-driven") rather than a per-interaction decision on these six axes; most real systems need both, often for different steps of the same business flow. A subtler pitfall is picking asynchronous messaging for its scalability story while underestimating the observability tax: without correlation IDs threaded through message headers and consumer-lag/DLQ-depth dashboards from day one, an asynchronous flow that silently stalls is far harder to detect than a synchronous call that returns an explicit error, because nothing "fails" in a way that pages anyone; the failure just accumulates quietly as growing lag until a downstream SLA (service-level agreement) is missed.
You must choose between Apache Kafka and RabbitMQ as the backbone for an internal eventing platform. Constraints: peak 50k events/sec, need durable replay for analytics, many consumers require at-least-once delivery, and some consumers require ordered delivery per key. List evaluation criteria, recommend one option with justification, and describe mitigations for its weaknesses.
Sample Answer
Direct answer
For an internal eventing platform at 50,000 events/sec with durable replay for analytics, at-least-once delivery for many consumers, and per-key ordering for some consumers, Kafka is the better fit: its partitioned, replayable log natively supports per-key ordering (all events for a given key land on the same partition) and long retention, which RabbitMQ does not provide as first-class capabilities. RabbitMQ remains the better choice when the workload is closer to task distribution with complex routing needs and no replay requirement, which this workload is not.
Structured elaboration
Evaluation criteria, applied to the four stated constraints:
- Sustained throughput at 50k events/sec: both platforms can reach this rate, but the design work to get there differs. Kafka scales throughput by increasing partition count (more parallelism), which is a capacity-planning exercise done up front. RabbitMQ scales by adding queues and consumers, and can also sustain very high throughput, but does not offer partition-based ordered parallelism as a native primitive.
- Durable replay for analytics: this is the decisive criterion. Kafka retains events for a configured window regardless of consumption and lets any consumer group replay from an arbitrary offset. RabbitMQ removes messages once acknowledged; replaying "already-processed" history is not a built-in capability and would require bolting on a separate durable store.
- At-least-once delivery for many consumers: both support at-least-once delivery natively. Kafka's consumer-group model lets many independent consumer groups each read the full stream at-least-once without competing with each other; RabbitMQ supports at-least-once via manual acknowledgment, but achieving "many independent full-stream readers" specifically (rather than competing consumers on one queue) requires fanning the exchange out to a separate queue per consumer group, which is more configuration to maintain as consumers are added.
- Ordered delivery per key for some consumers: Kafka provides this natively via partition-key hashing, exactly the "some consumers require ordered delivery per key" requirement. RabbitMQ can approximate per-key ordering with a single active consumer per queue and a routing key per entity, but that limits parallelism for that queue to one consumer, which is a real constraint at 50k events/sec.
Recommendation: Kafka, specifically because the combination of durable replay and per-key ordering are both native to its architecture, whereas RabbitMQ would need workarounds for both.
Mitigations for Kafka's weaknesses. Kafka's two well-known weak points relative to RabbitMQ are operational complexity (a broker cluster, plus metadata quorum management, to run and monitor) and the lack of complex, content-based routing that RabbitMQ's exchange types provide natively. Mitigate the operational-complexity weakness by using a managed offering (e.g., Amazon MSK or Confluent Cloud) rather than self-hosting the cluster. Mitigate the routing-flexibility weakness by keeping routing logic in the consuming application (a consumer subscribes to specific topics and filters or re-publishes as needed) rather than expecting the broker to route by message content, which is a reasonable trade given this workload's requirements are about ordering and replay, not complex routing.
Worked example
Sizing partitions for 50,000 events/sec with per-key ordering: assume, as a planning input for this example (not a general Kafka benchmark), that a single partition on the chosen broker instance size can sustainably sustain roughly 5,000 events/sec for this message payload size. The minimum partition count is:
Npartitions≥⌈5,000 events/s per partition50,000 events/s⌉=10
Ten partitions is the bare minimum to sustain the target throughput with zero headroom; in practice you would provision with headroom for growth and for uneven key distribution (a small number of very active keys, or "hot keys," can overload their assigned partition even when the average across all partitions is fine), so a reasonable starting point is roughly double the bare minimum, i.e. 20-24 partitions, revisited once real key-distribution data from production traffic is available. This calculation is illustrative: the 5,000 events/sec per-partition figure is a stated planning assumption for this example, to be replaced with a measured number from a load test against your actual message size and hardware before committing to a partition count in production.
Trade-offs and pitfalls
The main pitfall is under-provisioning partitions based only on average throughput and ignoring hot-key skew; a partition count that comfortably covers the 50k events/sec average can still fall over if one key (e.g., one very active customer or entity) accounts for a disproportionate share of traffic, since that key's events are all pinned to a single partition by design. A second pitfall is choosing partition count too high without a plan to ever reduce it: Kafka does not support shrinking partition count on an existing topic without breaking the per-key-to-partition mapping (and therefore ordering) for every key, so partition sizing decisions are effectively one-directional and should be made deliberately, not just rounded up generously. A third pitfall specific to this scenario is assuming "at-least-once for many consumers" and "ordered per key for some consumers" are the same requirement: ordering is a per-partition property that some consumers need to respect (by not parallelizing within a key), while at-least-once is a delivery guarantee every consumer needs to handle via idempotency regardless of whether it cares about ordering.
From an SRE perspective, evaluate managed message brokers (e.g., hosted Kafka) versus serverless event buses (e.g., cloud pub/sub) for high-throughput service-to-service communication. Discuss operational costs, operational complexity, SLA guarantees, scaling, latency, and tooling for monitoring and recovery.
Sample Answer
Direct answer
From an operations standpoint, a managed message broker (e.g., a hosted Kafka offering such as Amazon MSK or Confluent Cloud) gives more control over throughput tuning, retention, and ordering at the cost of more operational surface to monitor and higher baseline cost, while a serverless event bus (e.g., a cloud pub/sub service such as Google Cloud Pub/Sub or AWS EventBridge) gives near-zero operational burden and pay-per-use cost at the cost of less fine-grained control over partitioning, latency tuning, and self-service recovery tooling. For high-throughput service-to-service communication where the team wants to own tuning and recovery, favor managed Kafka; where the team wants to minimize what they operate at all, favor a serverless event bus.
Structured elaboration
Assess both against the six named axes:
- Operational costs. Managed Kafka carries a standing cost for provisioned broker capacity (you pay for the cluster whether or not it is fully utilized) plus storage for retained data; this is predictable but not elastic. A serverless event bus is priced per message/operation with no idle cost, which is cheaper at low or spiky volume but can become more expensive than a well-utilized Kafka cluster at sustained very high throughput, since you are paying a per-unit rate indefinitely rather than amortizing fixed capacity.
- Operational complexity. Managed Kafka removes broker patching and hardware management but the team still owns partition planning, consumer-group management, and topic configuration; there is real domain knowledge required to run it well even when "managed." A serverless event bus removes essentially all of that: no partitions to plan, no cluster sizing, subscribe and publish are the entire interface.
- SLA guarantees. Managed Kafka offerings typically publish an availability SLA (service-level agreement) for the cluster/control-plane but leave throughput and latency characteristics as something the team must validate for their own workload and partition layout. Serverless event buses typically publish both an availability SLA and, in some cases, delivery-latency expectations, since the vendor controls the entire execution path end to end.
- Scaling. Managed Kafka scales by adding partitions and/or brokers, an action the team plans and executes (even if the underlying hardware provisioning is automated by the vendor). A serverless event bus scales transparently with no action from the team, which is the more attractive property for unpredictable or bursty traffic, but also means the team has less insight into and less control over how the vendor is scaling underneath them.
- Latency. A well-tuned Kafka cluster with a warm consumer typically offers lower and more predictable latency than a general-purpose serverless event bus, because the team controls partition count, replication factor, and consumer configuration directly. A serverless event bus's latency is generally good but is a shared, vendor-controlled characteristic the team cannot tune, and can vary more under the vendor's own multi-tenant load.
- Tooling for monitoring and recovery. Managed Kafka exposes rich native metrics (consumer lag per partition, in-sync-replica count, under-replicated partitions) that a site reliability engineer (SRE) can build detailed alerting and runbooks around, plus the ability to manually reset consumer offsets to recover from a bad deploy. A serverless event bus exposes a narrower, vendor-defined metric set (delivery counts, dead-letter queue depth) and generally offers fewer manual recovery levers, since the vendor controls the internals; recovery is often "retry via dead-letter redrive" rather than a fine-grained offset reset.
Worked example
A platform doing 200,000 events/sec of internal service-to-service traffic, where three specific consumer services each need to independently tune their own consumer-group parallelism and one of them needs strict per-key ordering for correctness, is a strong case for managed Kafka: the team needs partition-level control (to guarantee per-key ordering) and per-consumer-group tuning that a serverless event bus does not expose as directly. In contrast, a platform with bursty, unpredictable traffic (ranging from near-zero overnight to spikes during business hours) and a small team with no dedicated messaging-platform owner is a stronger case for a serverless event bus: near-zero idle cost during quiet hours, no capacity planning required for the spikes, and no partition-tuning expertise needed on the team.
Trade-offs and pitfalls
The pitfall in choosing a serverless event bus for a workload that genuinely needs strict per-key ordering or fine-grained consumer-group tuning is discovering, after the fact, that the vendor's abstraction does not expose the control needed, at which point migrating to a partition-aware broker is a much larger project than choosing correctly up front. The pitfall in choosing managed Kafka for a small team with bursty, low-average traffic is paying for standing cluster capacity that sits mostly idle, and taking on partition-planning and consumer-group operational knowledge the team does not otherwise need. A senior answer separates "who wants to own the tuning and recovery levers" from "who wants to own as little operational surface as possible" as the actual deciding question, since both are legitimate priorities depending on team size and workload shape.
Unlock Full Question Bank
Get access to all 38 Event-Driven Architecture and Asynchronous Messaging interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.