Prev Next

Integration / Distributed Systems Exactly Once Processing: Myth vs Reality Interview questions

Last updated

1. What is exactly-once processing? 2. What are the three message delivery guarantees? 3. Define at-most-once delivery? 4. Define at-least-once delivery? 5. What is idempotency in distributed systems? 6. What is an idempotency key? 7. What is the Two Generals Problem? 8. What causes duplicate messages in a distributed system? 9. What is a deduplication store? 10. What is the transactional outbox pattern? 11. What is an idempotent producer in Kafka? 12. What is a consumer offset? 13. Define effectively-once processing? 14. What is a dead letter queue? 15. What is an acknowledgement in messaging? 16. Why is exactly-once delivery impossible in distributed systems? 17. What is the difference between exactly-once delivery and exactly-once processing? 18. Why is at-least-once with idempotent consumers the practical approach? 19. How do Kafka transactions work? 20. What does isolation.level=read_committed do? 21. How does Kafka Streams achieve exactly-once semantics? 22. Why does Kafka exactly-once not cover external side effects? 23. How do zombie producers get fenced in Kafka? 24. Explain the execution flow of a Kafka consume-transform-produce transaction? 25. How do you make a REST API idempotent? 26. Why are PUT and DELETE idempotent but POST is not? 27. What is the dual-write problem? 28. How does change data capture complement the outbox pattern? 29. How does the inbox pattern make consumers idempotent? 30. What happens when a consumer commits its offset before processing? 31. What happens when a consumer group rebalance occurs mid-processing? 32. How do you design an idempotent consumer using a unique constraint? 33. When should you use natural idempotency instead of a dedup table? 34. How long should you retain idempotency keys? 35. How do you handle concurrent requests carrying the same idempotency key? 36. How does SQS FIFO deduplication work? 37. Why can the SQS visibility timeout cause duplicate processing? 38. How does Flink achieve exactly-once state consistency? 39. What is a two-phase commit sink in Flink? 40. How does Spark Structured Streaming achieve exactly-once? 41. What is the difference between two-phase commit and idempotent retries? 42. How do saga compensations handle partial failures? 43. How do you store consumer offsets in the database for exactly-once? 44. How does message ordering affect duplicate handling? 45. Why does a deduplication window fail for late duplicates? 46. When would you choose Kafka transactions over idempotent consumers? 47. How do you test for duplicate processing? 48. How do you troubleshoot duplicate payments in production? 49. Which is better: a dedup table or Redis SETNX, and why? 50. Explain the end-to-end flow of an exactly-once payment pipeline?

1. What is exactly-once processing?

Exactly-once processing means that the effect of handling a message appears in your system one time, even if the message is delivered, retried or replayed more than once. The goal is a correct final state, not a network that never repeats itself.

In practice no real broker can promise to hand over a message exactly one time. What systems actually do is combine at-least-once delivery with idempotent or transactional handling, so a second copy is either ignored or produces the same result as the first.

A payment worker is a typical case: if the same charge-4411 event arrives twice, the customer must still be charged once and the ledger must show a single entry.

Take quiz
Exactly-once processing guarantees that:
the network never sends a message twice
the final effect of a message is applied once even if it is delivered several times
every message is processed by exactly two consumers
messages are processed once but may be lost on failure
A payment worker receives the same charge event twice. What does exactly-once processing require?
The customer is charged once and the ledger has one entry
The second event is delivered to a different worker
Both events are processed so the charge is applied twice for safety
The broker is restarted to clear the duplicate

2. What are the three message delivery guarantees?

Messaging systems offer three delivery semantics: at-most-once, at-least-once and exactly-once. They differ in what happens when a failure hits between sending, processing and acknowledging a message.

Guarantee Messages lost? Duplicates? Typical mechanism
At-most-once Possible Never Fire and forget, ack before processing
At-least-once Never Possible Retry until acked, ack after processing
Exactly-once Never No visible effect At-least-once + idempotency or transactions

The first two are properties of the transport. The third is usually a property of the whole pipeline, which is why it needs cooperation from producer, broker and consumer.

Take quiz
Which delivery guarantee can lose messages but never duplicates them?
At-least-once
Exactly-once
Retry-with-ack
At-most-once
Which delivery guarantee is typically built by retrying until an ack is received?
At-most-once
Fire-and-forget
At-least-once
Best-effort broadcast

3. Define at-most-once delivery?

At-most-once delivery means a message is sent one time and never retried. It arrives zero or one times, so duplicates are impossible but loss is accepted.

It happens when a producer does not wait for an ack, or when a consumer commits its offset before doing the work and then crashes. The message is marked done even though nothing was processed.

It fits data where a missed event is harmless, such as a periodic metrics sample or a heartbeat. It is a poor fit for orders or payments.

Take quiz
At-most-once delivery arises when a consumer:
commits the offset only after the database write succeeds
commits the offset before processing the message
retries the message until it gets an ack
stores each message in an outbox table first
Which workload is the best fit for at-most-once delivery?
A CPU-usage sample sent every few seconds
A bank transfer instruction
An order confirmation email trigger
A ledger posting

4. Define at-least-once delivery?

At-least-once delivery guarantees a message is never lost, but it may be delivered more than once. The sender keeps retrying until it gets an acknowledgement.

Duplicates appear when the work succeeded but the ack did not make it back: a timeout, a dropped connection, a consumer crash after processing and before the offset commit, or a rebalance.

This is the default for most brokers (Kafka consumers with manual commit after processing, SQS standard queues, RabbitMQ with manual acks). It is the safe base to build exactly-once effects on, because you can add deduplication on top, but you cannot recover a lost message.

Take quiz
A duplicate under at-least-once delivery is most commonly caused by:
the broker compressing the message twice
the producer using too many partitions
the message exceeding the retention period
the ack being lost after the work already succeeded
Why is at-least-once preferred as the base for exactly-once effects?
It never produces duplicate messages
It needs no acknowledgements
Duplicates can be filtered later, but lost messages cannot be recovered
It is faster than any other mode because there are no retries

5. What is idempotency in distributed systems?

An operation is idempotent if running it once or many times leaves the system in the same state. The result of the second call is the same as the first.

SET balance = 100 is idempotent. ADD 10 TO balance is not, because every repeat changes the answer. Idempotency is the main tool for turning at-least-once delivery into exactly-once effects.

Idempotent Not idempotent
UPDATE users SET status='ACTIVE' WHERE id=7 UPDATE accounts SET bal = bal + 10
HTTP PUT /users/7 HTTP POST /payments
Delete row with id=7 Append a row to a log table

Non-idempotent operations can be made safe by attaching a unique id and recording that it was already applied.

