DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Testing Asynchronous Systems, Part 2: A Taxonomy of Failure, Detection, and Mitigation
  • 7 Failure Modes Every Production AI Agent Should Be Tested Against
  • How We Know What We Know
  • Why AI-Assisted Development Is Raising the Value of E2E Testing

Trending

  • How Has AI Impacted Code Obfuscation?
  • Testing Asynchronous Systems, Part 1: Mapping the System and Classifying Its Asynchrony
  • Seven AI Adoption Failures and How to Overcome Them
  • An Introduction to OpenID AuthZEN and authzen-enforcer, a Java SDK

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Testing Asynchronous Systems, Part 3: Message Semantics, Observability, and a Test Checklist

Testing Asynchronous Systems, Part 3: Message Semantics, Observability, and a Test Checklist

Learn how to test message delivery guarantees, idempotent processing, fault recovery, and observability in asynchronous systems.

By 
Stelios Manioudakis
DZone Core CORE ·
Dec. 03, 26 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
588 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

The first two parts of this series built a model before prescribing any tests. Part 1 argued that a test strategy for an asynchronous system has to start from two questions: which components and networks are really involved, and how asynchronous each connection really is. The same order-processing pipeline fell into three different regimes depending on where its boundary was drawn: a partially synchronous core region, an asynchronous, weak-notion-of-time edge made of multiple regions and offline mobile clients, and an asynchronous, no-notion-of-time batch integration with an external partner. A central idea was that a timeout is a trustworthy failure signal only to the degree that the system is synchronous. As timing guarantees weaken, we need to rely on different methods: logical ordering, message identity, and reconciliation.

Part 2 then enumerated what can go wrong. Components can stop, pause, lose state, or misbehave. Networks can lose, duplicate, or reorder messages. Failures differ by where they can be handled (application level or platform level) and by how they recur (transient, intermittent, or permanent). Detection and mitigation are separate properties that deserve separate tests. Two findings carry directly into this part. First, no failure detector can be both complete and accurate over an unreliable, partially synchronous network, so some test flakiness is a correct reflection of that limit rather than a defect. Second, the failure-dominance matrix showed that message duplication, loss, and reordering weigh more heavily in the two regimes where timing is weakest.

That is where this part begins. If messages can be lost, duplicated, and reordered, and a sender cannot tell a slow receiver from a malfunctioning receiver, then the main question is this: What can our system actually promise about each message, and how can we test that promise? This part covers three things, and Part 4 then brings the whole series together:

  • Message delivery and processing semantics. Why delivery and processing are separate guarantees. Why exactly-once processing is impossible in the presence of failure. Why exactly-once processing semantics, built on idempotence, is the achievable and testable target. It also covers how to test idempotence as its own contract, and where common reliability claims stop: a TCP acknowledgment does not mean your application processed the data, and a broker's "exactly-once" feature does not extend to an external side effect such as a card charge.
  • Observability as a testing prerequisite. Why diagnosing an asynchronous test failure needs correlated, cross-component tracing, and why causal identifiers are more trustworthy than timestamps.
  • A practical test-design checklist. The framework from all three parts condensed into items you can lift into a test plan. Organized by component, network hop, operation, workflow, failure temporality, and scenario.

The running example stays the same: an order-processing pipeline in which a payment service charges a customer's card. A duplicated charge is the failure this part keeps returning to. This is because it makes the difference between processing a message twice and having the system behave as though it processed it once easy to see.

Message Delivery and Processing Semantics: Testing the Contract

This is the area where imprecise language does the most damage, both in test names and assertions and in what gets promised to stakeholders.

1. Keep Delivery and Processing Separate

Delivery is the network transferring a message and presenting it to a component. Processing is the receiver acting on it: generating a response and causing a side effect. Each gets the same three-way classification independently: at-most-once (zero or one time), at-least-once (one or more times), and exactly-once (exactly one time).

A test asserting "exactly-once delivery" and one asserting "exactly-once processing" check different things. Conflating them is a common source of confusion when a suite has both a broker-level guarantee (delivery) and an idempotent-consumer guarantee (processing) layered together. Name tests to make the distinction explicit; for example, test_broker_at_least_once_delivery versus test_payment_handler_exactly_once_processing_semantics.

2. The Uncertainty That Senders Live In

Between sending a request and receiving a response, a sender cannot distinguish among five situations: the request was lost, the receiver crashed before processing, the receiver crashed after processing, the response was lost, or the network or receiver is merely slow. Only a response returns the sender to certainty. Because a sender in that state has exactly two options, give up or try again, it is choosing between at-most-once and at-least-once behavior. Neither is exactly-once.

Two naive attempts at exactly-once processing show why it is impossible in the presence of failure. If the receiver records the request and then processes it, a crash between the two steps means the retry is silently dropped: at-most-once. If the receiver processes the request and then records it, a crash between the two means the retry is processed again: at-least-once. There is always a gap, and a crash can occur within that gap.

