Search Sreeni's Insights

Filter by content type
technical August 14, 2018 15 min read

How to make messaging reliable and consistent? - Part 5

Make messaging reliable: guaranteed delivery, retry, poison messages, dead-letter queues, replay, idempotency, deduplication and Saga consistency.

Share:

How to make messaging reliable and consistent? - Part 5

Messaging lets a producer and consumer work at different times, but the gap between them creates failure questions. A consumer can write a NAV to SQL Server and crash before completing the message. A provider file can be permanently malformed, while a database outage may be temporary. In the previous article, we discussed how messages flow through adapters, routers, dispatchers and consumers. In this article, we are going to start with the failure model, then see guaranteed delivery, delivery semantics, retry, poison messages, dead-letter queues, replay, idempotency, deduplication and Saga consistency.

Enterprise Integration Patterns series:

  1. What is enterprise integration and why do we need it? - Part 1
  2. What are the styles of integration? - Part 2
  3. What are messages, commands and events? - Part 3
  4. How do messages flow from producer to consumer? - Part 4
  5. How to make messaging reliable and consistent? - Part 5 (this article)
  6. What is event-driven architecture? - Part 6
  7. What is event sourcing? - Part 7

TL;DR Summary

  • A reliable design starts with the failure model: send, store, receive, process and acknowledge are separate failure windows.
  • Guaranteed delivery combines durable storage, a receive lock, acknowledgement and an explicit retry or dead-letter path.
  • At-most-once can lose work, at-least-once can deliver duplicates and exactly-once is rarely an end-to-end property.
  • Retry is for transient failures; poison messages need a bounded delivery count and a dead-letter queue.
  • Replay is deliberate processing after the cause is fixed, not blindly sending every failed message again.
  • Idempotency makes repeated business operations safe, while deduplication recognises repeated technical messages.
  • A Saga provides consistency across services by coordinating local transactions and compensating for steps which already completed.

Why does messaging fail?

A message flow contains several independent steps,

  1. The producer creates the message.
  2. The transport accepts and stores it.
  3. A consumer receives it under a lock.
  4. The consumer validates and performs a business write.
  5. The consumer acknowledges completion.

Each step can fail separately. The network can disconnect after the broker accepts a message, so the producer may not know whether to send again. The consumer can store a price and crash before acknowledgement, so the broker can deliver the same message again. SQL Server can be temporarily unavailable, or a provider row can contain an unknown ISIN which will never become valid through retry.

If we treat every failure as transient, the platform retries bad data forever. If we treat every failure as permanent, a short database outage loses valid work. The consequence reaches the customer: a missed NAV can leave a factsheet stale, while a duplicate price write can create an incorrect return. Reliability begins by distinguishing these failure windows and recording what happened.

Guaranteed delivery and delivery semantics

What is guaranteed delivery?

Guaranteed delivery is a design in which a message is durably stored, the consumer acknowledges it after successful processing and a known failure path handles messages which cannot complete. It is not a promise that every business operation across every system happens exactly once.

Azure Service Bus peek-lock mode lets a consumer receive a message under a lock. The consumer performs the work and calls CompleteAsync only after the required side effect is durable. If the process abandons the message, the lock expires or the process fails, the broker can make the message available again.

The lock and database write are not one transaction. That gap is why the consumer must be idempotent, which means safely handling a repeated message. We will define idempotency after the failure lifecycle.

The following diagram depicts guaranteed delivery as four steps between price ingestion, the broker and performance. (1) Price ingestion sends the message. (2) The broker writes it to its durable store before it acknowledges, so once price ingestion gets the ack, the message survives a broker restart. (3) Performance receives the message with a peek-lock; the message stays in the queue, hidden from other consumers. (4) Only after processing does performance complete the message, and only then does the broker remove it. If performance crashes between steps 3 and 4, the lock expires and the message is delivered again; nothing is lost, but it may arrive twice.

Guaranteed delivery with durable storage and acknowledgement
Guaranteed delivery with durable storage and acknowledgement

This is at-least-once delivery: the broker guarantees the message is not lost, not that it arrives exactly once. That is why idempotency and deduplication, later in this article, matter. Also note that the guarantee only starts at step 2: if price ingestion crashes before it gets the ack, it must send again.

At-most-once, at-least-once and exactly-once

Delivery semanticPlain meaningFund-data consequence
At-most-onceAcknowledge before work, so work is not repeatedA price can be lost after acknowledgement and before storage
At-least-onceRetry until acknowledgement, so the message can repeatNAV upsert and downstream reactions must be idempotent
Exactly-onceTransport and business side effect happen onceUsually possible only inside a narrow transaction, not end to end

At-most-once can be acceptable for a disposable notification, but it is unsafe for a provider price which must be stored. At-least-once is the practical default for durable work. Exactly-once should not be claimed across a provider, broker, database and search index unless the complete boundary has been verified.

Must Be Aware: Receiving a message once is not the same as applying its business effect once. Always place the acknowledgement boundary beside the business write in the design.

The failure lifecycle

The normal success path is receive, process, store the result and complete the message. The failure path needs a bounded retry, a definition of a poison message, a dead-letter queue and a replay procedure.

The following diagram depicts the complete life of one message. The consumer receives the price message with a peek-lock, so it stays in the queue but is hidden from other consumers. If processing succeeds, the consumer completes the message and the broker removes it. If processing fails, the consumer abandons it (or the lock expires), and the broker increases its delivery count. While the count is within the maximum, the message goes back to the queue and is retried. When the count goes over the maximum, the message is treated as poison and moved to the dead-letter queue, so it stops blocking the queue. An operator investigates and fixes the cause, then replays the message back to the price queue, where it starts again.

Reliable message lifecycle with retry and dead-letter queue
Reliable message lifecycle with retry and dead-letter queue

The flow highlighted in purple is receive, process, success and complete. The normal path avoids the dead-letter queue; the failure path is deliberately visible and bounded.

What is retry?

Retry means attempting a failed delivery or operation again. Retry is useful when the failure may recover, such as a short network reset, SQL Server connection failure or provider rate limit. Retry is harmful for malformed JSON, an unsupported schema version or a missing mandatory ISIN.

An immediate retry is suitable for a very short transient error. Backoff waits between attempts and can increase the delay so that an unavailable dependency is not hit by every worker at once. Polly was available in 2018 for expressing retry and circuit-breaker policies in .NET:

var retryPolicy = Polly.Policy
    .Handle<TimeoutException>()
    .WaitAndRetryAsync(
        retryCount: 3,
        sleepDurationProvider: attempt =>
            TimeSpan.FromSeconds(attempt));

This is an example only. The exception list and delay must fit the provider and operation. Do not retry a non-idempotent command unless the provider supports an idempotency key or repeating the operation is safe.

Azure Service Bus tracks delivery attempts. MaxDeliveryCount limits how many times a queue or subscription can deliver a message before it moves to the dead-letter subqueue. The value must allow temporary recovery but must not hide a permanent failure for an unlimited time.

What is a poison message?

A poison message is a message which repeatedly fails because its content or required business condition cannot be processed. A malformed provider file reference, unknown schema version, unknown ISIN or invalid currency can be poison for the current consumer.

The consumer should record MessageId, CorrelationId, delivery count, failure reason and provider context before the message leaves the normal path. It must not put credentials or a large file body into the error log.

What is a dead-letter queue?

A dead-letter queue (DLQ) is a holding channel for messages which cannot be delivered or processed normally. It is not a place to forget failures. An operator or repair process inspects the reason, fixes the data or consumer, and decides whether to replay, discard or manually repair the message.

Azure Service Bus provides a dead-letter subqueue for queues and subscriptions. A consumer can call DeadLetterAsync when it knows that another normal delivery will not help. The platform must monitor the count and age of DLQ messages, because a process can be healthy while important fund data is waiting for attention.

Must Do: Give every DLQ an owner, alert and runbook. Otherwise, the platform only moves the problem away from the main queue.

The following diagram depicts what happens to one bad message. Price ingestion sends a price with an unknown currency to the price queue. The price processor fails on it every time (the red cross), so the message never reaches its intended outcome. After the maximum delivery count, the broker moves it, together with the failure reason, to the dead-letter queue (the red stop marker). The price queue keeps flowing for every other price, and operations can investigate the dead message, fix the cause and replay it.

Dead-letter channel after delivery failure
Dead-letter channel after delivery failure

The dead-letter channel is a controlled holding path, not a discard path. An operator can inspect the reason and decide whether to repair, replay or discard the message.

What is replay?

Replay means deliberately processing a stored message again after the cause of failure has been corrected. It is useful after fixing a mapping rule, deploying a corrected consumer or rebuilding a downstream view.

A safe replay follows these steps,

  1. Identify the message type, provider, time range, consumer and failure reason.
  2. Fix the malformed data, mapping rule or consumer deployment.
  3. Verify the correction with a small sample.
  4. Confirm that the operation is idempotent or that a deduplication key is available.
  5. Replay a small set and compare it with the provider source.
  6. Replay the remaining messages with rate limits and monitoring.
  7. Record the range, code version, operator and outcome.

Event Hubs and Apache Kafka can replay retained events by reading from an earlier offset. This is useful for rebuilding a view, but replaying an event which triggers an external command must be controlled. Replaying a PriceDataPointChanged event may rebuild a calculation; replaying a create command may create a duplicate external record.

Handling duplicate messages

What is idempotency?

Idempotency means applying the same operation more than once produces the same final result as applying it once. An idempotent receiver is a consumer which applies this rule to its business operation.

For the fund platform, upserting a NAV using (ISIN, PriceDate) can be idempotent if the write rule is explicit. A repeated message with the same provider revision can be a no-op. A different value for the same date may be a correction which needs an audit record rather than a silent overwrite.

CREATE UNIQUE INDEX IX_Price_Isin_Date
ON FundPrices (Isin, PriceDate);