Take quiz
Which operation is naturally idempotent?
UPDATE orders SET total = total + 5 WHERE id = 42
INSERT INTO audit_log (msg) VALUES ('shipped')
UPDATE orders SET status = 'SHIPPED' WHERE id = 42
Increment a visit counter by one
What is the usual way to make a non-idempotent operation safe to retry?
Increase the timeout so retries never happen
Attach a unique id and record that it was already applied
Run it on a single thread
Convert it to a GET request

6. What is an idempotency key?

An idempotency key is a unique identifier, usually a UUID, that the client attaches to a request so the server can recognise a retry of the same logical operation.

The server stores the key together with the outcome of the first attempt. If the same key shows up again, it returns the stored result instead of running the operation a second time.

POST /v1/payments
Idempotency-Key: 7f3c9a52-1b0e-4c6a-9d1e-5a2b8c4f9e10
Content-Type: application/json

{"amount": 2500, "currency": "USD"}

The key must be generated once per intended action and reused on every retry. A new key for each retry defeats the purpose.

Take quiz
When should a client generate a new idempotency key?
For each new logical operation, but not for retries of the same one
On every HTTP retry attempt
Only once per user account for its entire lifetime
Never, the server should generate it
What does the server do when it sees an idempotency key it has already completed?
Runs the operation again and overwrites the result
Rejects the client with an authentication error
Deletes the key and waits for a new request
Returns the stored result of the first attempt

7. What is the Two Generals Problem?

The Two Generals Problem is a thought experiment showing that two parties cannot reach guaranteed agreement over an unreliable channel. Two armies must attack at the same time, and their only way to talk is a messenger who might be captured.

General A sends 'attack at dawn'. A cannot attack unless B confirms. B confirms, but B now cannot be sure the confirmation arrived, so B wants a confirmation of the confirmation, and so on forever.

No finite number of messages removes that last bit of doubt. This is the theoretical core of why a sender can never be 100% sure whether the receiver processed a message, which is exactly the uncertainty behind exactly-once delivery.

sequenceDiagram
  participant A as General A
  participant B as General B
  A->>B: Attack at dawn
  B->>A: Agreed
  Note over A,B: Did the last message arrive?
  A->>B: Got your agreement
  Note over A,B: Same doubt repeats forever
Take quiz
What does the Two Generals Problem demonstrate?
Two nodes can always agree using three messages
Messengers should be replaced by faster networks
Agreement over an unreliable channel cannot be guaranteed with finitely many messages
A majority of generals is enough to guarantee agreement
Why is the Two Generals Problem relevant to exactly-once delivery?
It proves that retries are never needed
A sender can never be certain whether its last message was received and acted on
It shows that acknowledgements remove all uncertainty
It states that brokers must use two partitions

8. What causes duplicate messages in a distributed system?

Duplicates are created by retries that are triggered by uncertainty. When a sender cannot tell whether a request succeeded, it sends it again to be safe.

The common sources are:

  1. Lost ack: the consumer finished the work, the ack was dropped, the broker redelivers.
  2. Timeouts: a slow but successful call looks like a failure to the client, which retries.
  3. Consumer rebalance: a partition moves to another consumer before the offset was committed.
  4. Visibility timeout expiry: in SQS the message becomes visible again while the first worker is still running.
  5. Producer retry: a broker write succeeded but the producer never saw the response.
  6. Human or batch replays: reprocessing a topic or re-sending a file.
Take quiz
A consumer crashes after updating the database but before committing its offset. What happens next?
The message is redelivered and processed again
The message is silently dropped
The database update is rolled back by the broker
The offset is committed automatically by the database
Which of these is a producer-side cause of duplicates?
The consumer commits offsets too late
A topic has too many partitions
The message is larger than the batch size
A write succeeded on the broker but the response was lost, so the producer retried

9. What is a deduplication store?

A deduplication store is a place where a consumer records the ids of messages it has already handled, so it can skip repeats. It can be a database table, a Redis set or a key-value store.

The check and the business write must be linked. If you record the id in one system and apply the change in another, a crash between the two leaves you either with a lost update or a duplicate.

The safest layout puts both in the same database transaction:

BEGIN;
INSERT INTO processed_messages (message_id) VALUES ('evt-9001');  -- fails on duplicate
UPDATE accounts SET balance = balance + 50 WHERE id = 12;
COMMIT;

Take quiz
Why should the dedup record and the business change be in one transaction?
It makes the table smaller
It lets Redis replace the database
A crash between them would otherwise cause a lost update or a duplicate
It avoids the need for message ids
In the SQL example, how is a duplicate detected?
The UPDATE returns zero rows
The insert into processed_messages violates the primary key
The COMMIT statement is skipped by the database
A trigger deletes older messages

10. What is the transactional outbox pattern?

The transactional outbox is a pattern where a service writes its business change and an 'event to publish' row into the same local database transaction. A separate relay later reads the outbox and sends the events to the broker.

This removes the gap between 'database committed' and 'message published', because either both rows are saved or neither is. The relay publishes with at-least-once semantics, so consumers still need to handle duplicates.

flowchart LR
  S[Service] -->|one transaction| DB[(Orders + Outbox tables)]
  R["Relay or CDC"] -->|poll or read log| DB
  R -->|publish| K["Message broker"]
  K --> C["Idempotent consumer"]
Take quiz
What does the transactional outbox write in a single local transaction?
Two rows in two different brokers
The business row and the event row to be published
Only the event, the business row is written later
The consumer offset and the producer id
After the outbox relay publishes an event, what must consumers still be prepared for?
Duplicate delivery of the same event
Missing business rows
A mandatory two-phase commit
Events arriving before they were written

11. What is an idempotent producer in Kafka?

An idempotent producer is a Kafka producer configured with enable.idempotence=true. It guarantees that retries by the producer will not write duplicate records into a partition.

The broker assigns the producer a producer id (PID), and the producer attaches an increasing sequence number to each batch per partition. The broker discards any batch whose sequence it has already stored.

It is on by default since Kafka 3.0 and needs acks=all. Its scope is limited: it covers one producer session and one partition. After a restart the producer gets a new PID, so duplicates across restarts are not caught unless you use transactions.

Take quiz
What does the broker use to detect a duplicate batch from an idempotent producer?
The message key hash
The consumer group id
The topic creation timestamp
Producer id plus per-partition sequence number
What is a limitation of the idempotent producer on its own?
It cannot retry failed sends
It only works with a single broker
It does not protect against duplicates across producer restarts
It requires acks=0

12. What is a consumer offset?

A consumer offset is the position of the next record a consumer group will read from a partition. Kafka stores committed offsets in the internal __consumer_offsets topic.