3. Exactly-Once Semantics Is the Achievable, Testable Target

What is achievable, and what "exactly-once" almost always means in a well-engineered system, is exactly-once processing semantics: the system behaves as though processing happened once even if it happened several times. This is because the extra attempts are idempotent and therefore equivalent in effect. It requires at-least-once delivery, at-least-once processing, and an idempotent processing step. Equivalence is application-defined: duplicate log lines are usually fine; a duplicate card charge is a problem.

The test implication is that you should not assert that the handler was called exactly once. Assert that the side effect is equivalent regardless of how many times it was called.

Python
 
# Weak assertion: tests a guarantee that cannot exist
assert handler.call_count == 1

# Correct assertion: tests the guarantee that can exist
deliver_duplicate(message, times=5)
assert account.balance == expected_balance_after_single_charge
assert payment_gateway.charge_count == 1   # deduplicated via idempotency key


A myth worth busting: TCP is a reliable protocol, but it does not extend that reliability to your application. TCP guarantees delivery to the receiving kernel's buffer and acknowledges it before the application has read and processed the data. A crash between the acknowledgment and the application's processing silently turns what looked like at-least-once delivery into message loss at the application layer. At-least-once delivery at a lower layer does not entail at-least-once delivery at a higher one.

Note also that some brokers offer "exactly-once" features (Kafka's idempotent producers and transactions are an example). These give strong guarantees within the broker's own boundary, for instance for read-process-write cycles between Kafka topics. They do not extend to an external side effect such as a card charge or an email, which remains your responsibility. Read the fine print of any exactly-once claim: what boundary does the guarantee cover?

4. Testing Idempotence Directly

Idempotence, f(f(x)) = f(x), is what makes at-least-once processing acceptable. It should be tested as its own explicit contract, independent of the rest of the business logic. A minimal test matrix per state-changing operation:

  • Single call. Call once and record the resulting state.
  • Duplicate call. Repeat with the identical request and idempotency key; assert the state is unchanged.
  • Concurrent duplicates. Fire N identical requests simultaneously (a thread pool or async gather). Assert the state is equivalent to one successful call and that the downstream side effect (the real payment gateway charge) happened once, not N times.
  • Crash at the boundary. Simulate a crash between the side effect and the recording of the idempotency key. Then retry, and assert that the side effect is not duplicated and the key is eventually recorded.

The common implementation pattern is an idempotency key: the sender generates a UUID and attaches it to the request and every retry. The receiver deduplicates on it. Payment processors such as Stripe support idempotency keys in their APIs and replay the stored result for a repeated key. On the receiving side, the safe pattern is to record the key and perform the side effect in one transaction. Commit only if the key was new (for example via a uniqueness constraint on a keys table).

Crash injection at the idempotency boundary. The naive implementations fail at exactly one point: the gap between the side effect and the durability record. That gap is tiny in wall-clock time, but it is where interesting production bugs can live. It can be tested deterministically if you can fault-inject at that specific boundary rather than at the whole-request level:

  • Code-level fault injection lets you inject a fault, a delay, or a simulated crash at a specific method or line, without modifying the code under test. That makes "crash between the database write and the key write" a repeatable test rather than a hope that a random chaos experiment lands there.
  • If the implementation uses the transactional recording pattern, the most valuable test may not be fault injection at all. It may be a plain integration test proving that the transaction boundary actually wraps both operations. A simple test at the right level can beat an elaborate chaos experiment.

5. Testing Consumer-Side Deduplication Against Real Brokers

Use Testcontainers with a real Kafka, RabbitMQ, or similar broker rather than mocking the broker client. Duplicate-delivery semantics are broker-specific: Kafka's at-least-once behavior with manual offset commits differs from SQS's visibility-timeout redelivery, which differs from RabbitMQ's ack and nack handling. A mock encodes your assumptions about the broker. The real broker encodes its actual behavior, and the actual behavior is exactly what you are trying to test against.

Consume a message, process it, crash the consumer before committing the offset, restart it, and assert that the redelivered message produces an equivalent (not doubled) side effect.

6. Beyond Hand-Written Examples for Message Handlers

Idempotence tests written by hand cover the cases someone thought of. Several other techniques cover the rest, and each is cheap at the level where it applies:

  • Property-based testing generates sequences of messages, with duplicates, reorderings, and crashes interleaved, and checks invariants such as "the final state is the same as if each message had been processed once, in a valid order". It finds orderings nobody would have written down.
  • Fuzzing and malformed-input testing target the poison-message problem: a message that is structurally invalid, oversized, or valid but nonsensical must be routed to a dead-letter path without crashing the consumer or blocking the partition behind it.
  • Contract and schema-compatibility testing treat messages as contracts. Consumers lag, replay old messages, and run old versions during deploys, so a message written last month must still be readable today. Consumer-driven contracts verify that a producer still satisfies what each consumer relies on, and compatibility checks verify that new and old schema versions can coexist.
  • Reconciliation testing is the safety net for message loss: a comparison of what was sent with what was acknowledged that reports anything missing, duplicated, or conflicting. It matters most where no timeout can decide, as in the batch scenario of Part 1.
  • Approval (snapshot) testing guards the shape of serialized messages against accidental change.

Part 4 places each of these at the level where it pays off.

Observability as a Testing Prerequisite

For async systems, you cannot write good tests, or diagnose failing ones, without correlated cross-component observability. A single logical operation spans multiple components' local state and multiple network hops. None of them is visible from any one component's logs.

A minimum viable setup for testing:

  • Distributed tracing with OpenTelemetry, with trace context propagated through message headers and not only HTTP headers. This is the highest-leverage investment for diagnosing async test failures. It exposes the actual causal chain (the happened-before relationship) across components instead of forcing you to reconstruct it from timestamps in separate log files.
  • Structured logging with a correlation ID on every log line in every component, as a baseline even without full tracing.
  • Traces captured during fault-injection windows, not just on failure. The interesting bugs are often in the recovery path, which appears only if you capture the whole timeline and not just the final assertion failure.
  • Logical ordering, not timestamps. When correlating events across components, prefer causal identifiers (trace and span relationships, Kafka offsets within a partition, per-key sequence numbers) over wall-clock timestamps, which cannot be compared across components without accounting for skew.
  • Tests that assert on traces. Beyond diagnosing failures, a test can assert on the causal path itself: that the spans for each service exist in causal order and that a second charge never appears. This checks the end state and the path that led to it, and it checks that observability itself works.

A Practical Test-Design Checklist

The framework, condensed into something you can lift into a test plan.

Before Writing Any Test

☐  Map the components and networks involved (Part 1, section 2). Do not assume the logical architecture diagram is the real one.

☐  Classify each network hop's degree of synchrony (Part 1, section 3). This decides whether timeout-based assertions are valid for that hop.

☐  Identify which of the three scenarios (or which composition) your system actually is (Part 1, section 3.4), and prioritize the failure cells using the matrix in Part 2, section 1.5.

For Each Component

☐  Crash-Stop test: kill and verify graceful degradation.

☐  Omission test: pause and resume, verify correct resumption.

☐  Crash-Recovery test: kill with partial state loss, verify that durable state is actually durable.

For Each Network Hop

☐  Message loss test.

☐  Message duplication test.

☐  Message reordering test.

For Each State-Changing Operation

☐  Idempotence matrix (section 1.4): single call, duplicate call, concurrent duplicates, crash at the boundary.

☐  An explicit exactly-once-processing-semantics assertion on the resulting state, not on the call count.

For Each Multi-Step or Multi-Component Workflow

☐  Compensation test: fail partway through and verify correct rollback, including a failing compensation.

☐  Retry test: verify that the backoff strategy matches the assumed failure temporality (transient, intermittent, permanent).

Temporal Coverage

☐  At least one transient-failure (single-shot) test per failure type.

☐  At least one intermittent-failure test per critical path, using scheduled recurring faults or soak testing.

☐  At least one permanent-failure test verifying escalation and alerting rather than infinite retry.

Per Scenario

☐  Scenario 1: boundary-value tests around every timeout; a load-plus-degradation test that checks for retry storms.

☐  Scenario 2: property-based tests of merge logic with skewed clocks; a long partition test with reconciliation after healing; a device test with a wrong clock.

☐  Scenario 3: malformed and duplicate file tests; a reconciliation test for every "missing, duplicated, conflicting" case; production reconciliation alerts with a defined grace period.

Observability

☐  Trace context propagated through asynchronous messages, not only synchronous calls.

☐  Traces captured during fault-injection windows, not only at the final assertion.

Closing: Emergent Correctness, Not Component Correctness

There are four main ideas in this part. First, delivery and processing are different guarantees: exactly-once processing is impossible in the presence of failure. Exactly-once processing semantics, built on at-least-once delivery and idempotence, is the target worth testing, with assertions on resulting state rather than on call counts. Second, idempotence deserves its own contract: a single call, a duplicate call, concurrent duplicates, and a crash between the side effect and its record. Third, messages are contracts that outlive the code that wrote them, so schema compatibility, contract tests, malformed-input tests, and reconciliation belong beside the idempotence tests. Fourth, you cannot diagnose or assert on asynchronous behavior without correlated tracing and causal identifiers instead of timestamps.

Part 4 brings the series together. It lists the techniques that apply at each level (unit, integration, API, system, UI, and production) and explains how they help in each of the three regimes.

Semantics (computer science) systems Testing

Opinions expressed by DZone contributors are their own.

Related

  • Testing Asynchronous Systems, Part 2: A Taxonomy of Failure, Detection, and Mitigation
  • 7 Failure Modes Every Production AI Agent Should Be Tested Against
  • How We Know What We Know
  • Why AI-Assisted Development Is Raising the Value of E2E Testing

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook