Testing Asynchronous Systems, Part 4: A Technique-by-Level Test Strategy
Learn how to test asynchronous distributed systems across weak-time, partially synchronous, and batch integration regimes using practical testing techniques.
This part answers the practical question: given all of this, what do you actually test, where, and how? This part answers using an example that covers all three regimes. Fundamental tests for each regime are addressed. Tables summarizing more elaborate lists of testing activities are presented in the appendix.
A Scenario Covering All Regimes
A technician working in a basement with no coverage uses a tablet app to order a replacement part, building the order offline. Forty minutes later, coverage returns and the app syncs the order to the nearest of three regions, where the core checkout validates stock, charges the customer's account, and notifies the technician. Because the part is stocked by a wholesale distributor, an adapter writes the order into that night's batch file, and the distributor's confirmation comes back in a response file somewhere between 6 hours and 3 days later. The same order passes through the weak-time edge (regime 2), the partially synchronous core (regime 1), and the no-time batch integration (regime 3), in that order.
For each stage, we list a sample of fundamental tests. The appendix holds the tables of techniques by level, with the remaining techniques for each level and an example test for each. All figures are illustrative.
Stage 1: The Device and the Edge (Regime 2, Weak Notion of Time)
The tablet's clock cannot be trusted. Delivery can be duplicated or reordered, and the delay is open-ended. Correctness has to come from logical ordering and idempotent replay.
- Property-based testing of merge and ordering logic. State the rules (merging two versions of an order is commutative, associative, and idempotent) and generate thousands of random edit histories with random delivery orders. A failure could arrive as a minimal counterexample, such as a part removed and re-added on two devices ending up as two lines in one replica and one in the other.
- Deliberately wrong clocks. Create edits stamped years ago or tomorrow, and run the real app with the device clock set two days back. Ordering must come from logical versions, so a tablet running two days fast cannot win every conflict.
- Idempotence under duplicates and crashes. Send the same submit request five times, concurrently and after a consumer restart, and also fail the system between the side effect and its deduplication record. Exactly one purchase order may result, and the assertion is on the resulting state, not on call counts.
- A simulated device. Model the tablet's queue, clock, and connection, then generate sequences: go offline, queue 10 actions, reconnect in a different order with 3 duplicates, crash the sync client midway. Compare the server state with a simple model. It finds bugs such as acknowledged actions that are never removed from the queue and are resent forever.
- Schema compatibility with old app versions. Tablets in the field replay messages written up to a year ago, so the newest consumer must still read them, and old consumers must tolerate added fields.
- Partition testing with a convergence check. Cut one region off for 2 hours and run another for an open-ended period, while both sides accept orders. Writes must be queued or explicitly rejected, never silently dropped, and replicas must converge after healing without a double order reaching the supplier.
- Offline, double-submit and multi-device tests. Go offline, build an order, reconnect and expect exactly one order; click submit twice; edit the same order on two devices and expect a visible conflict rather than a silent overwrite.
- Replication and reconciliation monitoring. Track replication lag, the conflict rate, and orders stuck in syncing, and check invariants hourly, such as no order submitted twice. Pre-release tests only sample this space; production checks cover it continuously.
Stage 2: The Core Region (Regime 1, Partially Synchronous)
Timeouts are meaningful here, so the work is calibrating them and keeping the system stable when load and degradation arrive together.
- Boundary value tests of timeouts and retries. With a fake clock, test a 400 ms retry budget at 399 ms (no retry), at 401 ms (exactly one retry) and after a third failure (an error, not a fourth attempt). Add a table of error level, temporality and attempt number so that an application-level failure, which cannot succeed, never retries.
- Mutation testing of that logic. Deliberately break the retry code (remove the cap on total retry time, flip a comparison) and run the suite. A surviving mutant marks a behavior nothing asserts, and a missing cap is exactly what produces retry storms.
- Scripted dependencies that are slow or failing. Make the card gateway answer in 300 ms normally, in 3 seconds for 5% of calls, and with a 503 twice for one order. Assert no second charge on a slow answer and that no order ends with zero or two charges. Slow and failed are different cases.
- Component tests against a real broker. Consume a message, kill the consumer before it commits its position, restart it, and assert one equivalent charge. A mock would only encode the team's assumption about redelivery.
- Consumer-driven contract tests. The payment service declares the StockReserved fields it relies on. The inventory build checks them, so a field renamed to tidy a schema fails the inventory build instead of the checkout.
- Load and degradation together. Apply five times normal load and, in the same run, 90 seconds of packet loss in one availability zone. Assert no retry storm, no cascade into the notification service, and full recovery afterwards. Neither the load alone nor the fault alone reveals the defect.
- Correlation and trace assertions. Place 1,000 orders carrying a correlation identifier. Each must end confirmed or cancelled with exactly one charge, and the trace must show no second charge attempt hidden behind a correct end state.
- Canary releases, synthetic orders and alert tests. Release changes to 5% of traffic against a baseline, place a synthetic order every minute, and test the alert rules themselves against synthetic data. The latency distribution drifts, so calibration must be re-validated continuously.
Stage 3: The Distributor (Regime 3, No Notion of Time)
No timeout can serve as a failure detector. We rest on the file contract and on reconciliation. Much of the testing becomes permanent operational activity.
- Boundary and malformed-input tests of the file contract. Generate files with 0, 1, the maximum and one more line items, zero and negative quantities, over-long codes and truncated content. The generator must refuse invalid input and the parser must reject a partial file instead of ingesting it. With no live handshake, the format is the entire contract.
- Fuzzing the response parser. The response comes from another organization, so feed it mutated and truncated variants. It may reject them but must never crash, hang or half-apply a file.
- Table-driven reconciliation tests. Sent 100 and acknowledged 98 reports 2 missing; an acknowledgment for an unknown order is reported; a duplicate counts once; shuffling the acknowledgments changes nothing.
- A simulated drop folder. Control arrival: the response never arrives, arrives twice, arrives half-uploaded, or arrives valid but with conflicting quantities. Seed 20 known discrepancies and assert that exactly those are reported, independent of when in its cycle the job ran.
- A round trip against the partner's sandbox over real elapsed time. Exchange files across at least 48 hours each release. Waiting is the point: it exposes a credential that expires on day 2 or a batch window that shifts after the partner's clock change.
- Pending states and usability tests. The technician should see that the order was sent and is awaiting confirmation. There is no confirmation after 36 hours and it has been escalated, not a blank. Ask users what they would do at 36 hours; if the answer is to send it again by hand, the design invites duplicates.
- Scheduled reconciliation, baseline monitoring and runbook drills. A daily job reports orders sent but not acknowledged past the 36-hour grace period (a business policy, not a technical threshold). Arrival times are compared with the last 90 days to distinguish a slow day from a broken integration, and a tabletop exercise rehearses a response that is 48 hours late.
Across the Boundaries
Every handoff between stages needs its own contract-style test: idempotent replay from device to region, an exactly-once effect on the file write from the broker to the adapter even if the adapter restarts, and reconciliation and deduplication when the response returns. A correlation identifier created on the tablet should appear in the file's line identifier and in the reconciliation report. One order can be followed through all three regimes. The terminal state, that the part has arrived, can only be verified by reconciliation, not by waiting for it.
Wrapping Up
The idea underlying everything in this article is that correctness, scalability, and reliability of a distributed system are emergent properties. They belong to the system as a whole and not to a single component. A payment service can pass every unit test in isolation and still double-charge once it sits behind an unreliable queue with a naive retry policy in front of it. Testing each component correctly is necessary. It is never sufficient.
The failure taxonomy and the delivery and processing semantics covered here are the minimum vocabulary needed to evaluate what and how to test. Guessing semantics by looking at old incident reports is never sufficient. A comprehensive async test suite is not the one with the most tests. It is the one that can be traced, cell by cell, to an explicit map of components. The one that can be traced to a classification of how asynchronous each connection really is. It is the test suite behind deliberate decisions about which failure modes are in scope and which are explicitly, documentedly, not.
Appendix
A table of possible testing activities is presented at the unit level, the API level and at system level. Each activity or technique is categorized, explaining the test itself, what it verifies and the regimes that it can be used for. All tables are indicative.
A.1 Unit
Unit tests are the cheapest place to get timing and failure logic right, because a fake clock and fake I/O make asynchrony deterministic.
| technique | what it verifies | example asynchronous test | regime |
|---|---|---|---|
|
Specification-based design |
|||
|
Equivalence partitioning and boundary value analysis |
Decision logic at the edges of its input and time ranges: timeout thresholds, retry limits, backoff caps, batch sizes, TTLs. |
Retry policy with a 200 ms timeout: assert behavior at 150, 199, 201 and 500 ms of simulated latency; test the retry limit at N-1, N and N+1; test the largest accepted message size. |
1 |
|
Decision-table testing |
Combined conditions that select a recovery action. |
A table of error level x temporality x attempt number: a platform-level transient failure on attempt 1 retries at once; an application-level failure compensates; exhausted retries escalate. One test per row. |
1 |
|
State-transition testing |
Workflow and handler state machines: legal and illegal transitions, including events that arrive twice or out of order. |
The order state machine receives PaymentCompleted before StockReserved, or the same event twice; assert the transition table and that no illegal state is reachable. |
1, 2 |
|
Approval (snapshot) testing |
Stable shape of serialized messages, generated batch files and notification templates. |
Snapshot the OrderPlaced message and the outbound batch file; a diff flags an accidental field rename or reordering that would break a downstream consumer. |
2, 3 |
|
Metamorphic testing |
Relations that must hold between outputs when no exact oracle exists. |
Reconciliation output is unchanged when the acknowledgment list is shuffled; processing a message log twice equals processing it once; an unrelated message does not change an order's outcome. |
2, 3 |
|
Structure-based analysis |
|||
|
Coverage analysis (statement, branch, condition) |
Whether failure-handling code is exercised at all: catch blocks, timeout branches, compensation paths. |
The coverage report shows the payment handler's refund-failure branch never runs; add a test that forces it. |
All |
|
Mutation testing |
Whether the tests would notice a bug in timing, retry and deduplication logic. |
Mutate >= to > in a timeout comparison, delete the dedupe check, or change the retry counter. Every surviving mutant points at a missing assertion. |
1, 2 |
|
Static analysis and code review |
Async mistakes visible without running anything: missing timeouts, unawaited promises, blocking calls on an event loop, unbounded retries, swallowed exceptions, inconsistent lock ordering. |
A lint rule fails the build on a floating promise; the review checklist asks whether every outbound call has a timeout and a retry budget and every consumer is idempotent. |
All |
|
Data-race detection |
Races and atomicity violations on shared in-process state such as caches, in-memory dedupe sets and counters. |
Hammer the dedupe store from 64 threads with overlapping keys under a race detector: no race reports, no double insert. |
1 |
|
Message and data semantics |
|||
|
Idempotence and duplicate-delivery testing |
Applying the same message once, twice or many times yields an equivalent state. |
Call the handler with one message and one idempotency key 1, 2 and 5 times and compare the final state; make a dependency fail between the side effect and the key write. |
All |
|
Out-of-order delivery testing |
Consumer logic against every permutation of a short event sequence. |
Feed all 6 orderings of three events and assert the same final state or an explicit, correct rejection. |
2, 3 |
|
Input-space exploration |
|||
|
Invariants over many generated inputs and operation sequences. |
merge(a, b) equals merge(b, a); any permutation or duplication of operations converges to the same state; backoff is non-decreasing and capped. |
2 |
|
|
Fuzzing |
Parsers and deserializers against malformed, truncated and adversarial input: message envelopes, EDI or CSV batch files, message payloads. |
Fuzz the batch-file parser for hours: no crash, no hang, no unbounded memory, and bad input yields a typed error instead of a half-parsed order. |
All |
|
Interface, integration and contract |
|||
|
Test doubles and service virtualization |
Handler logic in isolation, with dependencies scripted to fail, stall or misbehave. |
Stub the payment gateway to time out twice, then succeed; assert two retries, correct backoff and one recorded charge. |
1 |
|
Concurrency and timing |
|||
|
Systematic concurrency testing |
Interleavings of async tasks explored deterministically instead of by luck. |
Explore every schedule of two tasks debiting one balance; a failing schedule is printed and can be replayed exactly. |
1, 2 |
|
Virtual-time (fake clock) testing |
Time-dependent logic without real waiting: timeouts, heartbeats, backoff, TTLs, expiry. |
Advance a fake clock by 31 s and assert the circuit breaker opens; step the clock backward by 5 s and assert no negative durations or reordering. |
1, 2 |
|
Condition-based waiting |
Async assertions that wait for an effect instead of sleeping for a fixed time. |
Poll until the handler's side effect appears, with a generous ceiling, and fail with a message that names the missing condition. |
1, 2 |
|
Fault and resilience |
|||
|
Fault injection (code level) |
Behavior when one specific statement fails, such as the gap between a side effect and the record that deduplicates it. |
Throw after the database write and before the idempotency-key commit; the retry must not duplicate the effect. |
All |
|
Non-functional |
|||
|
Performance microbenchmarking |
Latency of hot paths whose cost feeds timeout calibration. |
Benchmark serialization, dedupe lookup and backoff computation; fail CI on a regression beyond a budget. |
1 |
|
Security testing |
Message-level authentication and replay defenses. |
A tampered signature, an expired timestamp and a reused nonce are each rejected; an unauthorized sender is refused. |
2, 3 |
|
Localization and internationalization testing |
Time zones, calendars and text in notifications and timestamps. |
An order placed at a DST change renders correctly; internal comparisons use UTC or monotonic time, never local time; every notification template has all placeholders in every locale. |
2 |
A.2 API
At the API level, asynchrony shows up as accepted-but-not-done responses, idempotency keys, webhooks and the agreements between teams.
| technique | what it verifies | example asynchronous test | regime |
|---|---|---|---|
|
Specification-based design |
|||
|
Equivalence partitioning and boundary value analysis |
Limits at the API surface: payload size, rate limits, idempotency-key lifetime, deadline values. |
Request at the maximum body size and one byte over; call exactly at and just beyond the idempotency-key expiry; hit the rate limit at N and N+1 requests. |
1 |
|
Functional API testing |
Endpoint behavior including async patterns: 202 Accepted with a status URL, polling, idempotency keys. |
POST /orders returns 202 and a status URL; poll until a terminal state; repeat the request with the same idempotency key and receive the same result. |
1 |
|
Message and data semantics |
|||
|
Idempotence and duplicate-delivery testing |
Idempotency keys: duplicate, concurrent, expired, and reused with a different body. |
Ten concurrent requests with one key produce one side effect; the same key with a different body is rejected. |
All |
|
Compatibility and versioning testing |
Old clients against new API versions during rolling deploys. |
Run the previous release's client test suite against the new server build. |
1, 2 |
|
Consistency-model testing |
Read-your-writes, monotonic reads and bounded staleness across regions. |
Write through region A and immediately read through region B: either the new value or an explicit pending state, never a silent absence; measure the staleness window. |
2 |
|
Input-space exploration |
|||
|
Property-based testing |
Generated request sequences checked against API invariants. |
Requests are derived from the API specification and checked: no response may violate the schema or return a 5xx. |
1, 2 |
|
Fuzzing |
Stateful sequences of calls that find crashes, 5xx errors and state bugs. |
A generator derives dependency-aware call sequences from the API specification (create order, pay, cancel, retry) and reports unexpected server errors. |
1, 2 |
|
Interface, integration and contract |
|||
|
Spec-driven API conformance testing |
Responses and events match the published API specification. |
Validate every response and every published event against its specification in CI; fail the build on an undeclared field or status code. |
All |
|
Asynchronous API lifecycle testing |
Eventual completion, polling behavior, webhook delivery, retries and signatures. |
A webhook receiver gets the same event twice and out of order; it verifies the signature and applies the event once. |
2, 3 |
|
Negative and error-path testing |
Status codes, error bodies, rate limiting and partial failures. |
A 429 with Retry-After is honored; a 503 triggers a retry rather than a user-visible failure; a timeout returns a clear pending status. |
1 |
|
Consumer-driven contract testing |
API expectations of each consuming client or service. |
Each mobile and web client publishes the response fields it relies on; the provider build fails if one disappears. |
1, 2 |
|
Test doubles and service virtualization |
The API under test with its downstream services scripted. |
Slow the downstream inventory stub and assert the API returns 202 with a pending status instead of blocking. |
1 |
|
Fault and resilience |
|||
|
Fault injection (network) |
Deadline propagation and graceful degradation at the API boundary. |
A client deadline of 2 s must reach downstream calls and no work continues after cancellation; add latency to a dependency while calling the API. |
1 |
|
Non-functional |
|||
|
Load, stress and spike testing |
Throughput, latency distribution, saturation, retry storms and queue growth at the API. |
Ramp load and add a spike while a dependency slows down; watch p99, error rate and consumer lag, and confirm the system recovers. |
1 |
|
Security testing |
Authentication, authorization, injection, replay, rate limiting and SSRF in webhooks. |
Replay a captured request after the signature window; probe object-level authorization on order IDs. |
2, 3 |
A.6 System (End-to-End)
System tests are the only level where load, partial failure and several components interact, so they carry the resilience and end-to-end techniques.
| technique | what it verifies | example asynchronous test | regime |
|---|---|---|---|
|
Specification-based design |
|||
|
Scenario-based testing |
Business flows across all components, including honest pending states. |
Place an order, poll until confirmed, and assert exactly one email and one charge, using a correlation ID instead of a fixed wait. |
All |
|
Regression testing |
Every production incident becomes a permanent test at the lowest level that reproduces it. |
A duplicate charge found in production becomes an idempotence test; a lost response becomes a retry test. |
All |
|
Smoke testing |
After every deploy, a minimal path through each async channel works. |
Publish a test message through each topic and confirm consumption, the side effect and the acknowledgment. |
All |
|
Combinatorial (pairwise) testing |
Fault, location, timing and load combinations without running all of them. |
Generate pairwise experiments from {kill, pause, latency, loss} x {broker, consumer, database} x {idle, loaded}. |
1, 2 |
|
Message and data semantics |
|||
|
Consistency-model testing |
Recorded histories of concurrent operations checked against a consistency model. |
Record the operations of concurrent clients during partitions and check the history for linearizability or serializability violations. |
2 |
|
Reconciliation and data-integrity testing |
Full round trip with a partner sandbox over real elapsed time. |
Exchange files with the partner sandbox across a realistic window, at least once per release, and reconcile every record. |
3 |
|
Compatibility and versioning testing |
Mixed versions during rolling upgrades and migrations. |
Roll consumers one by one while producing; messages from version N are consumed by N+1 and the reverse, with no loss or duplicate effect. |
1, 2 |
|
Concurrency and timing |
|||
|
Deterministic simulation testing |
The whole system in one process with a simulated network, disk and clock, reproducible from a seed. |
A simulator drops, delays and reorders messages at random; a failing seed reproduces the exact failure every time. A heavy investment, mostly for new infrastructure. |
1, 2 |
|
Fault and resilience |
|||
|
Fault injection (network) |
Resilience under realistic load: retry storms, cascades, recovery. |
Sustained load while latency is injected for one availability zone; assert no retry storm, no cascade, and full recovery after the fault lifts. |
1 |
|
Fault injection (process and resource) |
Crash, pause and restart of real components in a full environment. |
Kill the payment service between reserve and charge; pause the broker leader; verify the order still completes or compensates. |
1 |
|
Network partition testing |
Multi-region divergence, split-brain and reconciliation after healing. |
Partition one region for 10 minutes while both sides accept writes; heal and assert convergence with no silent loss. |
2 |
|
Byzantine fault injection |
Only where participants are not fully trusted: consensus layers, multi-party systems, adversarial input. |
A duplicated node (two instances sharing one identity) presents conflicting messages; forged events are published directly to the broker. |
2 |
|
Recovery, failover and disaster-recovery testing |
Recovery time and data loss, restore from backup, region failover, replay from the log. |
Fail region A; measure the time until region B serves traffic and verify that no acknowledged order is lost. |
2 |
|
Non-functional |
|||
|
Load, stress and spike testing |
Sustained, peak and sudden load on the full pipeline. |
Replay a peak-hour message rate plus a 3x spike and watch end-to-end latency to confirmation. |
1 |
|
Soak (endurance) testing |
Slow leaks and drift over days: memory, connections, queue growth, clock drift, certificate expiry. |
Run 72 hours of steady load while tracking memory, consumer lag and open connections. |
1, 3 |
|
Scalability and capacity testing |
How throughput scales with consumers and partitions, and where it stops. |
Double the consumer count and measure throughput until the partition count caps it. |
1 |
|
Observability testing |
Assert on the actual causal path through the services, not only the end state. |
A test asserts that spans for gateway, inventory, payment and notification exist in causal order and that no second charge span appears. |
All |
|
Configuration testing |
Timeouts, retry budgets, flags and limits are what you calibrated, in every environment. |
A policy check fails if a production timeout differs from the calibrated value or a retry budget is unbounded. |
1 |
|
Security testing |
Threat scenarios across channels: forged events, replay, poison-message denial of service. |
Publish a forged OrderPlaced directly to the broker without credentials; expect rejection and an alert. |
All |
Opinions expressed by DZone contributors are their own.