Where you commit the offset relative to your processing decides the delivery guarantee. Commit before processing and a crash loses the message (at-most-once). Commit after and a crash causes a re-read (at-least-once).

records = consumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String,String> r : records) {
    process(r);              // do the work first
}
consumer.commitSync();       // then commit: at-least-once

Take quiz
Committing the offset after processing gives:
at-most-once behaviour
at-least-once behaviour
guaranteed exactly-once delivery
no guarantee at all because offsets are ignored
Where does Kafka keep committed consumer offsets?
In the internal __consumer_offsets topic
In the producer's memory
In the message value of each record
In the ZooKeeper log of the consumer

13. Define effectively-once processing?

Effectively-once is another name for exactly-once effects. Messages may be delivered several times, but the visible outcome is as if each was handled once.

Many engineers prefer this term because it is honest about the mechanism: the system tolerates duplicates and neutralises them, rather than preventing them. The duplicate still travels over the wire and is still read by the consumer, it just has no second effect.

A consumer that skips an event after finding its id in a dedup table, or applies an upsert that rewrites the same row, is giving effectively-once behaviour.

Take quiz
Effectively-once processing means that:
duplicates can never arrive
each message is physically transmitted only once
messages are dropped if they look similar
duplicates may arrive but they produce no extra visible effect
Why do many engineers prefer the term 'effectively-once'?
It means the broker uses fewer partitions
It guarantees lower latency
It admits that duplicates are tolerated and neutralised, not prevented
It removes the need for idempotency

14. What is a dead letter queue?

A dead letter queue (DLQ) is a side queue where messages are moved after they fail processing a set number of times. It stops one bad message from being retried forever.

Without a DLQ, a poison message (malformed or triggering a bug) blocks a partition or loops endlessly, and each retry risks side effects. With a DLQ, the consumer gives up after, say, 5 attempts, parks the message and moves on.

Operators can inspect parked messages, fix the cause and replay them. Replays are another source of duplicates, so the consumer must still be idempotent.

Take quiz
Why is a dead letter queue used?
To speed up successful messages
To park messages that keep failing so they stop blocking or looping
To encrypt messages at rest
To increase the number of partitions
Replaying messages from a DLQ makes which property essential?
Idempotent consumers
A larger batch size
Disabling acknowledgements
Using at-most-once delivery

15. What is an acknowledgement in messaging?

An acknowledgement (ack) is a signal that tells the sender or broker that a message was received or processed. Its timing defines the delivery guarantee.

  • Producer ack: the broker confirms it stored the record. In Kafka, acks=0 means no wait, acks=1 leader only, acks=all all in-sync replicas.
  • Consumer ack: the consumer tells the broker the work is done, so it can be removed or the offset advanced.

Acking late, after the side effects are complete, gives at-least-once. Acking early gives at-most-once. No ack timing can give exactly-once alone, because the ack itself can be lost.

Take quiz
In Kafka, which setting makes the broker wait for all in-sync replicas before acknowledging a write?
acks=all
acks=0
acks=1
acks=leader-only-async
Why can't ack timing alone provide exactly-once?
Acks are always sent twice
Brokers do not support acks
Acks only work with idempotent keys
The ack message itself can be lost

16. Why is exactly-once delivery impossible in distributed systems?

Because a sender can never distinguish between 'the receiver did not get it' and 'the receiver got it but the ack was lost'. Both look identical from the sender's side: silence.

The sender then has only two honest choices. Retry, and risk a duplicate. Do not retry, and risk a loss. There is no third option that avoids both, which is the Two Generals Problem in practical form. Add the fact that nodes crash and networks partition at unpredictable moments, and the uncertainty cannot be engineered away.

What you can do is accept at-least-once delivery and make the receiver's work safe to repeat. That gives exactly-once effects, which is what applications actually care about.

sequenceDiagram
  participant S as Sender
  participant R as Receiver
  S->>R: message
  R->>R: process
  R--xS: ack lost
  Note over S: Silence, cannot tell if processed
  S->>R: retry same message
Take quiz
Why can a sender not tell a lost message from a lost ack?
Acks contain no information
Messages are always delivered in order
Both appear as silence from the receiver
The broker hides the difference on purpose
When the sender sees no ack, which choices does it really have?
Wait forever with zero risk
Retry and risk a duplicate, or give up and risk a loss
Guess the receiver state and always be right
Switch to UDP, which guarantees delivery

17. What is the difference between exactly-once delivery and exactly-once processing?

Exactly-once delivery would mean the transport hands a message to the consumer one time. It cannot be guaranteed. Exactly-once processing means the consumer's observable effect happens once, regardless of how many copies arrived.

Aspect Exactly-once delivery Exactly-once processing
Where it lives Network / broker Application + state store
Achievable? No, in the general case Yes, with idempotency or transactions
Duplicates on wire Claimed to be zero Allowed, but neutralised
Typical tool None reliable Dedup table, idempotent upsert, transactions

When a vendor advertises 'exactly-once', read it as processing within a defined boundary, for example 'inside Kafka topics', not as a guarantee about your database or email provider.

Take quiz
Which of the two is actually achievable in practice?
Exactly-once processing within a defined boundary
Exactly-once delivery over any network
Neither of them
Both without any application changes
When a vendor says 'exactly-once', what should you check first?
The colour of the dashboard
How many consumers you can add
Whether it uses UDP
What boundary the guarantee covers

18. Why is at-least-once with idempotent consumers the practical approach?

It splits the problem into two parts that can be solved. The transport guarantees nothing is lost, and the consumer guarantees repeats do no harm.

The alternatives are weaker. At-most-once drops data on any crash. Distributed transactions across broker and database (XA / two-phase commit) work in narrow cases but hurt availability and are not supported by most cloud services.

Idempotent consumers also survive things no broker feature covers: manual replays, bugs fixed by reprocessing a topic, upstream clients that resend, and switching brokers. The protection lives with the data, not with one piece of infrastructure.

Take quiz
Which problem does an idempotent consumer solve that a broker-only guarantee does not?
Disk space exhaustion
Slow network links
Manual replays and upstream client resends
Topic naming conflicts
Why is at-most-once a poor base for critical workflows?
It always produces duplicates
Any crash can silently drop messages
It requires two-phase commit
It cannot be used with databases

19. How do Kafka transactions work?

Kafka transactions let a producer write to multiple partitions and topics atomically, and optionally commit consumer offsets in the same unit. Either all records become visible or none do.

A producer sets a stable transactional.id. A broker-side transaction coordinator tracks the transaction state in the internal __transaction_state topic. On commit or abort, the coordinator writes control markers into every partition touched, and consumers using read_committed honour them.

