Kafka Streams Dead Letter Queues (KIP-1034) in Spring Boot 4: Poison-Pill Handling for Payment Pipelines Without Stalling the Topology
How to wire Kafka 4.2's native dead letter queue (KIP-1034, handleError() Response, errors.dead.letter.queue.topic.name) into a Spring Boot 4 Streams app: which payment errors resume, which fail, replayable DLQ records, metrics and tests.

The incident that changed how I build Streams apps was a silent one, not an outage. A payment-events topology had run for months with LogAndContinueExceptionHandler. On a Monday a partner switched a settlement amount field from an integer of minor units to a decimal string. Roughly 340 records over about 40 minutes failed deserialization. The handler wrote a WARN line for each and the topology kept going, so dashboards stayed green. We found out the next afternoon, around 30 hours later, when reconciliation showed 340 settlements with no matching event. By then the application logs had rotated, so there was no DLQ, no file and no copy of the payloads. We had to ask the partner to resend from their side.
After that I stopped treating error handling as an afterthought. Kafka 4.2 adds native dead letter queue support to Kafka Streams (KIP-1034), and for payment flows I now consider it part of the framework contract rather than something each team bolts on in business code. An app that treats a malformed record and a broker hiccup the same way will eventually lose money or stall, and the older handler API made that mistake very easy.
What changed between 4.1 and 4.2
Up to 4.1, the three exception handlers (deserialization, processing, production) returned a bare enum, CONTINUE or FAIL. If you wanted a DLQ you created your own KafkaProducer inside the handler, wrote to the topic, then returned CONTINUE. It works, but I was bitten three ways: the handler owned a second producer with its own lifecycle, the DLQ write had no relationship to the task's error semantics, and every team ended up with a slightly different copy.
In 4.2 the handler method is handleError() and it returns a Response. That is either Response.resume() or Response.fail(), and a resuming response can carry a list of ProducerRecord<byte[], byte[]> which Streams itself writes to the topic named in errors.dead.letter.queue.topic.name. There is one DLQ topic per application, and Streams does not create it for you. The old handle() variants are marked deprecated, so new code should implement handleError().
Everything below targets the 4.2 API as defined in KIP-1034. Two related proposals, routing records dropped inside the DSL to the DLQ and shipping a built-in production handler, were still being discussed when I wrote this, so do not assume they exist in your version. Compile against your own Streams jar and confirm the Response and ErrorHandlerContext signatures before copying anything.
Why a payments pipeline cannot just log and move on
In clickstream analytics, losing 0.01% of records is noise. In payments, each record is a money movement or the evidence of one, and an input I cannot account for leaves a hole in the audit trail. The rules that apply are concrete. PCI DSS Requirement 10 expects you to log and retain evidence of access and processing events, PSD2 and the national laws implementing it require payment service providers to keep transaction records and be able to reconstruct them, and RBI's payment-system directions in India require similar retention and traceability for transaction data. "It was logged and we continued" satisfies none of them once the log has rotated. My earlier PSD3 and PSR liability post covers the evidence side of that in more detail.
The opposite failure is just as real: stalling. If one malformed record crashes the app on every restart, that partition stays blocked, and a blocked payment partition is an incident too. So the useful question is not whether to dead-letter or fail. It is whether a given error belongs to the record or to the environment. A bad record goes to the DLQ. A sick environment should halt processing until it is healthy again.