The database key protects identity, but the handler still decides whether a duplicate revision is safe, whether an older effective date is ignored and whether a provider correction creates a new audit record. An idempotent receiver is the safety net for at-least-once delivery.

What is message deduplication?

Message deduplication recognises a repeated technical message before the consumer performs the business work. Azure Service Bus duplicate detection can compare stable MessageId values within its configured history window. The producer must reuse the same MessageId when retrying the same send; generating a new random id defeats broker detection.

Broker deduplication is helpful but not sufficient. Its window can expire, a message can pass through another channel or the technical MessageId can differ from the business key. A consumer-side deduplication table can store ConsumerName, MessageId, CorrelationId and processed time in the same local transaction as the data point update.

Must Consider: Deduplication is an optimisation; idempotency is the safety property. Keep the idempotent business write even when broker duplicate detection is enabled.

The following diagram depicts an idempotent receiver handling a duplicate. The same price message (MessageId 7f3c) reaches the price queue twice: once normally and once as a redelivery after a lock expired. For each message, the receiver first checks its table of processed MessageIds. The first time, the answer is no: it upserts the price by ISIN and price date and records the MessageId. The second time, the answer is yes: it skips the work and simply completes the message. The data point store ends with one row, however many times the message is delivered. Even without the MessageId check, the upsert by ISIN and price date is itself idempotent, so the check is a second line of defence that also saves work.

Idempotent receiver and message deduplication
Idempotent receiver and message deduplication

The important boundary is the receiver and its store. Even when the broker recognises a duplicate, the business write remains idempotent because a message can arrive through another path or outside the broker’s detection window.

Consistency across services with a Saga

What is a Saga?

A Saga coordinates a long-running business process as a sequence of local transactions. Each service commits its own data, and a later failure triggers a compensating action for steps which already completed. A Saga avoids holding one distributed transaction across unrelated databases.

Consider onboarding a new fund share class. The reference store creates the share class, the search index registers it, the performance service configures its inputs and the factsheet service publishes the profile. These stores cannot safely share one SQL transaction.

Orchestration versus choreography

Orchestration uses a coordinator which sends the next command and decides what to do after a response or failure. It makes the workflow and compensation path visible.

Choreography lets each service publish an event and the next service react without a central coordinator. It can reduce central control, but many event links and compensation rules can become difficult to understand.

The following diagram depicts Saga orchestration for share-class onboarding. The saga coordinator owns the whole flow: it sends one command at a time to the service which owns that step, waits for the reply and decides what happens next. Each step is a local transaction in its own service: (1) reference data creates the share class, (2) search registers it and (3) performance configures it. If all three succeed, the coordinator publishes ShareClassOnboarded. If step 3 fails (the red path), there is no distributed rollback; instead, the coordinator undoes the completed steps in reverse order with compensating commands: unregister from search, then remove the share class. The saga ends as “onboarding failed, compensated” rather than leaving a half-onboarded share class behind.

Saga orchestration with compensation
Saga orchestration with compensation

The flow highlighted in purple is the successful path from start through the three steps to publishing ShareClassOnboarded. The dashed path is the compensation. When a completed step can’t be undone automatically, the coordinator records a manual repair task instead of a compensating command.

Compensation is not always a technical undo. If an external system has published a share class, deleting it may be unsafe. Compensation can mark the record inactive, publish a correction event or create an operational exception. The business owner must define the correct result.

For a practical discussion of managing transactions across services, refer to Saga pattern - managing transactions across microservices.

Reliable consumer outline

A reliable price consumer can follow this sequence,

  1. Receive a message in peek-lock mode.
  2. Validate message type, ContentType, schema version, ISIN, price date and source.
  3. Check the consumer deduplication record or business key.
  4. Upsert the data point and write an audit record in SQL Server.
  5. Record the processing outcome.
  6. Complete the message only after the local write is durable.
  7. Abandon for a transient failure or dead-letter for a permanent failure.

The SQL write and deduplication record should be in one local transaction where possible. If the process fails after the transaction commits and before CompleteAsync, the message is delivered again, the idempotent receiver sees the existing result and completes safely.

Operational checks

Reliability is not complete until it can be observed. Monitor the following,

  • Oldest message age and queue length
  • Delivery count, retry rate and lock expiry
  • Dead-letter count and age
  • Complete, abandon and processing-failure outcomes
  • Duplicate detection and idempotent no-op counts
  • Provider file date and last successful ingestion
  • Time between data-point storage and consumer completion
  • Saga step failures and outstanding compensation

Trace a sample message by MessageId and CorrelationId across adapter, broker, consumer and store. A dashboard showing only process availability is not enough; a healthy process with a blocked queue is still an outage for the consumer.

Wrap up

In this article, we have looked at the failure model, guaranteed delivery, peek-lock, at-most-once, at-least-once and exactly-once semantics, retry, poison messages, dead-letter queues, replay, idempotent receivers, deduplication and Saga consistency. I really appreciate that you took the time to read this article. In the next article, I will walk you through event-driven architecture, event notification, event-carried state transfer and the complete fund-data event pipeline.

Related Posts