producer.initTransactions();
producer.beginTransaction();
producer.send(new ProducerRecord<>("payments-out", key, value));
producer.sendOffsetsToTransaction(offsets, consumer.groupMetadata());
producer.commitTransaction();   // or abortTransaction()

The guarantee ends at Kafka. Anything the application does outside Kafka is not part of the transaction.

Take quiz
Which component tracks the state of a Kafka transaction?
The transaction coordinator
The consumer group leader
The schema registry
The partition follower
What marks a transaction as committed inside a partition?
A file rename on disk
A special consumer offset of -1
A change to the topic name
A control marker record

20. What does isolation.level=read_committed do?

It tells a Kafka consumer to read only committed transactional records and skip records from aborted or still-open transactions.

The consumer reads up to the Last Stable Offset (LSO), which sits just before the earliest open transaction in the partition. Records from aborted transactions are filtered out client-side using abort metadata from the broker.

Setting What the consumer sees
read_uncommitted (default) Every record, including aborted and open transactions
read_committed Only committed records, up to the LSO

Side effect: one long-running open transaction holds back the LSO, so consumers may see added latency. Without this setting, Kafka transactions give no benefit to downstream readers.

Take quiz
What is the default value of isolation.level for Kafka consumers?
read_committed
serializable
snapshot
read_uncommitted
Why can a long open transaction slow down read_committed consumers?
It locks the consumer's CPU
It deletes older partitions
It holds back the Last Stable Offset
It forces a rebalance every second

21. How does Kafka Streams achieve exactly-once semantics?

Kafka Streams turns on Kafka transactions for you with a single setting: processing.guarantee=exactly_once_v2. Each processing cycle becomes an atomic read-process-write unit.

Within one transaction the application does three things together: writes output records, writes changelog records for its state stores, and commits the input offsets. On a crash the whole transaction is aborted, the task restarts from the last committed offsets and the state store is restored from its changelog.

Properties props = new Properties();
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG,
          StreamsConfig.EXACTLY_ONCE_V2);

Version 2 uses one producer per stream thread instead of one per task, which cuts overhead. It needs brokers 2.5 or newer. Reads and writes to external systems are still outside the guarantee.

Take quiz
Which Kafka Streams setting enables exactly-once?
enable.exactly.once=true
processing.guarantee=exactly_once_v2
acks=exactly
isolation.level=streams
What is committed atomically in a Kafka Streams exactly-once cycle?
Output records, state changelog records and input offsets
Only the output records
Only the consumer group name
The JVM heap snapshot

22. Why does Kafka exactly-once not cover external side effects?

Kafka's transaction protocol only controls records inside Kafka. Sending an email, calling a payment API or writing to PostgreSQL happens outside the transaction coordinator, so Kafka cannot roll it back.

If a transaction aborts after your code already called an external API, the call stays done and the retry will call it again. The result is a duplicate effect even though the Kafka topics look perfectly clean.

To protect external calls, pass an idempotency key to the remote system, derived from something stable such as topic, partition and offset, or the business event id. Alternatively, write the intent into a Kafka topic or outbox and let a dedicated, idempotent sender perform the call.

Take quiz
A Kafka transaction aborts after your code sent an email. What happens to the email?
It is automatically recalled
Kafka holds it until the commit
It is deleted from the recipient mailbox
It stays sent and may be sent again on retry
How can you protect an external API call made by a Kafka consumer?
Increase the partition count
Set acks=0
Send an idempotency key derived from a stable event id
Use a random key per attempt

23. How do zombie producers get fenced in Kafka?

A zombie is an old producer instance that was presumed dead (a long GC pause, a network split) but wakes up after a new instance has taken over its work. If both write, you get duplicates.

Kafka fences the old one using the transactional.id and a producer epoch. When a new instance calls initTransactions() with the same id, the coordinator increments the epoch and aborts any open transaction from the previous epoch. Any later request from the old epoch is rejected with a ProducerFencedException.

  • Use the same transactional.id after a restart so the new instance replaces the old.
  • Use different ids for instances doing different work, or they will fence each other.
Take quiz
What does the coordinator do when a producer calls initTransactions() with an existing transactional.id?
Creates a second independent producer
Bumps the epoch and aborts the previous open transaction
Deletes the topic
Copies all data to a new partition
What exception does a fenced zombie producer receive?
ProducerFencedException
TopicExistsException
NetworkWarmupException
OffsetOutOfRangeException

24. Explain the execution flow of a Kafka consume-transform-produce transaction?

This is the core exactly-once loop for stream processing: read from an input topic, transform, write to an output topic, and commit the input offsets in the same transaction.

  1. The producer calls initTransactions() and registers its transactional.id with the coordinator.
  2. The consumer polls records from the input topic with read_committed.
  3. The producer calls beginTransaction() and sends the transformed records.
  4. It calls sendOffsetsToTransaction() so the consumed offsets join the transaction.
  5. commitTransaction() makes the coordinator write commit markers to the output partitions and the offsets topic.

If the app crashes before step 5 the transaction is aborted. After restart, the consumer resumes from the previously committed offset and redoes the work, but the aborted output is never visible.

sequenceDiagram
  participant C as Consumer
  participant P as Producer
  participant TC as Coordinator
  participant O as Output topic
  C->>P: batch of records
  P->>TC: begin transaction
  P->>O: send results
  P->>TC: add input offsets
  P->>TC: commit
  TC->>O: write commit marker
Take quiz
In a consume-transform-produce transaction, how are input offsets committed?
With a separate commitSync after the transaction
By the broker at midnight
They are not committed at all
Through sendOffsetsToTransaction, inside the same transaction
What happens to the output if the app crashes before commitTransaction()?
The output is published anyway
The output is published twice
The transaction is aborted and the output is never visible to read_committed consumers
The consumer offset moves forward

25. How do you make a REST API idempotent?

Start with the HTTP method: GET, PUT and DELETE are defined as idempotent, so design them that way. For POST (create a payment, place an order), add an Idempotency-Key header.

  1. The client generates a UUID once per intended action and sends it in the header.
  2. The server atomically inserts the key, along with a hash of the request body, into a table with a unique constraint.
  3. If the insert succeeds, process the request and store the status code and response body against the key.
  4. If the key already exists and is complete, return the stored response without re-executing.
  5. If the key exists but the body hash differs, return an error such as 422, since the client has misused the key.

Stripe documents this approach for its payments API, and it works the same for internal services.

Take quiz
What should the server do if an existing key arrives with a different request body?
Process it as a brand new request
Overwrite the original response
Reject it as a misuse of the key
Silently ignore both
Which HTTP method usually needs an Idempotency-Key header added?
GET
POST
PUT
DELETE

26. Why are PUT and DELETE idempotent but POST is not?

