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.
Design a cost-efficient architecture for processing batch large-media file uploads using event-driven workflows in the cloud. Consider storage tiering, triggering via object storage events, compute scaling (serverless vs spot instances), streaming transforms vs copying, and minimizing egress and cold-start costs.
Sample Answer
Direct answer
Cost-efficient batch large-media processing trims cost on four independent levers: keep data in the cheapest storage tier it needs to be in, trigger compute directly off object-storage events instead of a separate polling layer, choose compute (serverless versus spot instances) based on the job's tolerance for interruption, and process media as a stream rather than a full local copy wherever the transform allows it. Each lever also happens to reduce egress or cold-start overhead as a side effect.
Structured elaboration
Storage tiering. Land the raw upload in a standard, hot tier only as long as it needs fast access, during and shortly after initial processing, then transition it to a cooler, cheaper tier via a lifecycle policy once it has been processed and access frequency drops. Most object stores support this as a built-in rule rather than something you have to build yourself.
Triggering via object storage events. Wire the object store's native "object created" event to invoke the processing pipeline directly, an event notification to a queue or a serverless function trigger, rather than running a separate poller that lists the bucket on an interval. This removes an idle compute component entirely and reacts immediately instead of on the poller's schedule, which also means not paying for a component that spends most of its time finding nothing new.
Compute scaling, serverless versus spot instances. Serverless (pay-per-invocation, no idle capacity) fits short, bursty, unpredictable-arrival jobs where the alternative is paying for idle worker capacity between infrequent uploads, and it fits workloads that tolerate the platform's execution-time and memory limits. Spot or preemptible instances fit longer-running, batchable jobs (large video transcodes) where the job can checkpoint and resume, or where the batch is broken into small enough units that losing one unit to preemption is cheap to redo. Spot capacity trades a real risk of interruption for a substantial cost reduction versus on-demand pricing, and that trade only pays off if the workload is actually resilient to being interrupted.
Priority across competing jobs. Where multiple jobs compete for capacity, a rush-priority transcode alongside routine batch jobs, a priority queue or priority field lets urgent jobs preempt routine ones for the next available worker slot, the same tiering principle used for backpressure-driven shedding elsewhere in this space, applied here to scheduling order rather than to dropping messages.
Streaming transforms versus copying. Many media transforms (transcoding, thumbnailing) can read the source as a stream and write the transformed output as a stream, without ever materializing the full file on local disk. This avoids provisioning large local disk or memory for large files, reduces the time before the job can start producing output, and avoids one extra full read-then-write pass over the data that a naive design (copy to local, then process, then upload) tends to add without realizing it.
Minimizing egress. Run compute in the same region as the storage bucket, transfer within a region, or between compute and storage in the same provider, is typically far cheaper than cross-region or cross-provider transfer, and avoid unnecessary intermediate copies between storage locations that would each incur their own transfer cost. This is less about a specific figure and more about counting how many times the bytes cross a network or region boundary in the design, each crossing is a cost decision, not a free operation.
Minimizing cold-start costs. For serverless compute, keep the deployed function or container lean, the transform's actual dependencies, not a general-purpose image, so cold starts are cheap when they happen. If job latency genuinely matters, not just cost, a small warm pool of provisioned capacity for the base load, with serverless or spot absorbing burst above that, avoids paying for constant idle capacity while still avoiding a cold start on every single burst-driven invocation.
Worked example
A batch of large video files, several hundred files, each significantly larger than the images an interactive upload pipeline would handle, uploaded overnight for a scheduled early-morning transcoding run: land the files in standard storage, trigger transcoding jobs off each object's creation event, run the transcode on spot instances sized for the batch (accepting that a preempted instance's partial work is cheap to redo because each file is its own checkpointable unit), stream-read the source and stream-write the transcoded output directly to the target bucket in the same region as the source, and transition the raw source to a cold storage tier once the transcoded output is confirmed written and verified. Every choice in that trace is one of the levers above, not a separate idea.
Trade-offs and pitfalls
- Spot or preemptible compute for a job that cannot checkpoint, a single monolithic multi-hour transcode with no intermediate save points, turns a cost optimization into a reliability problem. Break the job into smaller resumable units first, or do not use spot for it.
- Aggressive storage-tier transitions on data that turns out to still be accessed frequently reintroduce cost as retrieval fees from the colder tier, which can exceed what tiering saved if access patterns were misjudged.
- Streaming transforms that require random access to the whole file, some codecs, some multi-pass transforms, cannot always avoid a local copy. Verify the specific transform actually supports streaming before designing around it.
- Chasing egress savings by co-locating compute and storage in one region can conflict with a separate requirement, data residency or disaster recovery, that wants replication elsewhere. Cost is one input to the region decision, not the only one.
A producer team wants to remove a field that several downstream consumer teams currently read from an event. Two consumer teams say removing it will break their service; a third says they don't use it. Walk through how you would let the producer team make this change (and future ones like it) without breaking consumers who depend on the old shape, and what you would need in place beforehand for that to be possible.
Sample Answer
Direct answer
Do not trust the third team's "we don't use it" self-report as the basis for removing the field: verify usage empirically (via consumer-driven contract tests or a lineage/usage audit against the registry) before touching anything, then make the change additive and reversible rather than destructive: deprecate the field with a stated window while the two dependent teams migrate to whatever replaces it, and only physically remove it after the registry and the audit both agree nobody depends on it. What has to be in place beforehand for this (and every future change like it) to be low-risk is a schema registry with enforced compatibility, consumer-driven contracts wired into the producer's continuous integration (CI) pipeline, and field-level usage visibility, not policy written down but unchecked by tooling.
Structured elaboration
Step 1: verify the claims, don't just count votes
- Two teams say removal breaks them; one says they don't use it. Before acting on any of these statements, check field-level usage against real traffic (a lineage/audit view keyed to the registry, or the third team's own consumer-driven contract, if one exists) rather than relying on memory or a quick grep of code that might miss dynamic field access. A team that "doesn't use" a field today may still have a downstream job or dashboard reading it that the team itself is not aware of.
- If no usage-tracking tooling exists yet, this is itself the finding: the producer team cannot safely make this change (or any future one) without it, and building that visibility becomes the first deliverable, not an afterthought.
Step 2: never remove directly, deprecate first
- Mark the field deprecated in the schema registry with a stated time-to-live (a concrete window, for example 60 to 90 days depending on how disruptive the change is), rather than removing it in the next release. Deprecation is reversible; removal is not.
- If the field is being replaced rather than dropped outright (a common case: a flatter
carrier_codestring replaced by a richercarrierobject), ship the replacement as an additive, backward-compatible field alongside the old one first, so the two dependent teams can migrate to the new field on their own schedule while the old one still works.
Step 3: give the two dependent teams a real migration path, not a deadline
- Communicate the deprecation and its window through the same channel every consumer team already watches (the registry's deprecation surface, not a one-off message that is easy to miss).
- Track each dependent team's migration status against the deprecation window on a shared dashboard, so "day 89 and two teams still on the old field" is visible before it becomes an incident, not discovered at the deadline.
- If a team cannot realistically migrate within the standard window, that is a scheduling negotiation with a visible tracked extension, not silent, indefinite delay and not a forced break either.
Step 4: remove only once verified safe
- Remove the field only after both signals agree: the deprecation window has closed, and the usage audit independently confirms zero real traffic reads it, including the third team's prior "we don't use it" claim, now verified rather than assumed.
What must be in place beforehand for this, and future changes like it, to be possible
- A schema registry that enforces compatibility on every change automatically, so an accidental breaking change cannot ship silently regardless of what any individual engineer intends.
- Consumer-driven contracts (or equivalent field-level usage tracking / lineage) wired into the producer's continuous integration (CI) pipeline, so "who actually depends on this field" is a query, not a Slack thread across three teams.
- A documented, tooled deprecation workflow (a way to mark a field deprecated with a TTL, and tooling that surfaces that to consumers and eventually blocks removal until the window and the usage audit both clear), so this becomes a repeatable, low-drama process rather than a one-off negotiation every time a producer wants to evolve its data.
- Without these three things in place, the producer team's only honest options for a genuinely breaking change are: negotiate with every consumer team by hand each time (slow, does not scale past a handful of consumers), or ship the breaking change and hope (which is what created this exact situation).
Worked example
Say the field in question is legacy_shipping_zone on a shipment-events topic with 8 consumer teams subscribed. Team A and team B say they read it (matches the scenario's "will break" teams); team C says they don't.
- A usage audit against 30 days of production traffic (using consumer group lag/read metrics keyed to which fields a consumer's deserializer actually accesses, or the registry's usage tracking if wired up) confirms: team A genuinely reads it in a nightly job, team B reads it in a real-time dashboard, and team C's claim holds, zero reads from team C's consumer group in the 30-day window.
- The field is marked deprecated with a 60-day TTL. A replacement
shipping_zone_v2field ships additively alongside it in the same event, so team A and team B can migrate independently: team A's nightly job is updated in week 2 (low urgency, batch job, easy to redeploy); team B's real-time dashboard, wired into a customer-facing screen, is updated in week 7 after more careful testing. - At day 60, the audit is re-run: both team A and team B now read
shipping_zone_v2exclusively; nobody readslegacy_shipping_zone. The field is removed. Team C, whose original claim was correct, was never blocked or delayed by any of this.
Trade-offs and pitfalls
- Common wrong turn: trusting a consumer team's self-reported "we don't use it" without verification. Self-reports are honest but incomplete; a dynamic field access, a downstream job the reporting team forgot about, or stale documentation can all make a well-intentioned "we don't use it" wrong.
- Common wrong turn: removing the field once the two dependent teams say they've migrated, without an independent audit confirming zero remaining traffic. "We think we're done migrating" and "the traffic confirms nobody reads the old field" are different claims, and only the second one is safe to act on.
- Common wrong turn: treating this as a one-time negotiation to get through, rather than as evidence that the team needs standing tooling (registry, contracts, usage visibility) so the next field removal does not require the same manual, three-team back-and-forth.
- Senior signal: naming the prerequisite tooling explicitly as the actual answer to "what would you need in place beforehand," rather than only describing the sequence of steps for this one field.
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.
Design an idempotent consumer for processing payment events from a message queue. Message format: {payment_id, user_id, amount, currency, timestamp}. Requirements: prevent double-charges on redelivery, support at-least-once delivery semantics from the broker, allow retries, and maintain low latency. Describe the deduplication store, choices between in-memory, Redis, or relational DB, TTL strategy, and cleanup considerations.
Sample Answer
Direct answer
Derive the deduplication (dedup) key from the payment's own business identity, payment_id, not from anything the broker generates, then make claiming that key and processing the payment a single atomic step: check-and-claim, process, mark done. Redelivery of the same message must always produce the same payment_id, so a redelivered message collapses onto the same key and gets skipped instead of charged again.
Structured elaboration
Why payment_id, not the other fields. The message is {payment_id, user_id, amount, currency, timestamp}. user_id alone is wrong (one user can legitimately make two separate payments). (user_id, amount, timestamp) is also wrong: two real, distinct charges can share the same amount, and timestamp is set by the producer, so a retried publish can carry a different timestamp for the same logical payment while a coincidentally identical tuple could describe two different real charges. payment_id is the one field that is supposed to be stable across every redelivery of the same logical event, which is exactly the property a dedup key needs.
The atomicity requirement. "At-least-once delivery from the broker" means the same message will arrive more than once, by design, not as an edge case. If the consumer does exists = store.get(payment_id) followed by a separate store.set(payment_id, ...), two redeliveries handled concurrently (two consumer threads, or two instances in the same consumer group during a rebalance) can both read "not found" before either writes, and both charge. The claim has to be a single atomic operation: "insert this key only if it does not already exist," succeed-or-fail in one round trip.
Store choice: in-memory vs. Redis vs. relational database.
| Store | Atomic claim primitive | Round-trip cost | Durability across restarts | Shared across consumer instances | Best fit here |
|---|---|---|---|---|---|
| In-memory (process-local dict or least-recently-used, LRU, cache) | Check-then-insert under a single process lock | Lowest | None, lost on restart | No | A fast pre-check layer in front of a durable store, never the sole source of truth |
| Redis | SET key value NX PX ttl_ms (atomic in one command) | Low, one round trip | Best-effort unless persistence is explicitly enabled | Yes | Primary dedup store when "maintain low latency" is a hard requirement |
| Relational database | INSERT ... ON CONFLICT DO NOTHING or a unique constraint on payment_id | Higher, a transactional write | Full, same guarantees as the ledger | Yes | When the claim and the actual charge write must commit as one atomic transaction |
For a payment consumer, Redis is usually the right default for the hot path because "maintain low latency" is an explicit requirement and the claim is a single command. The relational option earns its extra latency specifically when you want the dedup row and the ledger write to be atomically consistent with each other, for example inserting the dedup row in the same transaction as the row that records the charge, so a crash between "claim" and "charge" cannot leave the dedup store and the ledger disagreeing.
Probabilistic pre-filter. At high volume, a Bloom or cuckoo filter can sit in front of the authoritative store as a cheap "have I possibly seen this before" check: a negative result is certain (definitely new, skip the store lookup and go straight to processing), a positive result is only "maybe," and must still fall through to the authoritative store, because treating a false positive as certain would silently drop a legitimate first-time charge. A cuckoo filter additionally supports deletion, which matters if you want the filter itself to track a rolling window rather than growing forever. Either filter is an optimization that reduces load on the durable store for the (usually large) fraction of genuinely-new events; it never replaces the store as the source of truth.
TTL strategy. The dedup key's time-to-live (TTL) must be at least as long as the broker's own maximum redelivery window plus a safety margin. If the broker can, in the worst case, redeliver a message up to 12 hours after first delivery (for example, a long consumer outage followed by catch-up), a TTL shorter than that lets the key expire and a legitimate-looking "new" charge slip through on a very late, otherwise-normal redelivery. TTL should not be sized off how long you want to retain history; it should be sized off how long the broker can still legally hand you a duplicate.
Cleanup considerations. Redis expires keys natively via the TTL, no separate job needed. A relational dedup table has no native per-row expiry in most databases, so it needs an explicit periodic sweep (a scheduled DELETE WHERE created_at < now() - retention_window, i.e. a dedup-table-plus-TTL pattern implemented as a cron job rather than a database feature), or the table grows without bound and both storage cost and index lookup latency degrade over time.
flowchart TD
A[Payment event arrives] --> B{Dedup key exists in store?}
B -- Yes --> C[Skip: return prior result, no charge]
B -- No --> D[Atomically claim key: SETNX with TTL]
D --> E[Process payment]
E --> F[Mark key as done, keep TTL]
F --> G[Ack message to broker]
C --> G
Worked example
Assume 500 payment events per second sustained, and a 24 hour TTL matching the broker's stated maximum redelivery window.
live keys=rate×TTL=500×86,400=43,200,000At roughly 150 bytes per key plus value plus Redis's own per-key overhead:
bytes=43,200,000×150B≈6.48GBThat is a meaningful working set for a single Redis instance. It is exactly the kind of number that motivates either sharding the dedup store across a Redis cluster keyed by payment_id, shortening the TTL if the broker's actual redelivery window is smaller than assumed, or moving completed, already-settled payments' dedup records into the cheaper relational table once they age past the point where redelivery is still plausible.
Trade-offs and pitfalls
- Using a coarse or derived key (amount, timestamp, or a hash of the whole payload) instead of
payment_idis the single most common mistake: it either misses real duplicates (payload varies slightly across redeliveries, for example a re-serialized timestamp) or falsely merges two distinct legitimate charges. - A GET-then-SET pattern instead of a single atomic command reintroduces the exact race the dedup layer exists to prevent; this only shows up under real concurrent redelivery, so it can pass casual testing and still double-charge in production.
- Redis becoming unavailable forces an explicit choice: fail closed (stop processing new payments until Redis is back, safe but reduces availability) or fail open (keep processing without dedup protection, risks double-charges). Silently defaulting to one without deciding on purpose is itself the pitfall.
- Sizing the relational table's cleanup job off total historical volume instead of the broker's actual redelivery window wildly over-retains data and slows the unique-constraint index down for no correctness benefit.
What is a Dead Letter Queue (DLQ)? Describe a DLQ-based architecture for handling poison messages in a task processing system, including how you would instrument metrics and alerts, automate quarantining, and implement a manual review and replay workflow. Mention any retention and security considerations.
Sample Answer
Direct answer
A Dead Letter Queue (DLQ) is a separate queue or topic a consumer (or the broker on its behalf) diverts a message to once it has failed processing beyond an agreed limit, so one message that will never succeed, a poison message, cannot block or endlessly retry-loop every other message queued behind it. A DLQ architecture is not just that holding area, it is the metrics and alerting that make its arrivals visible, the automated classification that quarantines messages sensibly, and the manual review and replay workflow that actually resolves them.
Structured elaboration
Why a message ends up in the DLQ. Broadly three reasons: a permanent business-logic or validation failure (the payload is malformed or violates a business rule, retrying changes nothing), a transient failure that simply exhausted its retry budget (the downstream dependency was down long enough that every retry also failed), or a poison message that crashes or hangs the consumer process itself (for example, a payload that triggers a parsing exception on every attempt). Distinguishing these at arrival is what makes the rest of the workflow tractable, they need different handling.
Metrics and alerts. Track DLQ depth (how many messages are currently quarantined), the age of the oldest DLQ message (a slow leak looks fine on depth alone if replay keeps pace, age catches it), arrival rate into the DLQ, and a breakdown by failure reason. Alert on any new arrivals to a topic that is normally near-zero, and on depth or age crossing a threshold tied to how quickly the team can realistically review them (a service-level objective, or SLO, for DLQ review turnaround).
Automated quarantining. Classify each message at the moment it arrives in the DLQ, not later: capture the failure reason, the error type or exception, the attempt count, timestamps, and the originating topic or partition as metadata alongside the payload. Tag messages that look transient (timeouts, connection resets, a known downstream outage window) as candidates for automatic replay after a cool-down; tag messages that look permanent (schema validation failures, business-rule violations) for manual review instead of blind retry.
Manual review and replay workflow. A reviewer inspects the payload, the failure reason, and the attempt history, then decides to replay (re-inject to the main queue), archive (keep for record but do not reprocess), or fix-forward (patch the producer or consumer, then replay). Replayed messages must go back through the exact same idempotency and deduplication path any normal delivery would use, not a special-cased bypass, otherwise a message that partially succeeded before its original failure can be double-processed on replay.
Retention. DLQ messages typically need a longer retention window than the main topic, since a human needs time to notice and act, but not indefinite retention; tie it to compliance and data-retention requirements rather than leaving it as an afterthought default.
Security. A DLQ commonly holds the exact same sensitive payloads as the main data path (a payment event that failed validation is still a payment event), so it needs the same encryption-at-rest and access control as the primary pipeline. Treating the DLQ as a lower-security scratch space is a common and risky oversight, precisely the hardest-to-process messages are the ones most likely to sit there.
flowchart LR
P[Producer] --> Q[Main queue or topic]
Q --> C[Consumer]
C -->|success| Ack[Ack / commit offset]
C -->|failure, retries exhausted| DLQ[Dead-letter queue]
DLQ --> M[Metrics: DLQ depth, age]
M --> Alert[Alert on-call]
DLQ --> Review[Manual review / classification]
Review -->|fixable| Replay[Replay to main queue]
Review -->|not fixable| Archive[Archive / discard]
Worked example
A payment consumer starts failing on three messages because an upstream producer shipped a breaking field rename. Each message exhausts its retry budget and is diverted to the DLQ. The unusual arrival rate (normally zero, now three in a minute) trips an alert. Automated classification tags all three as schema-related, since the failure is a deserialization error rather than a downstream timeout, routing them to manual review instead of an automatic retry loop that would just fail the same way again. On-call fixes the producer (or adds a compatibility shim on the consumer side), confirms the fix against one message manually, then replays the remaining three, and access logs record who replayed them, satisfying the audit angle of the security requirement.
Trade-offs and pitfalls
- A DLQ with no automated classification or alerting quietly becomes a graveyard nobody looks at, the single most common real-world failure of this pattern, not a hypothetical.
- Replaying a message without re-running it through idempotency checks is the most common way a "fixed" DLQ incident turns into a second incident, double-processing.
- Indefinite DLQ retention creates both a storage cost problem and, for sensitive payloads, a compliance liability; set retention deliberately.
- Treating every DLQ arrival identically (always retry, or always require manual review) wastes either engineering attention or retry budget; the transient-versus-permanent classification is what makes the workflow scale.
Unlock Full Question Bank
Get access to all 28 Event-Driven Architecture and Asynchronous Messaging interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.