Following a test through Kafka: coverage for producers and consumers
By Melih Sakarya · Published · 5 min read

Short answer
A test publishes an order; a consumer in another service handles the event a moment later, on another thread. Here is how CoverOps files the consumer's code under the test that produced the record, what the Java agent does without code, what needs a few lines, and where the trail stops.
Short answer: to know which test ran a Kafka consumer's code, the test's identity has to travel inside the record. CoverOps does this with record headers. With tracing on, the Java agent writes the test context and the chain header on every KafkaProducer.send, and on the consuming side runs each record of a poll, and each Spring Kafka record listener call, under the test that produced it. No code is needed for those. Batch listeners and work handed to another thread take a few lines; the other runtimes carry message context by hand.
Why Kafka breaks per-test coverage
An HTTP call is easy to follow: the caller waits, the callee runs on a thread that holds the request, and the answer comes back on the same connection. A Kafka hop has none of that:
- Time. The test gets its 201 and moves on. The consumer may handle the event a moment later, after the next test has started, or after the suite is done.
- Threads. The consumer runs on its own poll loop, not on a thread that ever saw the test's request.
- Batches. One poll returns many records, possibly produced by different tests.
Without context in the record, the consumer's coverage is real but anonymous: it shows up in the service's total and under no test. In a per-service report, a consumer that only some other test ever triggered looks exactly like one your test triggered.
What the record carries
The test context crosses services as headers. On HTTP those are request headers; on Kafka they are record headers with the same names:
X-CoverageOps-Trace: <trace key>-<hop>
X-CoverageOps-Test: checkout%3A%3Abuys%20a%20desk
X-CoverageOps-Test-Id: AUT-45
X-CoverageOps-Run: gh-9812
The consumer that reads them continues the producer's trace as the next hop, and files the code its handler runs under that test, in that run.
What the Java agent does without code
Start the services with trace=true (COVERAGEOPS_TRACE=true). Propagation is on whenever tracing is, and per-test attribution on the JVM needs tracing anyway.
- Producing:
KafkaProducer.sendwrites the record headers. Headers are replaced, never added, so a record sent twice does not carry two sets. A record that was sent before has read-only headers; the agent sends an annotated copy instead. - Consuming with a poll loop: each record of a
pollis handled in its own context while the loop body runs. The nextpollends the last record's context. - Consuming with Spring Kafka: record listeners run in the record's context for exactly as long as they run.
- Inside a request: a thread already handling a request keeps it, so a record read in the middle of an HTTP call belongs to that call.
A consumed record is adopted the way an inbound request is: the consumer shows up as the next hop of the producer's chain on the service map, and in the test's flow on the run page.

What needs a few lines
The Java agent does not follow these on its own: Kafka batch listeners, work handed to another thread (@Async, an executor, CompletableFuture), and clients outside the list above. For a batch listener, adopt each record's headers around its handling:
import io.coverageops.agent.api.Trace;
@KafkaListener(topics = "orders", batch = "true")
public void onOrders(List<ConsumerRecord<String, String>> records) {
for (ConsumerRecord<String, String> record : records) {
Map<String, byte[]> headers = new HashMap<>();
for (Header h : record.headers()) headers.put(h.key(), h.value());
Trace.adoptMessage(headers, "consume orders");
try {
handle(record);
} finally {
Trace.endMessage();
}
}
}
adoptMessage matches header names without regard to case and accepts values as strings or UTF-8 bytes. On the producing side of a client the agent does not know, Trace.outboundHeaders() returns every header to put on the record. Trace is loaded by the bootstrap classloader, so compile against the agent with provided scope.
Producers and consumers in other languages
- Ruby: the agent writes the headers automatically on ruby-kafka and rdkafka producers (so WaterDrop and Karafka). A consumer adopts them with
CoverageOps.with_context(message.headers, label: "orders.created") { … }. - Node.js, Go, Python, .NET and PHP: message hops are by hand. On the producing side, put the agent's outbound headers on the record yourself.
# Python producer (confluent-kafka)
from coverageops_agent.agent import current_tracer
headers = current_tracer().outbound_headers() # {} when nothing is traced
producer.produce("orders", value=payload, headers=list(headers.items()))
Mixed stacks work in your favour here: a record produced this way by a Python service and consumed by a JVM service is adopted by the Java agent automatically, because it reads the same headers whoever wrote them.
Late consumers and the run window
A record carries the run it belongs to, but traffic cannot open or reopen runs. A run named by traffic is honoured while it is open, or for 10 minutes after it finished, for stragglers an agent flushes after the runner said it was done. A consumer that lags a little still lands in the right run; one that handles the record later than that files its work in the agent's own run instead.
What you see
- The test's flow on the run page lists the consumer as a hop after the producer, with its service, duration and line count.
- The live trace feed shows the consumer's hop as it is reported, while the run is still going.
- The service map draws an edge from the producing service to the consuming one. A consumer that should be there but has no edge is a hop that lost its context.
- The consumer's files on the run page list, under Tests that touched this file, the tests whose records it handled.
- Test selection and impact see that a change in the consumer's handler is exercised by the test that produced its records.

A checklist for the first run
- Producer and consumer services both run an agent, with tracing on, and the same run key.
- The test labels its first request (the runner integrations do this).
- Open one test's flow and confirm the consumer hop is there.
- Check the service map for the producer-to-consumer edge.
- For batch listeners or thread hand-offs, add
adoptMessageand check again.
Limits to know
- The broker is not measured, only code in a process with an agent.
- Brokers older than 0.11 have no record headers; nothing is added there.
- Batch listeners and work handed to another thread need the lines above.
- Records handled more than 10 minutes after the run finished do not land in it.
- Consumers in one JVM that handle records of overlapping tests share a coverage window: each test keeps all of its lines and the overlap is recorded. The hops themselves stay exact.
This post is part of the functional test coverage in distributed systems series. For RabbitMQ and other queues, see keeping test context across async hops; for the map, a service map built from test traffic. The concepts guide has the propagation table, and the integration test coverage page has the product summary.
Related posts
- Parallel functional tests and per-test coverage: what stays exact, what is shared
Functional suites run in parallel to fit into CI, and every parallel test hits the same long-running services. Line counters cannot say which of two simultaneous requests ran a line. Here is what CoverOps keeps exact anyway, what it shares and labels, how each agent draws the line, and how to keep the shared part small.
- Paralel fonksiyonel testlerde test bazında coverage: ne kesin kalır, ne paylaşılır
Fonksiyonel suite'ler CI süresine sığmak için paralel koşar ve her paralel test aynı uzun ömürlü servislere gider. Satır sayaçları, aynı anda gelen iki istekten hangisinin bir satırı çalıştırdığını söyleyemez. CoverOps'un yine de neyi kesin tuttuğunu, neyi paylaştırıp işaretlediğini, her agent'ın sınırı nasıl çizdiğini ve paylaşılan kısmı nasıl küçük tutacağınızı anlatıyoruz.
- Changed-code coverage as a merge gate when a change spans services
Diff coverage from one repository's unit tests cannot see that the new lines in the inventory consumer only run when an end-to-end test places an order. Here is how to gate a merge on the changed lines your functional tests actually ran, in every service, and how to keep a service that did not run from quietly passing the gate.