It comes from what each method means. PUT replaces a resource at a known URI with the supplied representation, so repeating it gives the same final state. DELETE removes a resource, and deleting something already gone leaves it gone.

POST asks the server to process the payload, usually to create a new subordinate resource at a server-chosen URI. Two identical POSTs normally create two resources.

Method Idempotent (RFC 9110) Why
PUT /users/7 Yes Replaces the same resource with the same data
DELETE /users/7 Yes Final state is 'does not exist' after one or many calls
POST /orders No Each call may create a new order

Note that idempotent refers to server state, not to the response code. A second DELETE may return 404 and still be idempotent.

Take quiz
Why is a repeated DELETE still considered idempotent even if it returns 404?
The server state is the same after one or many calls
The response code never matters to anyone
DELETE always returns 200
404 means the delete is cancelled
Why do two identical POST calls usually differ in effect?
POST bodies are always empty
POST cannot carry data
POST is cached by browsers
Each call may create a new resource

27. What is the dual-write problem?

The dual-write problem occurs when a service must update two independent systems, typically a database and a message broker, and there is no shared transaction that covers both.

If you commit the database first and the process crashes before publishing, downstream services never hear about the change. If you publish first and the database commit fails, they act on something that never happened.

orderRepo.save(order);          // 1. DB commit succeeds
// crash here -> event is lost
broker.publish(new OrderCreated(order));  // 2. never reached

Reordering the lines does not fix it, it only changes which failure you get. The usual cures are the transactional outbox or change data capture, which reduce the two writes to one.

Take quiz
In the dual-write problem, what is lost if the process crashes after the DB commit but before the publish?
The database row
The broker topic itself
The event that downstream services depend on
The network driver
Why does swapping the order of the two writes not solve the problem?
It makes both writes atomic
It only changes which failure you get
It removes the need for a broker
It doubles the throughput

28. How does change data capture complement the outbox pattern?

Change data capture (CDC) reads a database's transaction log and emits each committed change as an event. Used with an outbox table, it replaces the polling relay with a log reader.

A tool such as Debezium tails the write-ahead log, sees every insert into the outbox table and publishes it to Kafka. Because it reads the log, it picks up changes in commit order, adds almost no query load and does not need a 'published' flag that has to be updated.

Relay style How it finds new events Trade-off
Polling relay SELECT unpublished rows on a timer Simple, but adds latency and DB load
CDC relay Reads the DB transaction log Low latency, needs log access and connector ops

Either relay is still at-least-once. After a connector restart it may re-emit an event, so the consumer-side dedup stays necessary.

Take quiz
What does a CDC tool like Debezium read to find outbox events?
The database transaction log
The application log files
The HTTP access log
The broker consumer offsets
Even with CDC, why must consumers still deduplicate?
CDC always emits two copies
The outbox table is write-only
CDC cannot read committed data
The connector may re-emit an event after a restart

29. How does the inbox pattern make consumers idempotent?

The inbox pattern is the consumer-side mirror of the outbox. The consumer records each incoming message id in an inbox table inside the same local transaction as its business update.

  1. A message arrives with a unique id, for example event_id.
  2. The consumer starts a transaction and inserts the id into inbox (primary key on the id).
  3. If the insert conflicts, the message was handled before, so it is acked and skipped.
  4. Otherwise the consumer applies the business change and commits, then acks the broker.

If the consumer crashes before the ack, the broker redelivers, but the inbox row already exists and the repeat is skipped. This works with any at-least-once broker and needs no special broker feature.

Take quiz
What makes the inbox pattern's duplicate check reliable?
The inbox table lives on the broker
The consumer never acks
The id insert and the business change share one local transaction
The check runs in a separate microservice
A message is redelivered after a consumer crash. What does the inbox table cause?
The business change is applied twice
The repeat is detected as a primary key conflict and skipped
The broker deletes the topic
The message is moved to another partition

30. What happens when a consumer commits its offset before processing?

The consumer gets at-most-once behaviour. If it crashes after the commit but before finishing the work, the broker believes the message was handled, and on restart the consumer begins after it. The message is lost.

Kafka's default enable.auto.commit=true can cause this subtly: offsets are committed on a timer (5 seconds by default) during poll(), independent of whether your code finished. A slow handler may have uncommitted work covered by a committed offset.

// risky for critical data
consumer.commitSync();   // marks offset 120 as done
process(record);         // crash here = record 120 is gone

Take quiz
What delivery behaviour results from committing the offset before processing?
At-least-once
At-most-once
Exactly-once
Ordered delivery
Why can enable.auto.commit=true risk losing messages?
Offsets are committed on a timer regardless of whether processing finished
It disables retries
It deletes consumed messages
It commits offsets of other groups

31. What happens when a consumer group rebalance occurs mid-processing?

A rebalance takes partitions away from one consumer and gives them to another. Any records the first consumer fetched but had not committed will be read again by the new owner.

This often shows up when processing takes longer than max.poll.interval.ms (5 minutes by default). The broker decides the consumer is stuck, kicks it out and reassigns its partitions, while the original thread is still working. Two consumers can then process the same record.

  • Commit offsets in a ConsumerRebalanceListener.onPartitionsRevoked callback.
  • Keep per-poll work short, or lower max.poll.records.
  • Use cooperative rebalancing to reduce stop-the-world pauses.
  • Make handlers idempotent, since a duplicate can still slip through.
Take quiz
What is a typical cause of two consumers processing the same record around a rebalance?
The topic has too few bytes
The producer used acks=all
The broker version is too old
The handler exceeded max.poll.interval.ms so the partition was reassigned
Which callback lets you commit offsets just before partitions are taken away?
onTopicCreated
onMessageDropped
onPartitionsRevoked
onProducerClosed

32. How do you design an idempotent consumer using a unique constraint?

Let the database enforce uniqueness for you. Add a unique constraint on a business-meaningful identifier, then make the insert safe to repeat.

For a payment event, payment_id is the natural choice. A second insert for the same id is rejected or turned into a no-op, so no application-level race can create two rows.

CREATE TABLE payments (
  payment_id  VARCHAR(64) PRIMARY KEY,
  amount      NUMERIC(12,2) NOT NULL,
  created_at  TIMESTAMP DEFAULT now()
);

INSERT INTO payments (payment_id, amount)
VALUES ('pay-881', 25.00)
ON CONFLICT (payment_id) DO NOTHING;

Then check the affected row count. Zero rows means a duplicate, so skip follow-up actions such as sending a receipt. Skipping that check is a common bug that leads to duplicate emails.