The decision table I use in reviews
The Kafka docs describe the mechanism but not which errors deserve which outcome, so here is the table I bring to design reviews, grouped by handler and cause.
| Stage | Error | Decision | Reason |
|---|---|---|---|
| Deserialization | Malformed bytes, unknown schema id, bad enum | Resume + DLQ | Deterministic; retrying never helps |
| Deserialization | Schema registry unreachable | Fail | Environmental; record may be perfectly valid |
| Processing | Validation failure, IllegalArgumentException, mapping error | Resume + DLQ | Property of the record |
| Processing | State store I/O, TimeoutException, downstream REST call timeout | Fail | Transient; dead-lettering would drop good payments |
| Processing | NullPointerException from a missing optional field, in a mapper you have wrapped | Resume + DLQ only if converted to PaymentValidationException | The record is at fault, but only your code knows that |
| Processing | Bare NullPointerException or any unclassified exception | Fail, with a counter | Could be a deploy defect hitting every record |
| Production | RecordTooLargeException, serialization failure | Resume + DLQ | Deterministic for this record |
| Production | Broker unavailable, NotEnoughReplicasException, timeouts | Fail | Environmental |
The NullPointerException rows deserve explanation. A null in a malformed payload really is a record-level problem, but from the stack alone a handler cannot distinguish it from a defect in the code you just shipped. The way out is to validate at the edge: mappers check required fields and throw PaymentValidationException, which is dead-lettered. Anything that still surfaces as a raw NPE means the code is wrong, so it fails the task.
I considered dead-lettering unknown exceptions by default and rejected it, because a bad deploy would then push your whole stream into the DLQ at full speed while every dashboard stays quiet. Only exceptions I have deliberately listed as record-level get dead-lettered. Everything else fails.
Wiring it into Spring Boot 4
The handler classes and the DLQ topic are ordinary Streams properties, so they go under spring.kafka.streams.properties and Spring hands them to StreamsConfig untouched:
spring:
kafka:
streams:
application-id: payments-enrichment-v3
bootstrap-servers: ${KAFKA_BOOTSTRAP}
properties:
errors.dead.letter.queue.topic.name: payments-enrichment-v3.dlq
deserialization.exception.handler: com.krishnakky.streams.dlq.PaymentDeserializationHandler
processing.exception.handler: com.krishnakky.streams.dlq.PaymentProcessingHandler
production.exception.handler: com.krishnakky.streams.dlq.PaymentProductionHandler
processing.guarantee: exactly_once_v2
A common surprise for Spring developers: you give Kafka a class name, and Kafka creates the object with reflection and calls configure() on it. Spring never sees these instances, so @Autowired and constructor injection silently do nothing. Rather than work around that, I keep the handlers small, stateless and Spring-free, and put the decision logic in a plain ErrorClassifier class. Metrics are the one place that needs a bridge, which I show in the metrics section with a static registry holder filled in at startup.
This is also where the approach diverges from the Spring Cloud Stream Kafka Streams binder. The binder's sendToDlq deserialization handler reuses the source record's partition number, so the DLQ needs at least as many partitions as the source, and it only covers deserialization. The native path covers all three error stages, keeps one topic per application, and lets Streams decide partitioning of the DLQ record. If you are already on the binder, it keeps working; I would not start a new service on it.
Provision the DLQ topic yourself, with a longer retention than the source. For payments I use 14 to 30 days, because the humans who repair these records work on business time, not broker time:
@Bean
NewTopic paymentsDlq() {
return TopicBuilder.name("payments-enrichment-v3.dlq")
.partitions(6)
.replicas(3)
.config(TopicConfig.RETENTION_MS_CONFIG, String.valueOf(Duration.ofDays(21).toMillis()))
.config(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "2")
.build();
}
The classifier: one place for the resume-or-fail rule
Keeping the decision in one class means the three handlers cannot drift apart, and the table above becomes testable code.
public final class ErrorClassifier {
public enum Verdict { DEAD_LETTER, FAIL }
public static Verdict classify(Throwable t) {
Throwable root = rootCause(t);
if (root instanceof org.apache.kafka.common.errors.TimeoutException
|| root instanceof org.apache.kafka.common.errors.RetriableException
|| root instanceof java.net.ConnectException
|| root instanceof java.net.SocketTimeoutException
|| root instanceof org.apache.kafka.streams.errors.InvalidStateStoreException) {
return Verdict.FAIL;
}
if (root instanceof org.apache.kafka.common.errors.SerializationException
|| root instanceof org.apache.kafka.common.errors.RecordTooLargeException
|| root instanceof PaymentValidationException
|| root instanceof IllegalArgumentException) {
return Verdict.DEAD_LETTER;
}
return Verdict.FAIL; // unknown means loud
}
private static Throwable rootCause(Throwable t) {
Throwable cur = t;
while (cur.getCause() != null && cur.getCause() != cur) cur = cur.getCause();
return cur;
}
}
The order matters. Transient checks run first, because a SerializationException wrapping a schema registry timeout is environmental, and the root cause tells you that.
Preserving raw bytes and metadata so replay is possible
A DLQ you cannot replay from is a graveyard. The rule I follow: store the original bytes untouched in the value, and push everything else into headers. Parsing a failed payload to "improve" it in the DLQ destroys the evidence and, worse, can fail again. This is the same discipline I applied to idempotency in the transactional outbox and idempotent consumers post: keep the original, make the replay safe.
Here is the deserialization handler. The processing and production ones differ only in the record type in the signature and where the bytes come from:
public class PaymentDeserializationHandler implements DeserializationExceptionHandler {
private String applicationId;
@Override
public void configure(Map<String, ?> configs) {
this.applicationId = String.valueOf(configs.get(StreamsConfig.APPLICATION_ID_CONFIG));
}
@Override
public Response handleError(ErrorHandlerContext ctx,
ConsumerRecord<byte[], byte[]> record,
Exception exception) {
DlqMetrics.record("deserialization", exception);
if (ErrorClassifier.classify(exception) == ErrorClassifier.Verdict.FAIL) {
return Response.fail();
}
ProducerRecord<byte[], byte[]> dlq = new ProducerRecord<>(
null, null, record.key(), record.value()); // raw bytes, untouched
add(dlq, "dlq.source.topic", ctx.topic());
add(dlq, "dlq.source.partition", String.valueOf(ctx.partition()));
add(dlq, "dlq.source.offset", String.valueOf(ctx.offset()));
add(dlq, "dlq.stage", "deserialization");
add(dlq, "dlq.exception.class", exception.getClass().getName());
add(dlq, "dlq.exception.message", truncate(exception.getMessage(), 512));
add(dlq, "dlq.application.id", applicationId);
add(dlq, "dlq.failed.at", Instant.now().toString());
record.headers().forEach(h -> dlq.headers().add("orig." + h.key(), h.value()));
return Response.resume(List.of(dlq));
}
private static void add(ProducerRecord<byte[], byte[]> r, String k, String v) {
r.headers().add(k, v == null ? new byte[0] : v.getBytes(StandardCharsets.UTF_8));
}
private static String truncate(String s, int max) {
return s == null ? null : s.length() <= max ? s : s.substring(0, max);
}
}
Three details here come from real mistakes. First, I truncate exception messages, because stack-trace-sized headers have hit max.request.size and turned a poison pill into a poison DLQ write. Second, I prefix original headers with orig. so trace context and idempotency keys survive but cannot collide with my own. Third, I never put customer data, such as account numbers, into exception messages. The DLQ is a data store with its own access controls, retention and, in the EU, its own GDPR scope.
For processing errors, the raw bytes are not what you consumed, because the record has already been deserialized. ErrorHandlerContext exposes the raw source key and value for the record that triggered the failure, and that is what I store, so a replay re-enters the topology at the very start, exactly as the original did. For production errors, the failing record is the output one, so I tag the stage accordingly and keep the source coordinates from the context to trace it back.
Card and account data in the DLQ
Dead-lettering a raw payment record copies whatever was in it, possibly a PAN, IBAN, VPA or name, into another topic. That topic often gets different ACLs and a much longer retention than the source, which is exactly how a PCI DSS scope problem appears. Three controls I apply:
- Same or tighter ACLs. Only the replay service principal can read the DLQ, and only the application principal can write to it. Developers do not get read access by default.
- Encrypt the value. If the source topic carries cardholder data, encrypt the DLQ payload at the application layer or use field-level encryption, so a 21-day retention does not mean 21 days of plaintext PANs. Under PCI DSS, stored PANs must be rendered unreadable, and a DLQ counts as storage.
- Retention matches the data class. Pick the shortest retention that still fits the repair workflow, and delete or expire repaired entries instead of keeping them. For EU data subjects this is also a GDPR storage-limitation question.
Headers must never carry payload fragments. Exception messages from parsers often quote the offending value, which is why the handler below truncates them, and in regulated flows I also strip the message entirely and keep only the exception class.
Guarding against a DLQ flood
Classification handles bad records, but a bad deploy can still make every record look bad if your whitelist includes a broad type like IllegalArgumentException. Add a rate-based circuit breaker. The handler keeps a sliding count of dead-lettered records per minute, and if the dead-letter ratio crosses a threshold, say more than 5% of consumed records over two minutes with a floor of 50 records so a quiet topic does not trip it, it returns Response.fail() instead of resume. The app stops, the consumer group stops advancing, and nothing more is lost. That feels extreme, but a stopped payment pipeline with an intact source topic is recoverable, while a DLQ holding hundreds of thousands of valid records is a much larger repair job.
The replay and repair consumer
Replay is where DLQs usually die. My pattern is deliberately boring, and deliberately not automated. An LLM that "repairs" payment payloads is guessing at money, which is why I do not use that approach for replay on this kind of data.
The replay service is a separate Spring Boot application, not a part of the topology. It does three things: lists DLQ records grouped by stage and exception class, lets an operator choose a fix (patch a field, correct a schema version, or discard with a recorded reason), and republishes to the original source topic.
@Service
class DlqReplayService {
private final KafkaTemplate<byte[], byte[]> template;
private final ReplayAuditRepository audit;
@Transactional
public void replay(ConsumerRecord<byte[], byte[]> dlq, byte[] repairedValue, String operator) {
String topic = header(dlq, "dlq.source.topic");
String origKey = header(dlq, "dlq.source.partition") + ":" + header(dlq, "dlq.source.offset");
if (audit.alreadyReplayed(topic, origKey)) return; // idempotent
ProducerRecord<byte[], byte[]> out = new ProducerRecord<>(
topic, null, dlq.key(), repairedValue);
out.headers().add("replayed.by", operator.getBytes(StandardCharsets.UTF_8));
out.headers().add("replayed.from", origKey.getBytes(StandardCharsets.UTF_8));
template.send(out);
audit.record(topic, origKey, operator, Instant.now());
}
}
Idempotency is the non-negotiable part. The pair of source partition and offset is a natural dedupe key, so a double click or a retried batch cannot pay twice. The downstream topology should also dedupe on the business idempotency key, the same as it would for any at-least-once input. I keep the audit table because "who changed this payment record and why" is a question I have had to answer in review.
Metrics and alerting
A DLQ that nobody watches is LogAndContinue with extra steps. I count at the handler, tagged by stage and exception class, and alert on rate, not on absolute value, because one bad record is routine and three hundred in a minute is a defect.
Since handlers are not Spring beans, I give them a tiny static bridge that the configuration fills in at startup:
public final class DlqMetrics {
private static volatile MeterRegistry registry = new SimpleMeterRegistry();
public static void bind(MeterRegistry r) { registry = r; }
static void record(String stage, Throwable t) {
registry.counter("streams.dlq.records",
"stage", stage,
"exception", t.getClass().getSimpleName(),
"verdict", ErrorClassifier.classify(t).name().toLowerCase())
.increment();
}
}
@Configuration
class StreamsMetricsConfig {
StreamsMetricsConfig(MeterRegistry registry) { DlqMetrics.bind(registry); }
}
Keep the exception tag low-cardinality: simple class names, never messages. The alerts I run in Prometheus:
- Rate alert:
rate(streams_dlq_records_total[5m])above a per-stage baseline, paging when it is both high and sustained. - Fail-verdict alert: any increment of
verdict="fail", since it means the app is about to stop on an unclassified error. - Age alert: the oldest unreplayed DLQ record older than your business SLA, using consumer lag on the replay group or a gauge of oldest-header timestamp.
For tracing, I carry the original traceparent header across (that orig. prefix again) so an OpenTelemetry trace from the replay links back to the failed attempt. The setup follows what I wrote in distributed tracing with OpenTelemetry in Spring Boot. Put the DLQ count and the replay-lag gauge on the same dashboard as consumer lag, because they are the same story told at different moments.
Testing: fast with TopologyTestDriver, honest with Testcontainers
Both layers earn their keep, and they catch different things.
TopologyTestDriver runs the topology in-process with no broker. It is where I verify the classifier decisions end to end: feed a malformed record, assert the output topic is empty and that the DLQ topic holds the original bytes with the right headers. Be careful about one limit: the driver exercises your topology and handler wiring, but check that the version you test against actually applies the DLQ config in the driver. If a handler is not honored there, test the handler class directly with a mocked ErrorHandlerContext and keep the end-to-end DLQ assertion for the container test.
@Test
void malformedRecordIsDeadLetteredWithRawBytes() {
byte[] garbage = new byte[] {0x00, 0x7F, 0x13};
input.pipeInput(new TestRecord<>("k".getBytes(), garbage));
assertThat(output.isEmpty()).isTrue();
TestRecord<byte[], byte[]> dlq = dlqTopic.readRecord();
assertThat(dlq.value()).isEqualTo(garbage);
assertThat(new String(dlq.headers().lastHeader("dlq.stage").value())).isEqualTo("deserialization");
}
@Test
void timeoutFailsTheTaskInsteadOfDeadLettering() {
assertThat(ErrorClassifier.classify(new TimeoutException("broker")))
.isEqualTo(ErrorClassifier.Verdict.FAIL);
}
Testcontainers with a real Kafka 4.2 broker is where I prove the things a driver cannot: that the DLQ topic exists and is writable, that headers survive real serialization, that exactly_once_v2 plus a resuming response does not duplicate DLQ records after a task restart, and that a stopped broker produces a failing app rather than a flood in the DLQ. That last test is the one that justified the whole setup for me. I pause the broker container mid-stream, assert the DLQ stays empty, restart it, and assert the pipeline resumes with zero loss.
Add one regression test that replays a DLQ record through your replay service and asserts a second replay is a no-op. It takes ten minutes and prevents a double-payment class of bug.
What I would do differently if starting today
Start with the decision table, before any code. Agree it with whoever owns reconciliation, since they are the ones who will live with the DLQ. Write the classifier, get the tests green, then wire the handlers. Provision the DLQ topic with generous retention and tight access control. Ship the replay service in the same release as the DLQ, never later, because the first poison pill always arrives within a week of go-live.
I have spent nine years building pipelines where silent loss is the expensive failure. If you are carrying a LogAndContinue handler in a payments topology right now, you can find my background on the experience section or reach out through contact if you want a second pair of eyes on your classification table.
Related Articles
- Transactional Outbox and Idempotent Consumers in Spring Boot Payment Systems
- Kafka Share Groups (Queues for Kafka) in Spring Boot Payment Pipelines
- Distributed Tracing with OpenTelemetry in Spring Boot: Production Guide
Today, open your Streams config, search for LogAndContinueExceptionHandler, and replace it with a classifier-backed handleError() handler plus a provisioned errors.dead.letter.queue.topic.name topic on your next release branch.