# How to Test Kafka Applications: Six Approaches

A Kafka application can pass every test in its build and still lose or duplicate records in production. Each test replaced part of Kafka with something that always behaves, and the failure came from the part that was replaced.

Take a producer that sends a record while its broker is paused. A mock reports success at once. A real paused broker makes the send fail with a timeout.

The record is in the topic anyway once the broker resumes, so an application that retries on that error writes it twice.

Every way of testing Kafka code makes this trade: a list in memory, a simulated runtime, one broker on a network that never drops. The replacement makes the test fast and repeatable, and it hides every failure that only the replaced part produces.

Each bracket spans the parts of the path that are real in that kind of test.

A test suite covers Kafka when every part a record passes through is real in at least one test, and the network and broker fail in at least one. Six steps build that suite:

1. Unit-test with `MockProducer`.
2. Test topologies with `TopologyTestDriver`.
3. Run a real broker with Testcontainers.
4. Pause the broker to test timeouts.
5. Check schema compatibility in CI.
6. Replay production records.

Timings were measured on a laptop running Docker:

| Approach | What runs for real | What it catches | Time per run |
|---|---|---|---|
| `MockProducer` and `MockConsumer` | Your logic and serializers | Wrong topic or key, a failed send your code mishandles | Under 0.1 s |
| `TopologyTestDriver` | Your Kafka Streams topology | Wrong filter or aggregation | 41 ms |
| A real broker: `@EmbeddedKafka` or Testcontainers | A broker inside the test JVM, or the broker version you deploy in Docker | Client configuration, a real produce and consume | 2.6 s embedded (broker up in 0.6 s); about 3 s in Docker, container start included |
| Fault injection | The failures you choose: pause, delay, error | Timeout, retry and duplicate handling | 5 s per timeout tested |
| Schema compatibility checks | Schema versions in Schema Registry | Incompatible schema changes, before deploy | One registry call |
| Production records | Record shapes from the real topic | Payloads your fixtures never had | Depends on the sample |

None of the six measures throughput, consumer lag under load or quota behavior on your cluster. That takes a load test on an environment sized like production.

## Unit-Test With `MockProducer`

Take `geo_events`, a topic for location events from IoT devices, and the code that publishes to it.

`kafka-clients` ships `MockProducer` and `MockConsumer`, in-memory stand-ins for the real clients. A producer test checks what your code sends by reading the records back from a list:

```java
var producer = new MockProducer<>(true, null, new StringSerializer(), new StringSerializer());

GeoEvents.publish(producer, "1234-e4b6-5678", EVENT).get();

assertThat(producer.history()).singleElement().satisfies(r -> {
    assertThat(r.topic()).isEqualTo("geo_events");
    assertThat(r.key()).isEqualTo("1234-e4b6-5678");
});
```

The first constructor argument, `autoComplete`, makes every `send()` succeed at once. Turn it off and the test decides each outcome: `errorNext(new TimeoutException(...))` fails the oldest pending send. `MockConsumer` takes records through `addRecord` and throws from `poll()` after `setPollException`.

Use mocks for logic: which topic and key a record gets, and what your error handler does with a failed send. The failure the handler receives is the one the test wrote, so a mock can't show which failures happen or when.

## Test Topologies With `TopologyTestDriver`