Take quiz
Why check the affected row count after ON CONFLICT DO NOTHING?
It speeds up the commit
Zero rows means a duplicate, so follow-up actions should be skipped
It lets you change the primary key
It is required by the HTTP spec
Why is a database unique constraint safer than checking existence in application code?
It stays correct even when two consumers race at the same moment
It removes the need for a database
It works only on a single thread
It compresses the key

33. When should you use natural idempotency instead of a dedup table?

Use natural idempotency when the operation itself is safe to repeat, because it saves storage, an extra lookup and the need to expire old ids.

Good candidates are 'set' style updates: UPDATE ... SET status='SHIPPED', an upsert keyed by entity id that overwrites the whole row, or writing a file to a deterministic path. Repeating them yields the identical state.

Choose a dedup table when the action is a delta or has outside effects: adding to a balance, incrementing a counter, sending an email, calling a payment gateway. There is no way to make 'add 10' safe without remembering that this specific 10 was applied.

Operation Approach
Set status to SHIPPED Natural idempotency
Overwrite profile by user id Natural idempotency (upsert)
Credit account by 10 Dedup table or ledger entry with unique id
Send welcome email Dedup table, keyed by user + email type

Take quiz
Which operation is best handled with natural idempotency?
Adding 10 to a balance
Sending a welcome email
Incrementing a counter
Setting an order status to SHIPPED
Why does 'credit account by 10' usually need a dedup record?
Credits are always rejected
Accounts cannot be updated twice a day
It is a delta, so repeating it changes the result
Numbers cannot be stored in SQL

34. How long should you retain idempotency keys?

Keep a key for at least as long as a duplicate can realistically arrive. That window is the maximum of client retry duration, broker redelivery time and any replay or backfill period you allow.

Work it out from facts, not guesses. If the client retries for up to 1 hour, SQS may redeliver for the message retention period, and your DLQ is redriven weekly, then a 24-hour TTL is too short.

  • API request keys: commonly 24 hours to 7 days. Stripe, for example, may prune keys after 24 hours.
  • Event ids from a broker: at least the topic retention period, since consumers can rewind to any retained offset.
  • Financial or regulatory flows: often keep forever in a ledger with a unique transaction id.

Too short a retention causes duplicates to slip through. Too long causes table growth, which you can control with partitioning or TTL indexes.

Take quiz
What should drive the retention time of an idempotency key?
The size of the message
The longest time a duplicate could realistically arrive
The number of consumers
The colour theme of the API
What risk comes from keeping keys for too short a time?
Late duplicates are no longer detected
The table becomes too large
Keys become longer
Retries are blocked forever

35. How do you handle concurrent requests carrying the same idempotency key?

Two copies of the same request can arrive at the same instant, so a simple 'select, then insert' check will let both through. The fix is to claim the key atomically before doing any work.

  1. Insert the key with status IN_PROGRESS using a unique constraint, or use Redis SET key value NX EX 60.
  2. The request that wins the insert executes the operation.
  3. The loser sees the existing key and either returns 409 Conflict with a Retry-After hint, or waits briefly and returns the stored result.
  4. When the winner finishes it updates the row to COMPLETED with the response.

Add a timeout on IN_PROGRESS so a crashed winner does not block the key forever. After the timeout, a retry may take over, which is safe only if the underlying operation is itself recoverable.

Take quiz
Why is 'select then insert' unsafe for claiming an idempotency key?
Two concurrent requests can both see no row and both proceed
SELECT is not allowed in transactions
INSERT is slower than SELECT
Keys cannot be selected
What does the losing concurrent request typically return?
A random new key
A 500 and delete the winner's row
Nothing, the connection is dropped
A 409 Conflict or the stored result once ready

36. How does SQS FIFO deduplication work?

An Amazon SQS FIFO queue ignores a second message that carries the same MessageDeduplicationId within a 5-minute deduplication interval. The duplicate is accepted by the API but is not delivered to consumers.

You can supply the id yourself, or enable content-based deduplication, where SQS uses a SHA-256 hash of the message body as the id.

Detail Value
Deduplication window 5 minutes
Id source MessageDeduplicationId or SHA-256 of body
Ordering scope Per MessageGroupId
Covers Producer retries within the window

This protects only against duplicate sends. It does not stop duplicate processing, because a message can still be redelivered to a consumer after the visibility timeout. Consumers should stay idempotent.

Take quiz
How long is the SQS FIFO deduplication interval?
24 hours
30 seconds
5 minutes
14 days
What does SQS FIFO deduplication not protect against?
A producer retrying a send within the window
A message being redelivered to a consumer after the visibility timeout
Two sends with the same MessageDeduplicationId
Out-of-order messages inside one group

37. Why can the SQS visibility timeout cause duplicate processing?

When a consumer receives an SQS message, the message is hidden for the visibility timeout (30 seconds by default). If the consumer does not delete it before the timeout ends, SQS makes it visible again and another worker receives it.

The first worker is not told. If it was just slow, not dead, it carries on and finishes, so both workers complete the same job.

  • Set the timeout to comfortably exceed the 99th percentile processing time.
  • Call ChangeMessageVisibility to extend it for long jobs.
  • Delete the message only after the work and its dedup record are committed.
  • Standard queues can also deliver a message twice for internal reasons, so idempotency is still required.
Take quiz
What happens if an SQS consumer is slower than the visibility timeout?
The message becomes visible again and another worker may receive it
The message is permanently deleted
The queue pauses itself
The message is converted to FIFO
Which API call extends the time a message stays hidden for a long-running job?
ExtendQueueLifetime
RenewMessageLock
PauseMessage
ChangeMessageVisibility

Flink takes periodic, consistent checkpoints of all operator state using asynchronous barrier snapshotting, an approach inspired by the Chandy-Lamport algorithm.

  1. The job manager injects checkpoint barriers into the source streams.
  2. Each operator, on receiving barriers from all its inputs, snapshots its state to durable storage and forwards the barrier.
  3. Sources record their read position, such as Kafka offsets, in the checkpoint.
  4. When every operator has acknowledged, the checkpoint is complete.

On failure, Flink restores state from the last complete checkpoint and rewinds sources to the saved positions. Records processed after that checkpoint are re-read, but the state they touched has been rolled back, so state is updated exactly once.

Note: this is exactly-once for Flink's internal state. External outputs need an idempotent or transactional sink.

flowchart LR
  S["Source with offsets"] --> B["Barrier injected"]
  B --> O["Operator snapshots state"]
  O --> K[Sink]
  O --> D[(Durable checkpoint storage)]
  F[Failure] --> R["Restore state + rewind source"]

