Distributed Systems and Microservices Testing Questions
Testing systems composed of many interacting services. Covers integration and end-to-end testing across service boundaries, handling eventual consistency and partial failure, and validating behavior in distributed, specialized architectures. Includes fault injection and testing at scale.
Create a test plan to detect deadlocks and livelocks in a microservices architecture that uses distributed locks and RPC calls. Describe adversarial scheduling and fault-injection techniques you'd use to provoke the condition, resource-starvation tests, and watchdogs that assert forward progress. Explain which observability signals and assertions you'd add to automated tests to detect these conditions.
Sample Answer
Direct answer
Combine adversarial scheduling (deliberately interleaving lock-acquisition attempts and RPC calls to provoke a cycle) with resource-starvation tests (holding a lock or exhausting a pool just long enough to force contention) and a watchdog that asserts forward progress within a bounded time, so the test suite catches both a hard deadlock (nothing ever progresses) and a livelock (things keep happening, but nothing useful completes).
Structured elaboration
- Provoking the condition deliberately. A deadlock or livelock is, by definition, rare under normal random timing; a test suite that just runs the system under light concurrent load will usually not hit it. Instead, script the specific interleaving that creates a lock-ordering cycle (service A acquires lock 1 then requests lock 2 from service B, while service B acquires lock 2 then requests lock 1 from service A) using controllable delays or an explicit test-only coordination hook that pauses each side at the critical moment.
- Resource-starvation tests. Separately, saturate a shared resource (a connection pool, a thread pool, a rate-limited downstream) to just below its limit and add one more contender, and assert the system either queues it fairly and eventually serves it (progress, just delayed) or rejects it explicitly (a defined backpressure signal), rather than silently hanging forever.
- Watchdog assertion. Wrap the scenario in a watchdog that asserts SOME forward-progress signal (a completed request, an incrementing counter, a released lock) occurs within a generous but bounded time window; a livelock is specifically the case where activity (retries, lock attempts) continues but the progress signal never fires, so "no timeout occurred" is not sufficient evidence of correctness, only "the progress signal fired" is.
- Observability signals to add. Thread/goroutine dumps or stack traces on timeout (to see exactly where each participant is blocked), lock-acquisition and lock-wait-time metrics (a lock held far longer than its expected duration is a strong deadlock signal even before a full hang), and request-latency histograms (a livelock often shows as a spike in retries or a plateau in the completion rate, not literally zero throughput).
Worked example: a hard deadlock
A scripted two-service lock-ordering scenario with a watchdog assertion:
import threading
def test_lock_ordering_cycle_is_prevented_or_detected():
lock1, lock2 = threading.Lock(), threading.Lock()
progress = threading.Event()
barrier = threading.Barrier(2)
def service_a():
with lock1:
barrier.wait() # deliberately synchronize both sides at the critical moment
with lock2:
progress.set()
def service_b():
with lock2:
barrier.wait()
with lock1:
progress.set()
# daemon=True is deliberate: this scenario deadlocks the two threads
# PERMANENTLY (Python's plain threading.Lock has no built-in deadlock
# detector, unlike a real database engine). Without daemon=True, the two
# blocked threads never terminate, and the interpreter hangs forever at
# exit waiting to join them, even after the watchdog assertion below has
# already correctly failed and reported the deadlock.
t1 = threading.Thread(target=service_a, daemon=True)
t2 = threading.Thread(target=service_b, daemon=True)
t1.start(); t2.start()
made_progress = progress.wait(timeout=2.0) # the watchdog
assert made_progress, (
"deadlock detected: neither side made progress within the watchdog timeout "
"(this specific interleaving requires a consistent lock-ordering discipline, "
"or a lock-timeout-and-retry strategy, to resolve)"
)
t1.join(timeout=0.1); t2.join(timeout=0.1)
This test is EXPECTED to fail against a naive implementation that acquires locks in inconsistent order (that is the point: it deliberately provokes the classic lock-ordering deadlock), and passing means the system under test has a real mitigation (consistent lock ordering, a timeout-and-retry, or a deadlock detector) in place.
Worked example: a livelock, the other half of this question
A hard deadlock and a livelock look identical from a bare "did it time out" check, so a suite that only has the example above has not actually tested for livelocks at all. Here two "polite" agents each back off the instant they detect contention, in perfect lockstep, so neither ever completes, yet both stay busy retrying: a deterministic, single-threaded simulation (rather than real OS threads, to avoid exactly the kind of real-timing race that makes ad hoc threaded livelock demos flaky) makes this reliably reproducible:
class Agent:
def __init__(self, name, own_lock, other_lock):
self.name = name
self.own_lock = own_lock
self.other_lock = other_lock
self.holds_own = False
self.retries = 0
self.done = False
def decide(self, snapshot):
"""Decide this round's action from a snapshot taken at the START of
the round, so neither agent gets a sequencing advantage within the
round -- a true simultaneous update, not a sequential one."""
if self.done:
return "noop"
if not self.holds_own:
return "take_own"
if snapshot.get(self.other_lock) is None:
return "take_other"
return "back_off"
def apply(self, action, held_by):
if action == "take_own":
held_by[self.own_lock] = self.name
self.holds_own = True
elif action == "take_other":
held_by[self.other_lock] = self.name
self.done = True
elif action == "back_off":
held_by[self.own_lock] = None
self.holds_own = False
self.retries += 1
def test_livelock_symmetric_polite_backoff_never_converges(max_steps=200):
held_by = {"lock1": None, "lock2": None}
a = Agent("a", "lock1", "lock2")
b = Agent("b", "lock2", "lock1")
for step in range(max_steps):
if a.done or b.done:
break
snapshot = dict(held_by)
action_a, action_b = a.decide(snapshot), b.decide(snapshot)
a.apply(action_a, held_by)
b.apply(action_b, held_by) # both actions land together, from the same snapshot
made_progress = a.done or b.done
assert not made_progress, "expected the symmetric polite back-off pattern to livelock forever, not complete"
assert a.retries > 10 and b.retries > 10, (
f"expected substantial, ongoing retry activity from both sides (the defining signature of a "
f"livelock, as opposed to a deadlock's total silence): got a={a.retries} b={b.retries}"
)
Running this prints made_progress=False with a.retries=100 b.retries=100 after the full 200 simulated rounds: real, ongoing activity, and zero useful progress, which is exactly the property a watchdog based only on "did anything happen" would miss, and exactly why the observability signals in point 4 (a retry-rate or lock-attempt counter, not just a completion counter) matter for distinguishing this from a slow-but-healthy system.
Trade-offs and pitfalls
- A watchdog timeout that is too short will falsely flag a system that is merely slow (heavily contended but still making progress) as deadlocked; calibrate the timeout against the system's actual expected worst-case latency under contention, not an arbitrary round number.
- Deliberately scripted interleavings (using a barrier, as above) prove a SPECIFIC scenario is or isn't handled; they do not prove the absence of ALL possible deadlocks, which is a fundamentally harder problem. Pair scripted scenarios with production-side lock-wait-time monitoring as a complementary, ongoing detection mechanism.
- Distinguishing a livelock from legitimate-but-slow retry behavior requires a real progress signal, not just "activity is happening"; a system that keeps retrying a doomed operation forever looks identical to one that is slowly succeeding unless the test asserts on an actual completion signal, not just CPU or network activity.
- When a scenario is EXPECTED to deadlock or livelock permanently (as both examples above are, by design), make sure any threads used to model it are daemonized or otherwise bounded; a non-daemon thread that blocks forever will hang the test process itself at exit, turning a correctly-failing assertion into a CI job that never returns.
Design a deterministic fault-injection harness for a distributed workflow engine that executes multi-step transactions with compensating actions. Describe how you would inject faults at a precise, chosen step and timing, how you would capture a deterministic trace of what happened, and how you'd assert that the retry and compensation logic still produces a correct final state.
Sample Answer
Direct answer
Build the fault-injection harness around a hook keyed by step index and elapsed time within the workflow (so a fault can be triggered precisely at "step 3, 50 milliseconds after it starts" rather than randomly), capture a full, ordered trace of every step transition and compensation action the workflow takes, and assert that after the fault, the compensation logic drives the workflow to one of its explicitly-defined terminal states (fully completed, or fully and correctly rolled back), never a state that is neither.
Structured elaboration
- Precise, addressable injection points. Instrument the workflow engine (or wrap each step's execution) with a hook that the test can parameterize:
inject_fault(at_step=3, after_ms=50, fault_type="exception"). This lets the test target the exact moment a compensating-transaction pattern is most likely to have a bug: mid-step, after some side effect has already happened but before the step recorded its own completion. - Deterministic trace capture. Every step transition (started, succeeded, failed, compensating, compensated) gets logged with the workflow's instance ID and a monotonic sequence number, so a test can assert not just the FINAL state but the exact SEQUENCE of compensations that ran, in the right order, exactly once each.
- Assert convergence to a valid terminal state. For a saga-style workflow (payment charged, inventory reserved, shipping scheduled, each with its own compensating action), a fault at step 2 must drive the workflow to EITHER "all steps after 2 skipped, step 1's compensation ran, workflow is CANCELLED" or, if the design retries instead of compensating, "step 2 eventually succeeded on retry, workflow proceeded normally." There is no valid state where step 1 committed, step 2 failed, and no compensation and no retry ran; that stuck state is exactly what this harness exists to catch.
- Idempotency of compensation itself. Since the workflow engine may itself retry a failed compensation, assert that running a given compensating action twice (because of the engine's own retry-on-failure behavior) does not double-refund, double-restock, or otherwise apply its effect twice.
Worked example
class FaultSchedule:
def __init__(self, at_step, after_ms, fault_type="exception"):
self.at_step, self.after_ms, self.fault_type = at_step, after_ms, fault_type
def test_fault_at_step_2_triggers_compensation_of_step_1_only():
trace = []
engine = SagaEngine(
steps=[charge_payment, reserve_inventory, schedule_shipping],
compensations=[refund_payment, release_inventory, cancel_shipping],
on_transition=lambda evt: trace.append(evt),
)
engine.inject_fault(FaultSchedule(at_step=2, after_ms=10, fault_type="exception"))
engine.run(order_id="ord-99")
assert engine.final_state("ord-99") == "CANCELLED"
step_names = [e.step for e in trace if e.kind == "compensated"]
assert step_names == ["charge_payment"], (
f"expected only step 1's compensation to run, got: {step_names}"
)
# idempotency of the compensation itself: replay it and assert no double refund
balance_before = ledger.balance("acct-1")
engine.replay_compensation("ord-99", step="charge_payment")
assert ledger.balance("acct-1") == balance_before, "replaying a compensation must not refund twice"
Trade-offs and pitfalls
- Precise step-and-timing fault injection requires the workflow engine to expose a hookable extension point; for a fully managed third-party workflow service without such hooks, you are limited to injecting faults at the boundary of each step's own external call (still useful, just less precise about the exact millisecond).
- The most common bug this class of test finds is a compensation that assumes it will only ever run once; always include a deliberate double-invocation of the compensation path in the test suite, since the engine's own retry logic is a completely realistic way for that to happen in production.
- Asserting only the final state (
CANCELLED) without asserting the exact sequence of compensations can hide a bug where the RIGHT final state is reached by the WRONG path (for example, two compensations ran instead of one, coincidentally leaving the same final balance); capture and assert the full trace, not just the endpoint.
In a distributed service that writes data to two datastores for redundancy, describe tests to validate correctness when one datastore becomes slow or unavailable. Explain how you'd simulate latency, partial writes, and read-after-write consistency, and how you'd assert eventual consistency and data integrity across both stores.
Sample Answer
Direct answer
Test each datastore's unavailability independently by injecting latency or failure into ONE store at a time while the other stays healthy, and assert three properties: writes still succeed (with a defined degraded mode), reads reflect the healthy store's state without silently returning stale data from the failed one, and once the failed store recovers, both stores converge to the same value.
Structured elaboration
Dual-write-for-redundancy systems have a specific failure geometry: two independent stores, each of which can fail independently, with the interesting bugs living in the ASYMMETRY between them. Structure tests around:
- One-store-slow. Inject latency into store A only (via a proxy, a fault-injecting client wrapper, or a test double) and assert the write path either waits appropriately (if it requires both stores to succeed) or completes via store B with a documented degraded-consistency flag (if it tolerates a partial write), whichever the design actually promises. The important thing is asserting the SPECIFIC behavior the system claims, not "it doesn't crash."
- One-store-down. Fully fail store A's writes and assert either the whole write fails cleanly (never a silent partial write with no record of the gap) or the write to B succeeds and a reconciliation record is created noting A is behind, depending on the intended design.
- Read-after-write across two stores. Immediately after a write, read from EACH store independently and assert you never construct a response that mixes a fresh value from B with a stale value from A in a way that looks internally inconsistent to the caller (for example, showing an updated balance from one field sourced from B, alongside a stale related field sourced from A).
- Recovery and convergence. Bring the failed store back online and assert that whatever reconciliation mechanism exists (a background repair job, a read-repair-on-access pattern, a replay of a durable write-ahead log) actually drives both stores to the same value within a bounded time, and that the test can prove this by reading both stores directly and diffing them, not just trusting the reconciliation job "ran."
Worked example
class FaultyStoreProxy:
"""Wraps a real store client; can be told to fail or delay calls so tests
control exactly when and how one store misbehaves."""
def __init__(self, store, fail=False, delay_s=0.0):
self.store, self.fail, self.delay_s = store, fail, delay_s
def write(self, key, value):
if self.fail:
raise ConnectionError("simulated store outage")
if self.delay_s:
time.sleep(self.delay_s)
return self.store.write(key, value)
def read(self, key):
return self.store.read(key)
def test_store_a_down_write_still_succeeds_with_reconciliation_record():
store_a = FaultyStoreProxy(InMemoryStore(), fail=True)
store_b = FaultyStoreProxy(InMemoryStore())
redundant = DualWriteService(store_a, store_b, reconciliation_log=InMemoryLog())
redundant.write("acct-1", {"balance": 100})
assert store_b.read("acct-1") == {"balance": 100}
pending = redundant.reconciliation_log.pending_for("acct-1")
assert pending, "a write that only reached one store must leave a reconciliation record, not silently succeed as if both stores agreed"
# store A recovers; run reconciliation and assert convergence
store_a.fail = False
redundant.run_reconciliation_once()
assert store_a.read("acct-1") == store_b.read("acct-1") == {"balance": 100}
Trade-offs and pitfalls
- This class of test is only as good as your fault-injection proxy's fidelity; a proxy that can only fail 100% or succeed 100% misses the more common real-world case of INTERMITTENT slowness or partial failure (some requests succeed, some time out), so consider parameterizing the proxy with a failure rate, not just an on/off switch.
- The most common false-negative here is a test that asserts "the write eventually succeeds somewhere" without also asserting a reconciliation record exists; that combination looks correct in the test but silently accumulates permanent drift in production if the reconciliation job itself has a bug or was never actually scheduled.
- Recovery testing needs an explicit "turn the fault back off" step and a subsequent convergence assertion; a surprising number of dual-write test suites only ever test the FAILURE half and never actually verify the system correctly heals once the fault clears.
Design how automated tests should assert on observability signals, logs, metrics, and distributed traces, to detect functional regressions in distributed transactions. Give examples of the kinds of assertions you would add, such as checking for expected spans or aggregated metric thresholds, and explain how you'd avoid brittle checks against variable timing and sampling.
Sample Answer
Direct answer
Write assertions against the SHAPE of observability data (a span with the expected name exists, an error tag is absent, an aggregated metric crosses a threshold) rather than its exact values, and specifically design each assertion to tolerate the variance that real distributed tracing and sampling introduce (timing jitter, sampling gaps, span ordering) so the test is checking a real regression, not a coincidence of the specific run.
Structured elaboration
- What to assert on. For a distributed transaction spanning multiple services, useful test-writable observability assertions include: a specific expected span exists in the trace (proving a particular code path executed), no span in the trace carries an error tag (proving the transaction completed without an internal failure being swallowed), and an aggregated metric (a counter, a latency histogram bucket) crossed an expected threshold within the test's time window (proving a specific code path was exercised at the expected rate).
- Avoiding brittleness from timing variance. Never assert on an EXACT latency value from a trace; assert on a bounded range, or better, on a metric's PERCENTILE over the test's own generated load rather than any single span's duration, since a single span's timing is inherently noisy in any real environment (CI runners are especially variable).
- Avoiding brittleness from sampling. If your tracing system samples (only some fraction of transactions get a full trace recorded), a test relying on trace presence will intermittently fail purely due to sampling, independent of correctness; for tests that need reliable trace assertions, force 100% sampling for the test's own traffic (most tracing systems support a per-request sampling override) rather than relying on the ambient sampling rate.
- Structuring the assertion as a query, not a scrape. Query the tracing/metrics backend's own API for the specific trace ID your test generated (correlate via a header or a deterministic test-generated ID) rather than attempting to parse raw exported trace data directly, since the backend's query API is the stable, documented interface, while raw export formats can change between versions.
Worked example
def test_transaction_trace_has_no_error_span_and_expected_hop_present(tracing_client):
trace_id = str(uuid.uuid4())
checkout_client.place_order(sample_order(), trace_id=trace_id)
trace = poll_until(
lambda: tracing_client.get_trace(trace_id),
predicate=lambda t: t is not None and t.is_complete(),
timeout_s=5.0,
)
span_names = {span.name for span in trace.spans}
assert "inventory-service.reserve" in span_names, "expected the inventory-reservation hop to appear in the trace"
error_spans = [s for s in trace.spans if s.has_error_tag]
assert not error_spans, f"trace contains error-tagged spans that should not be present: {[s.name for s in error_spans]}"
def test_checkout_latency_metric_p95_within_bound(metrics_client):
for _ in range(30):
checkout_client.place_order(sample_order())
p95 = metrics_client.query_percentile("checkout_latency_ms", percentile=95, window_s=60)
assert p95 < 500, f"checkout p95 latency {p95}ms exceeded the 500ms expected bound over this test's own traffic"
Trade-offs and pitfalls
- Forcing 100% sampling for test traffic is usually necessary for reliable trace-presence assertions, but confirm your tracing backend actually supports a reliable per-request override; if it doesn't, trace-based assertions may need to be treated as best-effort/soft signals rather than hard pass/fail gates.
- Querying an aggregated metric over a short test-generated window can be noisy if the metric's collection interval is coarser than the test's own traffic burst; generate enough load (as in the p95 example, 30 requests rather than 1) to give the percentile calculation real statistical meaning.
- Asserting only on span PRESENCE (not absence of unexpected extra spans, or the correct PARENT-CHILD relationship between spans) can miss a regression where a hop runs at the wrong point in the call graph; where that distinction matters, assert on the trace's structure, not just a flat set of span names.
Design a comprehensive end-to-end testing strategy for a distributed message queue system that promises at-least-once delivery. Define test scenarios that validate duplicate deliveries, message loss under broker failure, consumer crash-and-restart, reordering, backpressure, visibility timeouts, and poison messages. Explain how you would simulate failures, generate deterministic test messages, assert that the application behaves correctly despite them, and collect observability metrics for verification.
Sample Answer
Direct answer
Design test scenarios around each named failure mode as its own explicit test (duplicate delivery, broker-failure message loss, consumer crash-and-restart mid-processing, reordering, backpressure, visibility-timeout expiry, and poison messages), simulate each with a fault-injecting test harness rather than hoping production traffic happens to exercise them, assert application-level correctness (idempotent processing, no lost or double-applied effects) rather than only "no exception was thrown," generate deterministic test messages so a found failure can be reproduced exactly, and back every assertion with the same observability metrics (consumer lag, redelivery counts, DLQ depth) a real on-call engineer would use to verify recovery in production.
Structured elaboration
At-least-once delivery means the QUEUE promises a message is delivered at least once, but says nothing about exactly once, or in order, across failures; the application has to supply the missing guarantees itself, and each of the following needs its own test:
-
Duplicate delivery. Deliver the same message twice (same message ID) and assert the consumer's effect is applied exactly once (an idempotency-key-based dedupe check, or an operation that is naturally idempotent).
-
Broker-failure message loss. Simulate the broker failing after accepting a message but before it is durably committed (if the broker's own contract allows this window) and assert the PRODUCER side has its own confirmation/retry logic, so message loss at this layer is bounded by the producer's own retry, not silently absorbed.
-
Consumer crash-and-restart. Kill the consumer mid-processing (after it read the message but before it acknowledged) and assert the message is redelivered (since it was never acked) and reprocessing it produces the correct final state, not a partial or corrupted one.
-
Reordering. Deliver messages for the same logical entity out of their production order and assert the consumer either has an ordering-independent design (commutative updates) or explicitly detects and correctly handles the out-of-order case (a version check that rejects an older update arriving late).
-
Backpressure. Flood the consumer faster than it can process and assert the system degrades gracefully (bounded queue growth, load shedding, or backpressure signaled to the producer) rather than an unbounded memory blow-up or a silent message drop.
-
Visibility timeout expiry. Hold a message past its visibility timeout without acking it and assert it becomes available for redelivery to another consumer, and that BOTH the original (now-late) processing and the redelivered processing converge to the same correct idempotent result if the original consumer eventually also finishes.
-
Poison messages. Deliver a message the consumer can never successfully process (malformed payload, a bug that always throws) and assert it is moved to a dead-letter queue after a bounded number of retries, rather than blocking the queue for every other message behind it forever.
-
Observability metrics as verification evidence, not just test assertions. Beyond the pass/fail test assertions above, instrument the harness itself to emit the same signals you would want in production: a consumer-lag gauge (how far behind the latest offset each consumer is), a redelivery counter (how many times a given message id was redelivered), and a DLQ-depth gauge. Assert on these directly where relevant (for example,
assert dlq_depth_metric.value() == 1after the poison-message scenario, orassert redelivery_count_metric.value(message_id="m1") == 1after the visibility-timeout scenario), so a test failure is corroborated by the same metrics an on-call engineer would look at in a real incident, and so a regression that silently stops emitting a metric (even while the underlying behavior is still correct) is itself caught.
Worked example
def test_poison_message_goes_to_dlq_without_blocking_the_queue():
dlq = []
dlq_depth_metric = Counter()
redelivery_count_metric = Counter()
queue = FakeAtLeastOnceQueue(max_retries=3, dead_letter_sink=lambda m: (dlq.append(m), dlq_depth_metric.inc()))
processed_good = []
def handler(message):
if message.body == "POISON":
raise ValueError("cannot process this payload, ever")
processed_good.append(message.body)
queue.enqueue(Message(id="m1", body="POISON"))
queue.enqueue(Message(id="m2", body="good-payload"))
queue.drain(handler)
assert [m.id for m in dlq] == ["m1"], "poison message should land in the DLQ after exhausting retries"
assert processed_good == ["good-payload"], "a poison message must not block processing of the message behind it"
assert dlq_depth_metric.value() == 1, "the DLQ-depth metric must reflect the one poisoned message, corroborating the test assertion with the same signal on-call would see"
def test_redelivery_after_visibility_timeout_is_idempotent():
store = IdempotentApplyStore()
redelivery_count_metric = Counter()
queue = FakeAtLeastOnceQueue(visibility_timeout_s=0.1, on_redeliver=lambda mid: redelivery_count_metric.inc(mid))
queue.enqueue(Message(id="m1", body={"op": "credit", "account": "a1", "amount": 10}))
first = queue.receive()
time.sleep(0.15)
second = queue.receive()
store.apply(second.body, idempotency_key=second.id)
store.apply(first.body, idempotency_key=first.id)
assert store.balance("a1") == 10, "redelivery due to visibility-timeout expiry must not double-credit"
assert redelivery_count_metric.value("m1") == 1, "the redelivery counter must show exactly one redelivery for m1, not zero (which would mean the scenario never actually fired) and not more than one"
Trade-offs and pitfalls
- Building a fake queue that faithfully reproduces visibility-timeout and redelivery semantics is itself nontrivial; where possible, run these tests against a real (local, disposable) instance of the actual message broker rather than a hand-rolled fake, to avoid the fake's own bugs masking or fabricating findings.
- Poison-message tests must assert BOTH halves: the poison message eventually stops retrying (lands in the DLQ), AND unrelated messages behind it are not blocked; a suite that only tests one half can pass while the other silently regresses.
- Testing reordering is easy to under-specify; be explicit about which entities' ordering matters (usually per-key, not global) and test out-of-order delivery specifically WITHIN one key's message stream, since that is the case a naive "just process messages as they arrive" consumer is most likely to get wrong.
- Asserting on a metric alongside a direct state assertion (as in the DLQ-depth and redelivery-count checks above) also catches a subtler regression: the underlying behavior staying correct while the metric silently stops being emitted, which would otherwise go unnoticed until an actual production incident where on-call has no signal to look at.
Unlock Full Question Bank
Get access to all 45 Distributed Systems and Microservices Testing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.