Video in progress

Strong Junior 🏗️ System design

If the same message arrives twice from a queue, how do you protect the worker?

Most brokers give an at-least-once guarantee, so duplicates are normal. You need to make the worker idempotent: store each message's unique ID and don't redo one that was already handled, or write the operation itself so that repeating it is harmless.

📖 Answer

Where duplicates come from: the consumer finished processing a message but restarted before it could send the ack. The broker thinks "the message wasn't processed" and delivers it again. This isn't a bug — it's the nature of the at-least-once guarantee.

The most reliable way is to record processed messages in the database, in the same transaction as the business change:

@Transactional
public void handle(PaymentEvent e) {
    int inserted = jdbc.update("""
        INSERT INTO processed_messages(message_id) VALUES (?)
        ON CONFLICT (message_id) DO NOTHING
        """, e.messageId());
    if (inserted == 0) return;            // this message was already handled

    accountService.credit(e.accountId(), e.amount());
}

If credit fails, the transaction rolls back — the message_id isn't written either, and the next attempt handles the message correctly.

Sometimes it's easy to make the operation itself idempotent: instead of balance = balance + 100, use status = 'PAID' WHERE status = 'PENDING' — the second time, nothing changes.

Be careful with "exactly-once" promises: they usually hold only inside the broker. Together with your database and external APIs you still need idempotency.