A two-phase commit (2PC) sink lets Flink write to an external system transactionally and tie that transaction to its checkpoints. This is how end-to-end exactly-once is achieved for sinks such as Kafka.

  1. Pre-commit: while a checkpoint is in progress the sink writes records inside an open transaction and flushes them, but does not commit.
  2. Commit: only after Flink confirms the checkpoint finished for the whole job, the sink commits the transaction.
  3. Abort: if the checkpoint fails, the transaction is aborted and the data is replayed.

With the Kafka sink you request this with DeliveryGuarantee.EXACTLY_ONCE. Downstream consumers must use read_committed, or they will see uncommitted data. Committed data becomes visible only at checkpoint intervals, so latency is at least the checkpoint interval.

40. How does Spark Structured Streaming achieve exactly-once?

Structured Streaming combines three ingredients: a replayable source, checkpointed progress and an idempotent sink. If any is missing, the guarantee falls back to at-least-once.

Before processing a micro-batch, Spark writes the planned offset range to a write-ahead log in the checkpoint directory. After the batch succeeds it records a commit. On restart, Spark re-runs any batch that was planned but not committed, using the same offset range, so results are deterministic.

Because a batch can be re-run, the sink must tolerate it. With foreachBatch you receive a batchId that is stable across retries, which you can use as a dedup key:

def write(df, batch_id):
    # upsert keyed by (batch_id, record key) so a re-run overwrites, not duplicates
    upsert_to_db(df, batch_id)

query = stream.writeStream.foreachBatch(write).start()

Take quiz
Which three ingredients does Structured Streaming exactly-once rely on?
A single JVM, a fast disk, a large heap
Two brokers, three zookeepers, one proxy
A UDP socket, a cache, a cron job
Replayable source, checkpointed progress, idempotent sink
Why is the batchId in foreachBatch useful?
It changes on every retry
It is the Kafka partition id
It is stable across retries, so it can serve as a dedup key
It encodes the cluster name

41. What is the difference between two-phase commit and idempotent retries?

Two-phase commit (2PC) coordinates several systems so they all commit or all abort together. Idempotent retries make no such promise: each system is updated independently and repeats are harmless.

Aspect Two-phase commit Idempotent retries
Coordination Central coordinator, prepare then commit None, each step retried on its own
Failure behaviour Participants may block holding locks if coordinator dies Retry later, no locks held across systems
Requirements All participants support XA or similar Unique ids and dedup or upsert
Availability Lower, all must be up Higher, eventual consistency
Fit Few tightly coupled databases Microservices, brokers, cloud APIs

Most cloud services, such as SaaS APIs, SQS or S3, do not take part in XA at all, so idempotent retries is often the only workable choice across service boundaries.

Take quiz
What is a known risk of two-phase commit if the coordinator fails after the prepare phase?
All data is erased
Participants can be left blocked while holding locks
Messages are delivered twice by design
The network is reconfigured
Why are idempotent retries often chosen across microservices?
Most services cannot join a shared XA transaction
They use less CPU than any other method
They guarantee strict ordering
They remove the need for unique ids

42. How do saga compensations handle partial failures?

A saga splits a business transaction into local transactions, each with a compensating action that semantically undoes it. If step 3 fails, the saga runs compensations for steps 2 and 1, in reverse order.

For an order: reserve stock, charge card, create shipment. If shipment creation fails, the saga issues a refund and releases the stock.

Exactly-once matters twice here. Each forward step must be idempotent so a retry does not double-charge. Each compensation must also be idempotent, otherwise a retried refund could pay the customer twice. Compensations must also be retryable until they succeed, since giving up leaves the system inconsistent.

flowchart LR
  A["Reserve stock"] --> B["Charge card"] --> C["Create shipment"]
  C -- fails --> X["Refund card"]
  X --> Y["Release stock"]
Take quiz
Why must saga compensating actions be idempotent too?
Compensations never run
They are executed only once by the broker
They are always read-only
A retried compensation could otherwise be applied twice, such as a double refund
In which order does a saga run compensations after a failure at step 3?
In random order
Only for step 3
Reverse order of the completed steps
Forward order starting at step 1

43. How do you store consumer offsets in the database for exactly-once?

Instead of letting Kafka track the position, the consumer saves the offset in the same database transaction as the result of processing. The database then makes 'result applied' and 'position advanced' a single atomic fact.

BEGIN;
UPDATE balances SET amount = amount + :delta WHERE account = :acct;
UPDATE consumer_offsets SET next_offset = :offset + 1
 WHERE topic = 'payments' AND partition = :p;
COMMIT;

On startup the consumer reads next_offset from the table and calls consumer.seek(partition, next_offset). A crash after the commit simply resumes from the new position. A crash before the commit leaves both unchanged, so the record is read again and applied for the first time.

The cost is that you must handle partition assignment and rebalances yourself, and the pattern only works when the sink is the same database.

Take quiz
Why store the offset in the same database transaction as the business update?
To save Kafka disk space
So 'result applied' and 'position advanced' succeed or fail together
To skip polling
To allow multiple groups to share one offset
What does the consumer call on startup to resume from the DB-stored position?
consumer.seek(partition, next_offset)
consumer.reset()
consumer.commitSync(0)
consumer.unsubscribe(next_offset)

44. How does message ordering affect duplicate handling?

Duplicates and reordering often arrive together. A retry of an old event can land after a newer one, and a simple 'have I seen this id?' check will not stop it from overwriting fresher data.

Example: status=PAID (v5) is processed, then a delayed duplicate of status=PENDING (v3) arrives. If it is a new id it passes the dedup check and the order flips back to pending.

Protect against this with a version or sequence number and apply it only if it is newer:

UPDATE orders
   SET status = :status, version = :version
 WHERE id = :id AND version < :version;   -- stale events update 0 rows

Kafka only guarantees ordering within a partition, so key messages by entity id to keep all events for one entity in the same partition.

Take quiz
What problem can a delayed duplicate of an older event cause?
It deletes the partition
It increases the version number
It freezes the consumer
It can overwrite newer data with stale data
What does the 'WHERE version
It deletes older rows
It forces a table lock
Stale events update zero rows and are ignored
It copies the row to the broker

45. Why does a deduplication window fail for late duplicates?

Many systems only remember ids for a limited time, such as SQS FIFO's 5 minutes or a Redis key with a 1-hour TTL. A duplicate that arrives after the id has expired looks like a brand-new message and is processed again.

Late duplicates come from long outages, a client retrying after a day, a DLQ redrive, or a topic replay after a bug fix. None of them respects your TTL.

  • Match retention to the real worst case, including replay and redrive periods.
  • For money and inventory, keep a permanent unique id in the business table itself, for example a ledger entry id with a unique index.
  • Prefer natural idempotency (set, upsert) where possible, since it needs no memory of old ids.
