Message queues and delivery guarantees
Most queues guarantee at-least-once delivery: a message is not lost but can arrive twice, because without an acknowledgement (ack) it is redelivered. So the consumer must be idempotent: the id of the processed message and the data change are written in one transaction. Tests cover a duplicate, a consumer crash between processing and ack, ordering (in Kafka only within a partition), the DLQ and consumer lag.
System design · Backend
The message "credit 30" arrived twice. How much money did the user get?
The transfer service puts a message "credit 30 to acc_2" on a queue. The consumer processed it but crashed before acknowledging it. The queue, receiving no acknowledgement, delivered the same message again. The balance rose by 60. A double processing appeared in a system without code errors. This is not a failure but normal behaviour of most queues. The lesson covers what a queue guarantees, why a consumer must be idempotent and what to test.
How it works and why. A queue (Kafka, RabbitMQ, SQS) decouples services in time: a producer puts a message and moves on, a consumer processes it when it can. This gives resilience to peaks and independence of services, but the system becomes asynchronous. To avoid losing a message the queue waits for an acknowledgement (ack) from the consumer and delivers again if it is missing. This is where delivery guarantees come from.
- At-most-once: a message may be lost but is not duplicated. The acknowledgement is sent before processing.
- At-least-once: a message is not lost but may arrive twice. The acknowledgement comes after processing. The most common option.
- Exactly-once: achievable within one broker (for example Kafka transactions, deduplication in SQS FIFO queues within a time window), but at the boundary with external stores like your DB it is practically built from at-least-once and an idempotent consumer.
Why a duplicate appears
An idempotent consumer. At-least-once implies the main rule: processing the same message again must not change the result. Usually the consumer records the ids of processed messages and skips duplicates. It is important that the id record and the balance change are in one transaction, otherwise there is a window between them again:
BEGIN;
INSERT INTO processed_messages (message_id)
VALUES ('m-123')
ON CONFLICT DO NOTHING;
-- 0 rows inserted: a duplicate, ROLLBACK and send the ack
UPDATE accounts SET balance = balance + 30 WHERE id = 'acc_2';
COMMIT;
Example: a duplicate test. The test publishes the same message twice and checks that the credit happened once. The result is asynchronous, so we wait for a stable state instead of a fixed pause:
test('a duplicate message credits the account once', async ({ request }) => {
const before = await balanceOf(request, 'acc_2');
const msg = { messageId: 'm-' + Date.now(), account: 'acc_2', amount: 30 };
await publish('credits', msg);
await publish('credits', msg); // the same messageId again
await expect.poll(() => balanceOf(request, 'acc_2')).toBe(before + 30);
// give a wrongly written consumer time to apply the second copy
await new Promise((r) => setTimeout(r, 3000));
expect(await balanceOf(request, 'acc_2')).toBe(before + 30);
});
(publish and balanceOf here are project helpers.) The last pause is deliberate: the test checks the absence of an event and there is otherwise nothing to wait for. This is the only case where a fixed pause is justified, and it should be a short margin, not the main mechanism.
Other concepts.
- DLQ (dead letter queue): where messages go that could not be processed after N attempts. They must not be ignored: in fintech this is stuck money, so DLQ length needs an alert and re-processing needs a procedure.
- Ordering. In Kafka the order is guaranteed only within a partition. If events of one account go to different partitions, a "debit" may be processed before a "top-up". The usual solution: the message key by account id.
- Consumer lag: how many messages are waiting to be processed. A metric for monitoring and for load tests.
- Poison message. A message that always fails on processing. It must go to the DLQ after a few attempts and not block the queue or loop forever.
Two ways to process a message
Just add the amount
A redelivery adds 30 again. The balance diverges from reality without a single error in the logs.
Check the id and change the balance together
The processed message ids and the balance change in one transaction. A duplicate is skipped.
Limits and alternatives. The table of processed ids grows, so it needs cleanup by age; the period must exceed the maximum time within which a message can still be redelivered. Sometimes idempotence comes from the nature of the operation (setting the status to "COMPLETED" is safer than adding an amount), and a separate table is not needed. The more expensive the error, the more worth choosing transactional approaches, for example an outbox: the event is written in the same transaction as the data change and a separate process publishes it to the queue.
Common mistakes.
- Assuming a queue guarantees exactly one delivery: without an idempotent consumer it is hidden doubling of money.
- Not testing a consumer crash between processing and acknowledgement.
- Not watching the DLQ: messages quietly accumulate.
- Assuming a global message order: it exists only within a partition or a FIFO group.
Check yourself
A consumer reads a message, credits the money and then sends an ack. It crashes between the credit and the ack. What happens and how to avoid doubling?
Answer
The queue received no ack and will deliver the message again, so the money is credited twice. It is avoided with an idempotent consumer: store the ids of processed messages and write the id and the balance change in one transaction, so the duplicate is skipped.
The events of one account, "top-up" and "debit", are processed in the reverse order. Why does it happen in Kafka and what to change?
Answer
In Kafka order is guaranteed only within a partition, and the account's events landed in different partitions. The fix: a message key by account id so all its events go to one partition. The test: send a series of events for an account and check the processing order.