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.
Describe delivery semantics for messaging systems: at-most-once, at-least-once, and exactly-once. For each semantic, explain the practical impact on data loss and duplication, what guarantees the broker provides versus what the application must ensure, and give a realistic example where that semantic is appropriate (e.g., analytics ingestion vs financial transactions).
Sample Answer
Direct answer
At-most-once, at-least-once, and exactly-once describe how many times a message's effect is applied to a consumer's state when failures happen, and they trade off data loss against duplication: at-most-once can lose messages but never duplicates them, at-least-once never loses messages but can duplicate them, and exactly-once achieves neither loss nor duplication, at the cost of real coordination complexity between the broker and the application. The broker only ever guarantees delivery attempts and retries; whether duplicates or gaps actually matter is always decided by what the application does with what it receives.
Structured elaboration
| Semantic | Data loss | Duplication | What the broker guarantees | What the application must ensure |
|---|---|---|---|---|
| At-most-once | Possible | Not possible | A single delivery attempt, no automatic retry | Tolerate occasional missing messages; nothing to deduplicate |
| At-least-once | Not possible (assuming retries eventually succeed) | Possible | Persistence and retry until acknowledgment | Idempotency or deduplication (unique message identifiers, a dedup store, or naturally idempotent writes) |
| Exactly-once | Not possible | Not possible | Coordination primitives (transactional offsets/produce, or equivalent) that make the combination possible | Either rely on those broker-provided transactional guarantees end to end, or implement application-level idempotent writes tight enough to simulate the same outcome |
At-most-once in practice
- The broker or transport makes a single delivery attempt and does not retry on failure; if the consumer or the network drops the message, it is gone.
- Appropriate when losing an occasional message is cheaper than the cost of retry infrastructure and the risk of duplicates, for example high-volume sensor telemetry feeding a dashboard where one missing data point among thousands is invisible.
At-least-once in practice
- The broker persists the message and retries delivery until it receives an acknowledgment, which means a consumer crash between processing a message and acknowledging it results in redelivery of a message that was already (partially or fully) processed.
- The broker's job stops at "you will eventually get this message, possibly more than once." The application's job is to make processing that message twice harmless: a unique message identifier plus a dedup store, or a write that is naturally idempotent (an upsert keyed by a stable identifier, rather than an increment).
- Appropriate for analytics ingestion or audit logging, where losing a record is unacceptable but a duplicate can be cleaned up downstream (deduplicated at query time, or filtered by the same identifier used for idempotency).
Exactly-once in practice
- True end-to-end exactly-once requires coordination beyond a single retry-and-acknowledge loop: either the broker offers transactional semantics that atomically tie together "I read this" and "I wrote that" (so a crash mid-processing rolls back cleanly rather than leaving a partial, retryable state), or the application achieves the same outcome by combining at-least-once delivery with strict idempotent processing, which is functionally exactly-once from the business's point of view even though the transport itself only promised at-least-once.
- Appropriate for financial transfers or order processing, where a duplicate effect (charging a customer twice, decrementing inventory twice for one order) or a lost effect (an order accepted but never charged) both cause real monetary or legal problems, not just a dirty analytics row.
Worked example
A payments system processes a $250 transfer as a single message.
- Under at-most-once: if the consumer crashes after receiving the message but before applying the transfer, the $250 transfer is simply lost, no automatic retry recovers it, and the sender's balance is silently wrong by $250 unless a separate reconciliation process catches it.
- Under at-least-once with no application-side idempotency: the same crash-after-receive scenario causes the broker to redeliver the message; if the consumer blindly reapplies "subtract $250" a second time, the sender's balance is now wrong by $250 in the opposite direction (over-debited), a duplicate-effect bug, not a loss bug.
- Under at-least-once with application-side idempotency (a unique transfer identifier and an idempotent upsert: "set this transfer's status to applied if it is not already applied," not "subtract $250 unconditionally"): the redelivery is a no-op the second time, and the sender's balance is debited exactly once, $250, regardless of how many times the message is redelivered. This is the practical way most systems get exactly-once business outcomes without needing the broker to provide literal exactly-once transport.
Trade-offs and pitfalls
- Common wrong turn: choosing at-most-once for anything with real business consequence (payments, inventory decrements, order state) purely because it is the simplest and fastest option; the missing-message failure mode is invisible until an audit or a customer complaint surfaces it.
- Common wrong turn: assuming "the broker supports exactly-once" is a complete answer without checking what scope that guarantee actually covers (often just broker-internal processing, not the full path out to an external side effect like a payment gateway call, which the broker cannot make transactional on your behalf).
- Common wrong turn: implementing at-least-once with no deduplication strategy at all, treating "the broker retries" as sufficient without doing the application-side half of the job.
- Senior signal: naming which side, broker or application, is responsible for which half of the guarantee, and picking the example that matches the actual business cost of loss versus duplication rather than defaulting to whichever semantic sounds strongest.
Explain the difference between publish-subscribe and point-to-point (producer-consumer) messaging patterns. Provide concrete scenarios where pub/sub is a better fit (e.g., notifications, analytics) and where queues are preferable (e.g., work queues, task processing), particularly in multi-tenant SaaS and event-driven microservice architectures.
Sample Answer
Direct answer
Publish-subscribe (pub/sub) delivers each message to every interested subscriber, so it fits situations where multiple independent parties need to know the same fact happened, such as notifications or analytics. Point-to-point (producer-consumer, work-queue style) delivers each message to exactly one consumer among a pool, so it fits situations where a unit of work must be done exactly once by whichever worker picks it up, such as background task processing. The distinction is about fan-out (one-to-many awareness) versus load distribution (one-of-many execution), and both patterns are commonly implemented on the same underlying broker.
Structured elaboration
Publish-subscribe. A publisher emits an event to a topic; every subscriber with an active subscription receives its own copy. Subscribers are typically unaware of each other, can be added or removed without changing the publisher, and each one processes the event for its own purpose. This is the right model whenever "N different systems need to react to the same fact" is the actual requirement: a "UserSignedUp" event might be consumed by an email-welcome service, an analytics pipeline, and a fraud-scoring service simultaneously, with none of them competing for the message.
Point-to-point (work queues). A producer places a task on a queue; a pool of competing consumers pulls from the same queue, and each task is handled by exactly one consumer. This is the right model for "this unit of work needs to happen once, by whichever worker is free," such as resizing an uploaded image or sending a single transactional email: you do not want three workers all resizing the same image.
Where pub/sub is the better fit. Notifications is the clearest case: a single "OrderShipped" event needs to reach a push-notification service, an SMS service, and an in-app activity feed, each independently, and adding a fourth channel later should not require touching the producer. Analytics is the same shape: every business event (page view, purchase, signup) typically needs to reach an analytics pipeline in addition to whatever else consumes it, without competing with those other consumers for the message.
Where queues are preferable. Work queues and task processing are the clear case: a video-transcoding job, a report-generation job, or an outbound-email send should be picked up and completed by exactly one worker, with the queue's competing-consumers model providing natural load balancing and horizontal scaling (add more workers, they compete for the same backlog) without any risk of duplicate execution beyond what at-least-once delivery already requires the consumer to handle idempotently.
Multi-tenant SaaS (software as a service) and event-driven microservices. In a multi-tenant SaaS system, pub/sub is what lets independently-owned services (billing, usage-metering, audit logging) all react to the same tenant-level event, such as "SubscriptionUpgraded," without the team that owns the upgrade flow needing to know or coordinate with every downstream consumer; new consumers subscribe without any change to the publisher. Point-to-point queues, by contrast, are what those same microservices use internally for their own background work, such as a billing service's queue of pending invoice-generation tasks, where exactly-once-effective execution by one worker in the pool is the requirement, not fan-out to observers.
Worked example
A multi-tenant SaaS platform publishes a "TenantUpgraded" event when a customer moves from a free to a paid plan. Three independent subscribers exist on this topic: a billing service that starts metered invoicing, a feature-flag service that unlocks paid features, and a customer-success service that triggers an onboarding email sequence. All three receive their own copy of the same event; the team that owns the upgrade flow never had to know these three consumers existed. Separately, the feature-flag service's own onboarding-email trigger enqueues an actual "send welcome email" task onto a point-to-point work queue consumed by a pool of 5 worker processes; only one of those 5 workers ends up sending that specific email, because the queue hands each task to a single competing consumer, not to all 5.
Trade-offs and pitfalls
The common mistake is using a work queue where pub/sub was needed: if a "TenantUpgraded" task were placed on a single point-to-point queue instead of published to a topic, only one of billing, feature-flags, or customer-success would ever see it, and the other two would silently never fire, which is a subtle and easy-to-miss integration bug. The opposite mistake is using pub/sub where a work queue was needed for a task that must be done exactly once: if "resize this uploaded image" were published to a topic with multiple subscribed workers, every worker would independently resize the same image, wasting resources and, if the workers write to the same output path, potentially racing each other. A senior answer names this fan-out-versus-load-distribution distinction explicitly, rather than treating "pub/sub" and "queue" as interchangeable synonyms for "asynchronous messaging."
Explain the difference between message queues and event streams using: (1) simple high-level definitions, (2) step-by-step architecture differences (point-to-point vs publish-subscribe, retention and consumer offsets), (3) concrete use cases (task queue for background jobs vs event log for analytics), (4) discuss delivery semantics (at-least-once, at-most-once, exactly-once) and operational trade-offs.
Sample Answer
Direct answer
A message queue is a transient work-distribution mechanism: a message is delivered to one consumer and then typically removed. An event stream is a durable, ordered, append-only log that many consumers can read and re-read independently, each tracking their own position. Use a queue for background jobs that need to happen once; use an event stream when multiple consumers need to replay or independently process the same history of events, such as for analytics.
Structured elaboration
(1) Simple high-level definitions. A message queue holds discrete units of work; once a consumer successfully processes (and acknowledges) a message, it is generally gone from the queue. An event stream holds an ordered, append-only sequence of events that persists for a configured retention period regardless of whether any consumer has read them yet, and multiple independent consumers can read the same stream at their own pace.
(2) Step-by-step architecture differences.
- Delivery model: a queue is point-to-point: competing consumers pull from the same backlog, and each message goes to exactly one of them. An event stream is publish-subscribe at the storage layer: every consumer group gets its own full view of the log, so 5 independent consumer groups can each read every event, not compete for it.
- Retention: a queue typically discards a message once acknowledged (or after a short retention window for safety); an event stream retains events for a configured duration (hours to indefinitely) independent of consumption, which is what makes replay possible.
- Consumer offsets: a queue broker tracks per-message state (delivered, in-flight, acknowledged) on the broker's behalf; a consumer of an event stream tracks its own offset (a pointer into the log marking "I have processed up through here"), which the consumer can reset backward to reprocess history or forward to skip it, something a queue's consume-once model does not support.
(3) Concrete use cases. A task queue for background jobs (resize an uploaded image, send a single email, generate a PDF) is the queue use case: each job runs once, and once done there is no reason to revisit it. An event log for analytics (every purchase event, retained for 30+ days, read independently by a real-time dashboard consumer, a daily batch-aggregation consumer, and a fraud-detection consumer, each at their own offset) is the event-stream use case: the same history needs to serve multiple, independently-paced readers, and a new consumer added next month should be able to read events from before it existed.
(4) Delivery semantics and operational trade-offs. Both queues and streams commonly offer at-least-once delivery (a message may be delivered more than once, so consumers must be idempotent) as the practical default, since it is the easiest guarantee to build reliably. At-most-once (a message may be silently lost but never duplicated) is rarely chosen deliberately; it falls out of not retrying failed deliveries and is generally the wrong default for anything that matters. Exactly-once, from the consumer's experience, is achievable at the application layer by combining at-least-once delivery with a consumer-side idempotency check (a deduplication store keyed by message ID with a time-to-live, TTL), rather than relying on a broker guarantee alone; broker-level exactly-once semantics (EOS) protocols exist on some platforms but their internals are a streaming-platform implementation detail, not something the consuming application needs to reason about. Operationally, queues are simpler to run (bounded backlog, straightforward monitoring of queue depth) but lose replay ability; event streams give you replay and multiple independent consumer groups at the cost of needing retention-size planning, offset-lag monitoring per consumer group, and generally a heavier broker to operate.
Worked example
An e-commerce platform's "PurchaseCompleted" event needs to reach a real-time inventory-decrement consumer (must process within seconds), a nightly analytics-aggregation job (reads the whole day's events once, in batch), and a newly-added fraud-review consumer (needs to backfill and reprocess the last 7 days of purchases to retrain a rule set). This is only possible on an event stream: the inventory consumer reads from the current offset forward, the analytics job resets its offset to the start of each day, and the fraud-review consumer resets its offset back 7 days on rollout, all three reading the same retained log independently. If "PurchaseCompleted" had instead been placed on a point-to-point queue, only one of the three would ever have received a given event, and none of them could replay history that had already been consumed.
Trade-offs and pitfalls
The most common pitfall is reaching for an event stream by default because it seems more capable, then paying its operational cost (retention planning, per-consumer-group offset-lag monitoring, a heavier broker) for a workload that was really a simple once-only task queue. The opposite pitfall is placing something that needed independent replay, like the fraud-review backfill above, onto a queue and discovering months later that the history needed to replay it was already gone. A senior answer treats "does more than one independent party need to read this, possibly at different times or replaying history" as the deciding question, not "which technology is newer or more scalable."
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.
Define idempotency in the context of event-driven architectures. As a Solutions Architect, design a simple idempotency/deduplication strategy for an email-sending consumer that reads messages with payload {email_id, recipient, template}. Describe storage choices for dedup keys, TTL policies, memory vs disk trade-offs, and how to handle retries and long outage recovery.
Sample Answer
Direct answer
Idempotency in an event-driven system means processing the same message any number of times produces exactly the same effect as processing it once, which matters because message brokers commonly redeliver: a crash between processing and acknowledging, a network blip, or a producer retry can all cause the same logical message to arrive twice. For the email-sending consumer, that means checking a durable, atomic "have I already sent this email_id" record before every send, not trusting that the broker will only ever deliver a message once.
Structured elaboration
Dedup key
- Use
email_idas the deduplication key if oneemail_idalways corresponds to exactly one intended send; if a singleemail_idcould legitimately target multiple recipients, use(email_id, recipient)as a composite key instead. - Store a small record per key: status (in progress or sent) and when it was written.
Storage choices for dedup keys
- A fast in-memory store (a Redis-style key-value cache) for the hot path: low latency, high throughput, supports an atomic check-and-set operation needed to avoid a race between two consumer instances both trying to claim the same message.
- A durable, disk-backed store (a relational or key-value database) as the system of record: survives a full cache restart or a long outage, at higher latency than the in-memory tier.
- Hybrid: check the fast in-memory tier first; on a miss, fall back to the durable store before concluding the message is genuinely new, so a cache restart cannot cause a previously-sent email to be resent.
Time-to-live (TTL) policies
- The in-memory tier's entries expire after a TTL sized to the realistic redelivery window (long enough that any plausible retry or redelivery is still caught, short enough not to grow unbounded).
- The durable tier does not need a TTL for correctness (it is the long-term source of truth for "was this ever sent"), though it may have its own separate retention policy for storage cost or compliance reasons, independent of the dedup TTL.
Memory vs disk trade-offs
- Memory: fast, ideal for the common case (a redelivery arriving within seconds to minutes of the original), but limited capacity and lost on a restart unless backed by persistence.
- Disk: slower per lookup, but durable and cheap to retain for long windows, which is exactly what is needed for the "long outage recovery" requirement below.
- The two-tier design exists specifically to get the low latency of memory for the common case without losing correctness when memory alone is not enough.
Handling retries and long outage recovery
- Use an atomic check-and-set (an operation like Redis's
SETNX, or an equivalent conditional write) to claim a key before sending, so two concurrent consumer instances processing a redelivered pair of the same message cannot both decide they are the one to send it. - After a long outage (the in-memory cache is empty on restart, or entries aged out past their TTL during the outage), a redelivered message must not be trusted as new just because the fast cache has no record of it; falling back to the durable store catches exactly this case.
Worked example
The following script implements the two-tier dedup store (an in-memory "hot" tier with a TTL, backed by a durable tier with no TTL) and an idempotent consume function for the email-sending consumer, and was executed exactly as shown. A logical tick counter stands in for wall-clock time so TTL expiry is deterministic and reproducible, rather than asserting any real elapsed-time claim.
"""
Pinned, deterministic demo of a consumer-side dedup store for an email-sending
consumer, A logical tick counter
stands in for wall-clock time so TTL expiry is reproducible (no sleep()).
Run with: python3 idempotent_email_consumer.py
"""
from dataclasses import dataclass
from typing import Dict, Optional
@dataclass
class DedupRecord:
status: str # "in_progress" | "sent"
written_at_tick: int
class DedupStore:
"""Emulates a Redis-style store with SETNX (atomic check-and-set) and a
TTL measured in logical ticks, backed by a durable table for anything
that survives past the TTL window (the 'long outage recovery' path)."""
def __init__(self, ttl_ticks: int):
self.ttl_ticks = ttl_ticks
self._hot: Dict[str, DedupRecord] = {} # Redis-like cache
self._durable: Dict[str, DedupRecord] = {} # DB-backed, no TTL
def _expire_if_needed(self, key: str, now_tick: int):
rec = self._hot.get(key)
if rec and now_tick - rec.written_at_tick > self.ttl_ticks:
del self._hot[key]
def try_claim(self, key: str, now_tick: int) -> bool:
"""Atomic check-and-set: returns True if this call claimed the key
(i.e., no prior attempt is in flight or completed), False if a
duplicate delivery should be skipped."""
self._expire_if_needed(key, now_tick)
if key in self._hot:
return False # in_progress or sent, already claimed
if key in self._durable:
# survived a hot-cache eviction or full outage; still dedup
self._hot[key] = self._durable[key]
return False
self._hot[key] = DedupRecord(status="in_progress", written_at_tick=now_tick)
return True
def mark_sent(self, key: str, now_tick: int):
rec = DedupRecord(status="sent", written_at_tick=now_tick)
self._hot[key] = rec
self._durable[key] = rec # durable write-through, no TTL
def status(self, key: str) -> Optional[str]:
if key in self._hot:
return self._hot[key].status
if key in self._durable:
return self._durable[key].status
return None
class FakeEmailProvider:
def __init__(self):
self.sent_log = []
def send(self, email_id: str, recipient: str, template: str):
self.sent_log.append((email_id, recipient, template))
def consume(store: DedupStore, provider: FakeEmailProvider, message: dict, now_tick: int):
key = message["email_id"]
claimed = store.try_claim(key, now_tick)
if not claimed:
return "skipped_duplicate"
provider.send(message["email_id"], message["recipient"], message["template"])
store.mark_sent(key, now_tick)
return "sent"
if __name__ == "__main__":
TTL = 5 # ticks
store = DedupStore(ttl_ticks=TTL)
provider = FakeEmailProvider()
msg = {"email_id": "welcome-e100", "recipient": "a@example.com", "template": "welcome_v2"}
print("=== First delivery ===")
r1 = consume(store, provider, msg, now_tick=0)
print(f"result={r1}, provider.sent_log={provider.sent_log}")
assert r1 == "sent"
assert provider.sent_log == [("welcome-e100", "a@example.com", "welcome_v2")]
print("\n=== At-least-once redelivery of the SAME message, 1 tick later (well within TTL) ===")
r2 = consume(store, provider, msg, now_tick=1)
print(f"result={r2}, provider.sent_log={provider.sent_log}")
assert r2 == "skipped_duplicate"
assert len(provider.sent_log) == 1, "must not send twice"
print("\n=== Two consumers race on the SAME message at the SAME tick (concurrent redelivery) ===")
store2 = DedupStore(ttl_ticks=TTL)
provider2 = FakeEmailProvider()
claim_a = store2.try_claim("race-1", now_tick=0)
claim_b = store2.try_claim("race-1", now_tick=0)
print(f"consumer A claimed={claim_a}, consumer B claimed={claim_b}")
assert claim_a is True and claim_b is False, "only one consumer may claim the key"
print("\n=== Hot cache entry expires after TTL, but durable store still dedups (outage-recovery path) ===")
# Simulate a long outage: the in-memory/Redis-style cache is empty on
# restart (process restarted, or the key aged out past its TTL), but the
# durable table still has the record from before the outage.
after_outage_tick = 0 + TTL + 1 # past the TTL window
store._expire_if_needed("welcome-e100", after_outage_tick)
print(f"hot cache has key? {'welcome-e100' in store._hot}")
assert "welcome-e100" not in store._hot, "TTL should have evicted the hot entry"
r3 = consume(store, provider, msg, now_tick=after_outage_tick)
print(f"redelivery after TTL expiry + simulated outage -> result={r3}, provider.sent_log={provider.sent_log}")
assert r3 == "skipped_duplicate", "durable store must still catch the duplicate"
assert len(provider.sent_log) == 1, "still must not have sent twice"
print("\n=== A genuinely NEW message with a different email_id sends normally ===")
msg2 = {"email_id": "welcome-e101", "recipient": "b@example.com", "template": "welcome_v2"}
r4 = consume(store, provider, msg2, now_tick=after_outage_tick)
print(f"result={r4}, provider.sent_log={provider.sent_log}")
assert r4 == "sent"
assert len(provider.sent_log) == 2
print("\nALL ASSERTIONS PASSED")
Actual output from running python3 idempotent_email_consumer.py:
=== First delivery ===
result=sent, provider.sent_log=[('welcome-e100', 'a@example.com', 'welcome_v2')]
=== At-least-once redelivery of the SAME message, 1 tick later (well within TTL) ===
result=skipped_duplicate, provider.sent_log=[('welcome-e100', 'a@example.com', 'welcome_v2')]
=== Two consumers race on the SAME message at the SAME tick (concurrent redelivery) ===
consumer A claimed=True, consumer B claimed=False
=== Hot cache entry expires after TTL, but durable store still dedups (outage-recovery path) ===
hot cache has key? False
redelivery after TTL expiry + simulated outage -> result=skipped_duplicate, provider.sent_log=[('welcome-e100', 'a@example.com', 'welcome_v2')]
=== A genuinely NEW message with a different email_id sends normally ===
result=sent, provider.sent_log=[('welcome-e100', 'a@example.com', 'welcome_v2'), ('welcome-e101', 'b@example.com', 'welcome_v2')]
ALL ASSERTIONS PASSED
Walking the scenarios: the first delivery of welcome-e100 sends normally. A redelivery of the identical message one tick later (well within the 5-tick TTL) is skipped, and the send log still shows only one entry, proving no duplicate email went out. Two consumer instances racing on the same key at the same tick show only one successfully claims it (consumer A claimed=True, consumer B claimed=False), which is what the atomic check-and-set is for. After simulating the hot cache's TTL expiring (past tick 5) to represent a long outage, a redelivery of welcome-e100 is still correctly skipped, because the durable tier (no TTL) still has the record even though the fast tier does not, exactly the outage-recovery path the design requires. A genuinely new message (welcome-e101) sends normally and independently, confirming the dedup logic does not over-match on unrelated messages.
Trade-offs and pitfalls
- Common wrong turn: relying on the in-memory cache alone with no durable backing. It is fast for the common case, but a cache restart or an outage that outlasts the TTL causes exactly the duplicate-send failure idempotency was supposed to prevent.
- Common wrong turn: using a non-atomic "check, then set" (two separate operations) instead of a single atomic check-and-set. Between the check and the set, a second consumer instance can slip through and both end up believing they are the one to send.
- Common wrong turn: generating a fresh key on every delivery attempt (for example, from the broker's own delivery identifier) instead of using the message's own stable
email_id. A key tied to delivery mechanics changes on redelivery and stops deduplicating the thing that actually matters. - Senior signal: treating the TTL'd fast tier and the untimed durable tier as two different concerns (latency versus correctness-across-outages) rather than a single cache with an arbitrary expiry. The same two-tier idempotent-consumer pattern applies unchanged to other at-least-once consumers with a different natural key, for example a payment-notification consumer keyed by
payment_idinstead ofemail_id.
Unlock Full Question Bank
Get access to all 25 Event-Driven Architecture and Asynchronous Messaging interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.