Take quiz
Why does a duplicate arriving after the dedup window expires get processed twice?
The broker re-encodes it
Dedup tables reject only new messages
Its id has been forgotten so it looks like a new message
The consumer ignores timestamps on purpose
What is a sturdier alternative for financial data than a short-lived TTL key?
A shorter TTL
A permanent unique id in the business table, such as a ledger entry id
A bigger Redis instance
Dropping the id altogether

46. When would you choose Kafka transactions over idempotent consumers?

Choose Kafka transactions when both input and output of your processing live in Kafka, as in a stream-processing pipeline that reads a topic, transforms and writes another topic. The platform then handles atomic offsets and output with no extra tables.

Choose idempotent consumers when the result lands outside Kafka, in a database, an API or an email provider, since Kafka transactions cannot span those.

Situation Better fit
Topic to topic enrichment or aggregation Kafka transactions / Kafka Streams EOS
Topic to PostgreSQL write Idempotent consumer (unique key or inbox)
Topic to third-party payment API Idempotent consumer + provider idempotency key
Need to survive manual replays Idempotent consumer, even alongside transactions

They are not exclusive. Many teams use transactions inside the streaming core and idempotent writes at the edges.

Take quiz
Which scenario is the best fit for Kafka transactions?
Reading one topic, transforming, and writing to another topic
Calling a third-party payment API
Sending marketing email
Writing a PDF to a local disk
Why are idempotent consumers needed for topic-to-database writes?
Databases cannot store offsets
Kafka transactions are disabled by default for databases only
Idempotent consumers are faster than any DB
Kafka transactions cannot include the database write

47. How do you test for duplicate processing?

You test it by forcing the failures that create duplicates and then asserting on the final state, not on log lines.

  1. Inject duplicates: publish the same event two or three times and assert that exactly one row, one charge and one email exist.
  2. Kill between steps: crash the consumer after the DB commit but before the offset commit, restart, and check the totals.
  3. Drop acks: use a proxy such as Toxiproxy to cut responses so clients retry.
  4. Force a rebalance: add or remove consumers mid-run.
  5. Replay a topic: reset the group offset to the beginning and confirm balances are unchanged.
  6. Race two requests: send concurrent calls with the same idempotency key.

Assert invariants such as 'sum of ledger entries equals sum of payments' after each run. A small sample test is easy to pass by luck, so run it with high volume and random kill timing.

Take quiz
What should a duplicate-processing test assert on?
Only the application log lines
The CPU graph
The final state, such as one row and one charge
The number of partitions
Which test best exposes the 'processed but not committed' gap?
Restarting the broker with no traffic
Killing the consumer after the DB commit and before the offset commit
Doubling the heap size
Adding a new topic

48. How do you troubleshoot duplicate payments in production?

Start by finding where the second copy was introduced. Duplicates have a small set of origins, and the logs usually show which one.

  1. Pick one affected payment and trace every request, message and DB write by its payment or idempotency key.
  2. Compare timestamps. Two attempts a few seconds apart suggest a client or gateway retry after a timeout. Minutes apart with the same offset suggest a consumer rebalance or redelivery.
  3. Check the HTTP layer: load balancer or proxy retries on 502/504, mobile apps resending on a spinner.
  4. Check the consumer: rebalance logs, max.poll.interval.ms breaches, SQS visibility timeouts shorter than the job.
  5. Check the data model: is there a unique constraint on the payment id? If not, add one.
  6. Check the provider call: was the idempotency key passed to the payment gateway, and was it the same on retries?

Then fix the cause, refund the duplicates, and add a test that reproduces the exact failure.

Take quiz
Two charges for one order happened 3 seconds apart. What is the most likely cause?
A client or gateway retry after a timeout
A topic compaction
A schema change
A broker disk failure
Which database safeguard directly prevents a second payment row for the same id?
A larger connection pool
A read replica
A longer log retention
A unique constraint on the payment id

49. Which is better: a dedup table or Redis SETNX, and why?

For money and other critical data, a dedup table in the same database as the business data is better. For cheap, short-lived protection, Redis SET NX is fine.

Aspect Dedup table (same DB) Redis SET NX
Atomic with business change Yes, one transaction No, separate system
Failure window None for the pair Crash between SETNX and DB write loses or duplicates work
Speed Slower, disk-based Very fast, in-memory
Durability Strong Depends on persistence and failover
Best for Payments, inventory, ledgers Rate limits, notification de-spam, cache-level guards

With Redis, a crash after SET NX but before the business write means the retry is wrongly rejected. If you set the key after the write, a crash in between lets a duplicate through. Neither order is safe, because two systems cannot commit together.

Take quiz
Why is a same-database dedup table safer than Redis for payments?
Redis cannot store strings
Databases are always faster
The dedup record and the business change commit in one transaction
Redis lacks TTL support
What is the risk of using Redis SET NX before a DB write?
The key is stored twice
A crash in between can make the retry wrongly rejected
Redis refuses all writes
The DB write becomes idempotent automatically

50. Explain the end-to-end flow of an exactly-once payment pipeline?

A reliable payment flow does not rely on one magic setting. It chains idempotency at every hop so a duplicate is neutralised wherever it appears.

  1. Client: sends POST /payments with an Idempotency-Key and reuses it on every retry.
  2. API service: claims the key atomically, saves the payment row and an outbox row in one DB transaction, then returns the stored result on repeats.
  3. Outbox relay / CDC: publishes PaymentCreated to Kafka with an idempotent producer. This is at-least-once.
  4. Consumer: reads with an inbox table so a repeated event id is skipped, and commits its offset after the DB commit.
  5. Gateway call: passes the payment id as the provider's idempotency key, so a retried charge is not charged twice.
  6. Ledger: writes entries with a unique transaction id, which is the final safety net.

Every duplicate that gets past one layer is caught by the next. The pipeline never delivers exactly once, but its effect is exactly once.

sequenceDiagram
  participant C as Client
  participant A as API + DB
  participant K as Kafka
  participant W as Consumer
  participant G as Gateway
  C->>A: POST with Idempotency-Key
  A->>A: payment + outbox in one tx
  A->>K: relay publishes event
  K->>W: deliver (maybe twice)
  W->>W: inbox check
  W->>G: charge with payment id as key
  G-->>W: result
Take quiz
In the pipeline, what protects against a retried charge at the payment gateway?
Increasing the topic partitions
Passing the payment id as the provider's idempotency key
Using acks=0 on the producer
Disabling the outbox relay
Why is each layer of the pipeline idempotent instead of relying on one?
A duplicate that slips past one layer can be caught by the next
Broker features are always enough alone
Layers run in parallel for speed
Idempotency is required only at the client
«
»

Comments & Discussions