AlgoMaster Logo
AlgoMasterBuild an Idempotent Consumereasy

Build an Idempotent Consumer

easy

At-least-once delivery protects against message loss by allowing a broker to redeliver a message when an acknowledgment is missing. The tradeoff is that the consumer may receive the same message more than once. To ensure the business effect happens once, the consumer must recognize message IDs it has already processed.

Design an IdempotentConsumer class:

  • IdempotentConsumer() creates a consumer with no processed message IDs.
  • boolean process(int messageId) processes a new ID and returns true, or suppresses a previously processed ID and returns false.

The first call with a particular messageId must record that ID and return true. Every later call with the same ID on the same object must return false. Suppressing a duplicate must not remove or reset its recorded ID.

Example 1:

Input:

Output:

Explanation: IDs 1, 2, and 3 are processed on first arrival. The later deliveries of IDs 1 and 2 are duplicates and are suppressed.

Example 2:

Input:

Output:

Explanation: The first delivery creates the effect and records ID 5. Both redeliveries find that ID already recorded.

Constraints

  • -2^31 <= messageId <= 2^31 - 1
  • At most 10^5 calls are made to process on one object.
  • Message IDs are stable: redeliveries of the same logical message use the same ID.
  • Each IdempotentConsumer object has its own deduplication state.
Hints

Loading...
CallReturns
new IdempotentConsumer()null
process(1)true
process(2)true
process(1)false
process(3)true
process(2)false
process(1)false

IDs 1, 2, and 3 are processed on first arrival. Later deliveries of 1 and 2 are suppressed.

Run checks these cases. Submit also runs a larger hidden set.