For [Kafka Streams](https://www.conduktor.io/glossary/introduction-to-kafka-streams), the `kafka-streams-test-utils` artifact provides the `TopologyTestDriver`, which runs a topology with no broker at all:

> *"You can use the test driver to verify that your specified processor topology computes the correct result with the manually piped in data records."*
> — [Apache Kafka documentation, Testing a Streams Application](https://kafka.apache.org/documentation/streams/developer-guide/testing/)

Say the topology filters `geo_events` down to device `1234-e4b6-5678` and writes the result to `geo_events_tracked`. The test pipes in one event from that device and one from another, and expects only the first:

```java
var strings = Serdes.String();
try (var driver = new TopologyTestDriver(GeoEvents.filterStream(), config)) {
    var in = driver.createInputTopic("geo_events", strings.serializer(), strings.serializer());
    var out = driver.createOutputTopic("geo_events_tracked", strings.deserializer(), strings.deserializer());

    in.pipeInput(null, tracked);  // deviceId 1234-e4b6-5678
    in.pipeInput(null, other);    // deviceId 9876-e1p3-6763

    assertThat(out.readValuesToList()).containsExactly(tracked);
}
```

It ran in 41 ms. The driver differs from a running Streams application in two ways ([`TopologyTestDriver` Javadoc](https://kafka.apache.org/44/javadoc/org/apache/kafka/streams/TopologyTestDriver.html)):

- **Synchronous processing.** It commits after each record, so `commit.interval.ms` and the record cache have no effect.
- **One partition per input topic.** Records from two partitions never interleave.

An aggregation that emits one update per record in the test can emit fewer in production, where the [record cache](https://kafka.apache.org/44/streams/developer-guide/memory-mgmt/) compacts updates to the same key before forwarding them.

## Run a Real Broker With Testcontainers

Client configuration and [consumer group](https://www.conduktor.io/glossary/kafka-consumer-groups-explained) behavior need a running broker, inside the test JVM or in Docker. A round trip with the Kafka CLI shows that a cluster accepts and returns records. Here `geo_events` gets three partitions on Kafka 4.4.0 ([running Kafka locally](https://www.conduktor.io/kafka/starting-kafka)):

```bash
$ kafka-topics.sh --bootstrap-server localhost:9092 --topic geo_events \
    --create --partitions 3 --replication-factor 1
Created topic geo_events.
$ echo '{"timestamp":"1647515491","deviceId":"1234-e4b6-5678","latLong":"38.8951,-77.0364"}' \
    | kafka-console-producer.sh --bootstrap-server localhost:9092 --topic geo_events
$ kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic geo_events \
    --from-beginning --max-messages 1 \
    --formatter-property print.partition=true --formatter-property print.offset=true
Partition:2	Offset:0	{"timestamp":"1647515491","deviceId":"1234-e4b6-5678","latLong":"38.8951,-77.0364"}
Processed a total of 1 messages
```

The round trip is the right check for a new cluster and a useless test. Nothing asserts on the output, and nothing runs it again when the producer code changes.

Spring's [`@EmbeddedKafka`](https://docs.spring.io/spring-kafka/reference/testing.html) starts a broker in the JVM from Kafka's own server jars: called from a plain JUnit test, `EmbeddedKafkaKraftBroker` was up in 619 ms.

The broker shares your test's JVM and classpath, and its version is the one your test library pins: `spring-kafka-test` 4.1.2 brings Kafka 4.2.2, two releases behind the current 4.4.0.

[Testcontainers](https://github.com/testcontainers/testcontainers-java) starts the broker image you choose in Docker and removes it when the tests finish, with versions for [Python](https://github.com/testcontainers/testcontainers-python) and [Go](https://github.com/testcontainers/testcontainers-go). With Testcontainers 2.0.5 and `apache/kafka:4.4.0`, this test took about 3 s, container start included:

```java
@Container
static KafkaContainer kafka = new KafkaContainer("apache/kafka:4.4.0");

@Test
void producedEventIsConsumed() throws Exception {
    // producer and consumer built on kafka.getBootstrapServers()
    GeoEvents.publish(producer, "1234-e4b6-5678", EVENT).get();

    consumer.subscribe(List.of("geo_events"));
    List<ConsumerRecord<String, String>> received = new ArrayList<>();
    Instant deadline = Instant.now().plusSeconds(15);
    while (received.isEmpty() && Instant.now().isBefore(deadline)) {
        consumer.poll(Duration.ofMillis(200)).forEach(received::add);
    }
    assertThat(received).singleElement()
        .satisfies(r -> assertThat(r.value()).isEqualTo(EVENT));
}
```

`KafkaContainer` from `org.testcontainers.kafka` runs `apache/kafka` images; the [older class](https://java.testcontainers.org/modules/kafka/) in `org.testcontainers.containers` is deprecated. Tests in a class share a static container and its topics: when another test wrote to `geo_events` first, this one received three records instead of one. Give each test its own topic.

Both start one healthy broker by default. With a single replica, `acks=all` and [`min.insync.replicas`](https://www.conduktor.io/glossary/kafka-replication-and-high-availability) have nothing to wait for, and no leader election happens.

## Pause the Broker to Test Timeouts

A broker in a container stays up for the whole run, so your producer's timeout handling never runs. The simplest fault injection pauses the container in the middle of a test, here with `delivery.timeout.ms=5000` and `request.timeout.ms=3000`:

```java
var docker = kafka.getDockerClient();
producer.send(new ProducerRecord<>(topic, "d1", "before-pause")).get();

docker.pauseContainerCmd(kafka.getContainerId()).exec();
var sent = producer.send(new ProducerRecord<>(topic, "d1", "during-pause"));
assertThatThrownBy(sent::get).hasCauseInstanceOf(TimeoutException.class);
docker.unpauseContainerCmd(kafka.getContainerId()).exec();
```

The send failed, and a consumer that read the topic afterwards found both records. Each of eight runs printed the same result:

```
org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for geo_events_pause_1-0:5000 ms has passed since batch creation. The request has not been sent, or no server response has been received yet.
run 1: send() failed after 5020 ms; topic holds [0:before-pause, 1:during-pause]
```

Here the request had reached the broker, which appended the record once it resumed:

The producer reports a failure at 5,000 ms. The broker appends the record when it resumes.

A `TimeoutException` means the outcome is unknown, so an application that resends on timeout can write the event twice.

The [idempotent producer](https://www.conduktor.io/glossary/exactly-once-semantics-in-kafka), on by default in current clients, removes duplicates from its own retries, but a record your code sends again is new to it. With default settings, a send times out after two minutes, because `delivery.timeout.ms` defaults to 120,000 ms.

A paused container covers an unreachable broker, and says nothing about a slow disk on one follower. Other faults need other tools:

- **Latency and dropped connections.** [Toxiproxy](https://github.com/Shopify/toxiproxy) adds both between client and broker, and has a [Testcontainers module](https://java.testcontainers.org/modules/toxiproxy/).
- **Kafka-level errors.** A moving partition leader or a corrupted record needs a proxy that speaks the Kafka protocol. [Conduktor Gateway](https://www.conduktor.io/gateway) is a Kafka proxy that can inject them.

## Check Schema Compatibility in CI

A contract test checks a schema change against the versions already registered, before a producer ships it. Confluent [Schema Registry](https://www.conduktor.io/glossary/schema-registry-and-schema-management) answers over REST. Say version 2 of the `geo_events` value schema adds a required `accuracyMeters` field:

```bash
$ curl -s -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
    --data @geo-event-v2.json \
    "$REGISTRY/compatibility/subjects/geo_events-value/versions/latest?verbose=true" \
    | jq -r '.is_compatible, .messages[0]'
false
{errorType:"READER_FIELD_MISSING_DEFAULT_VALUE", description:"The field 'accuracyMeters' at path '/fields/3' in the new schema has no default value and is missing in the old schema", additionalInfo:"accuracyMeters"}
```

Under `BACKWARD`, the registry's default, consumers on the new schema must read records written with the old one, and old records have no value for a field without a default. With a `null` default, the same call on Schema Registry 8.4.0 returned `{"is_compatible":true,"messages":[]}`.

Run the call in CI on every schema change, or use the `test-compatibility` goal of the [Maven plugin](https://docs.confluent.io/platform/current/schema-registry/develop/maven-plugin.html), so an incompatible schema fails the build.

The registry compares types, so a change in meaning passes: writing `latLong` as longitude first keeps the type `string`.

## Replay Production Records

Fixtures hold the records a developer thought of. A topic holds what producers wrote: every schema version still within retention, tombstones on [compacted topics](https://www.conduktor.io/glossary/kafka-log-compaction-explained), empty fields, records from producers your team doesn't own.

Export a sample from the topic, mask the personal fields, and replay it through your deserializer and topology in a `TopologyTestDriver` or consumer test. The sample covers only the cases it happened to contain.

When production data can't leave production, generate records from the registered schema, which gives the shape without the values.

## Test With Console and Gateway

[Conduktor Console](https://www.conduktor.io/console) covers the manual checks. Its producer generates records from a topic's registered schema, in flow mode at a set interval, and the topic view filters what comes back.

For fault injection with real clients, [Gateway](https://www.conduktor.io/gateway) has eight chaos interceptors ([chaos testing guide](https://docs.conduktor.io/guide/use-cases/chaos-testing)), among them:

- **Broken brokers.** `SimulateBrokenBrokersPlugin`, with `rateInPercent` and an `errorMap` of errors per request type.
- **Other failures.** Leader election errors, slow brokers, message corruption, duplicate messages and invalid schema IDs.

The Console producer in flow mode, generating a record from the topic's schema every second.

The topic view in Console filtering consumed records by value.

## Prepare Test Evidence for DORA

Every Kafka test replaces part of Kafka, and the part it replaces is the part it can't test. A send that timed out and still landed in the topic shows up only in a test where the broker is real and then fails.

Auditors in finance will ask for that kind of test. DORA requires most EU financial entities to test the systems behind their critical or important functions at least once a year.

Its [Article 25](https://eur-lex.europa.eu/eli/reg/2022/2554/oj) names scenario-based, compatibility, performance and end-to-end testing. When one of those systems runs on Kafka, a suite that never fails the broker has no failure scenario to show auditors.

[Get started with Console and Gateway →](https://www.conduktor.io/get-started?src=blog-testing-your-apache-kafka-data-with-confidence-2023)

---

Related: [Chaos Engineering for Kafka →](https://www.conduktor.io/blog/chaos-engineering-for-kafka-testing-recovery-before-you-need-it) · [Testcontainers, Embedded Kafka and Mocks →](https://www.conduktor.io/blog/testing-kafka-testcontainers-embedded-mocks) · [Kafka Data Contracts →](https://www.conduktor.io/blog/kafka-data-contracts)
