We are asked: "Design a streaming dead-letter compaction system: duplicate suppression, tracing, and replay windows."
We need to design a system that handles dead letters in a streaming context. Dead letters refer to messages that could not be processed successfully. In streaming systems (like Kafka, Pulsar, Kinesis), we have consumers that process messages. If processing fails (due to transient errors, malformed data, etc.), the message might be sent to a dead-letter queue (DLQ). However, we want a "dead-letter compaction system" with features: duplicate suppression, tracing, and replay windows.
Interpretation: We need to design a system that takes dead-letter messages from various sources (stream processing pipelines), compacts them (maybe to reduce storage, deduplicate), while preserving ability to trace the origin and context of the dead-letter, and to replay them within a certain window (maybe for reprocessing after fix). The system should handle duplicates (multiple occurrences of same failed message or similar), maintain traceability (link to original message, processing attempt metadata), and support replay (reprocessing of dead-letter messages within a configurable time window, maybe automatic after delay, or manual).
We need to design the architecture, components, data model, APIs, and considerations.
Let's break down requirements:
Dead-letter ingestion: Accept dead-letter messages from various streaming consumers. Each dead-letter message should include original message content, metadata (source topic/partition, offset, timestamp, processing error, stack trace, etc.), and perhaps a unique identifier for dedup.
Duplicate suppression: Many messages may end up in DLQ multiple times (if retried and failed each time, or from multiple consumers). We want to avoid storing duplicate dead-letter entries. Duplicate detection could be based on a deduplication key (e.g., original message ID, topic+partition+offset, or a hash of content+error?). We need to decide. Also need to handle exactly-once semantics? Might be at-least-once ingestion. System should de-duplicate on write and also handle idempotent reads? But focus on compaction: store only one copy per duplicate group.
Tracing: We need to be able to trace the dead-letter back to its origin and processing history. That means we need to store correlation IDs, perhaps a trace ID that spans the entire pipeline. Could incorporate OpenTelemetry trace information. The system should allow querying by trace ID, original message ID, etc. Also store processing attempts logs, maybe a log of events per dead-letter (like attempts, timestamps, error reasons). This could be stored as a separate time-ordered log.
Replay windows: The system should support replaying dead-letter messages within a certain time window. This could be for automatic retry after some time (e.g., after fixing a bug) or manual. The system should be able to re-emit messages back to the original topic (or a retry topic) respecting ordering? Possibly replay within a window: only messages that entered DLQ within the last X days are eligible for replay. After that, they may be archived or deleted. Also need to handle duplicates during replay (avoid re-processing already processed messages). Might need to track replay status.
Compaction: Over time, dead-letter store can grow. We want to compact data: merge duplicate entries, remove old data outside replay window, maybe summarize. Could use a time-aware compaction strategy.
Scalability and reliability: The system should handle high volume of dead-letters from many streams.
APIs: Provide write API for ingesting dead-letters, read/query API for tracing, and replay API (trigger replay for specific dead-letter or batch). Also possibly admin APIs for config.
Integration: Should integrate with existing streaming ecosystems (Kafka, Pulsar, etc.). Might use Kafka as underlying storage? Or a database? Could design using a combination: a log for ingestion, a compacted topic for deduped view, a store for tracing.
Data model: Need to represent dead-letter messages and their metadata.
We can think of architecture:
Ingestion layer: Accept dead-letter messages via network (HTTP, gRPC) or via direct integration (e.g., Kafka consumer group commit?). Could have an agent that reads from DLQ topics and forwards to this system. Or the processing framework can directly send to this system via API. We'll design an ingestion API that is idempotent.
Deduplication: Upon ingestion, we compute a deduplication key (maybe using a combination: source system, original message ID, error code?). Check if we already have a dead-letter for that key. If yes, we might want to update some fields (like count of occurrences, latest error, timestamps). We need to store a canonical dead-letter record. Use a storage that supports efficient key-based lookup and update, like a key-value store (e.g., RocksDB, DynamoDB, Cassandra) or a database. Alternatively, use a log-structured store with compaction: e.g., a Kafka topic with key = dedup key and value = dead-letter record, using Kafka's log compaction to keep latest version. That could be a nice fit: we can ingest into a compacted Kafka topic. Each dead-letter is a record with key = dedupId, value = metadata. The compaction will merge duplicates, keeping the latest (or we can have a custom merge). But Kafka compaction is based on key and retains latest record for each key; it doesn't merge. However we could use a custom format: the value can contain a list of occurrences? But then updates would need to merge. Better to use a store that supports read-modify-write atomically.
Tracing store: We want to maintain a history of events for each dead-letter: perhaps a series of occurrences (each time it was sent to DLQ). That could be stored in an append-only log (like a separate topic) keyed by dead-letter ID. Then we can query by trace ID via indexing. For low latency, we might want a database that supports secondary indexes. Or we can use Elasticsearch for traceability. But we need to design within constraints.
Replay management: We need to track which dead-letters are eligible for replay (within window) and maybe their replay status (if replayed, mark as such, maybe with timestamp). When replay is triggered (automatically or manually), we need to emit the original message to a retry topic. We must ensure ordering? Possibly we can replay from the DLQ store. We may need to keep original message content and its offset to preserve ordering? If we replay to original topic, we need to maintain partition ordering. Could use original partition and offset for ordering? But if we produce to the topic, offset is assigned by broker. To maintain order relative to other messages, we need to produce to the same partition as original. So we should store partition number. Then replay can produce to that partition. However, if we replay many messages, order among them is based on original offset order? We might need to replay in offset order per partition. The system could sort and produce sequentially. But replay could be done by a separate consumer that reads from DLQ store and writes to topics with a delay. Might be complex.
Simplify: Replay could be a separate feature: we allow user to select dead-letters (by query) and trigger a replay job that reads dead-letter records (original message) and produces them to a target topic (maybe the original topic or a retry topic). The job can respect ordering if it processes per partition and by original offset. But we can assume replay will be best-effort ordering; we may not guarantee strict ordering across partitions. But we can at least preserve order per partition by replaying in offset order. So we need to store offset and partition.
Compaction and retention: We want to automatically remove dead-letters older than replay window (if not replayed or after replay). But maybe we keep them for audit? The requirement says "replay windows" so we have a window within which replay is possible. Outside that window, we may delete or archive. We can implement a Time-to-Live (TTL) on dead-letter records. However, since we have duplicates, the TTL should apply to the canonical record. But if duplicates keep coming, we might extend TTL. Possibly use a last-seen timestamp.
Duplicate suppression details: The deduplication key should be chosen to identify the same logical failure. If the same message fails multiple times, we want to treat as duplicate. But what if the message content changes? In streaming systems, message immutability; same offset same content. So using topic+partition+offset is unique per message. But if a consumer fails and retries (same offset, same content), it's the same message. So dedup key = (topic, partition, offset). That's unique per message. But if a message fails, it may appear exactly once in DLQ? Actually, often DLQ gets a copy of the message. If a consumer retries and fails again, it may send again to DLQ. So duplicates across retries. So using (topic, partition, offset) will deduplicate. However, if the same message is sent to DLQ from multiple consumer group members? That shouldn't happen because each partition consumed by one consumer in group; but if consumer crashes and rebalance, maybe same message could be re-delivered? Still same offset. So key works.
But sometimes we may want to deduplicate based on a business key if the same logical event appears with different offsets? That seems less likely; but we can allow custom dedup key configurable.
So we'll use (source_topic, partition, offset) as dedup key. Also we might include an optional "deduplication_id" from the message headers if provided (like Kafka's message id?). But we can stick with offset.
But note: offset is only unique within a partition. So together with topic and partition it's unique.
Thus the canonical dead-letter record will have fields:
dedup_key: (topic, partition, offset) as composite key.
message_id: maybe a UUID we generate for internal tracking.
original_message: the payload (or reference? But we need to replay, so store content). Could be stored as bytes.
last_failure_ts: most recent time we saw this dead-letter (for TTL).
occurrence_count: how many times we've seen this dead-letter (duplicate count).
trace_id: extracted from message headers or generated to correlate across systems.
replay_status: maybe (not replayed, replayed, retried) and replay timestamp.
replay_count: how many times replayed.
But we might also want to maintain a history of each occurrence: e.g., each time we get a failure we want to record additional context like which consumer instance, attempt number, etc. That could be too much. But tracing requirement suggests we need to trace the processing path. That might be stored separately as an event log. Could use a separate append-only log: each time a dead-letter is ingested (or an attempt made), we write an event to a "dead-letter events" log keyed by internal dead-letter ID. That event contains timestamp, consumer, error, maybe a trace ID. Then we can query the timeline.
Thus two data stores:
Canonical store: compacted representation of each distinct dead-letter (by dedup key). This holds aggregated info and the latest failure details, and state for replay. It can be stored in a database with primary key = dedup_key, and TTL based on last_failure_ts + retention window. Or a Kafka compacted topic: each time we get a dead-letter, we produce a record with key = dedup_key and value = aggregated state. Since we need to update the state (e.g., increment count, update last_failure_ts), we need to read-modify-write. Kafka's log compaction would keep the latest record, but we need to merge. We can implement merging in the producer: when we receive a dead-letter, we fetch the current state (maybe from a local cache or from the store), update, and write new state. But that's not atomic and may cause race conditions if multiple ingesters. Better to use a database that supports atomic updates (e.g., Cassandra with lightweight transactions, DynamoDB with conditional updates). Or use a Kafka Streams application that reads from an ingestion topic and does stateful aggregation to produce compacted topic. That could be good: ingestion topic (raw dead-letters) -> Kafka Streams app that deduplicates and aggregates, writes to a compacted topic "dead-letters-compacted". The Streams app maintains a state store (rocksdb) for dedup keys, aggregates count, last seen, etc. It can also produce events to a separate "dead-letter-events" topic for each raw dead-letter (or aggregated). The compacted topic will have one record per dedup key, with the latest aggregated state. The state store is backed by changelog topic that is compacted, providing fault tolerance. This is a common pattern.
Thus:
Raw ingestion: dead-letter messages are sent to a Kafka topic dlq-raw (or multiple). This topic is not compacted, just retained for a short time (e.g., 24h) for processing.
Deduplication/Aggregation Stream: A Kafka Streams application (or Flink) reads dlq-raw, groups by dedup key, maintains an aggregate: count, first_ts, last_ts, latest error, maybe list of recent events (bounded). It updates the aggregate on each new message. The aggregate is written to a compacted topic dlq-compacted with key = dedup_key. This topic retains the latest version for each key indefinitely (or with TTL). Actually, we may also want to delete after replay window. We can set a retention on compacted topic? In Kafka, compacted topics still have a delete retention (the "delete.retention.ms" and "min.cleanable.dirty.ratio") but compaction alone doesn't remove keys unless we write a tombstone. We could have a background job to write tombstone for entries older than retention window. Or we can have the Streams app manage TTL: if last_ts older than window, produce tombstone (null value) to remove key. But we might want to keep for audit; but requirement: replay windows, after which maybe not replayable but could be archived. Could also just keep but mark as expired.
Alternatively, use a database with TTL.
For simplicity, we can use Kafka with Streams and manage TTL with a separate cleaner.
Tracing events: The Streams app also writes each raw dead-letter event (or aggregated) to an "events" topic dlq-events which is time-ordered and retained for a longer period. This topic can be consumed by indexing services (e.g., Elasticsearch) to enable trace queries. Or we can use Streams to update a tracing store (e.g., Cassandra) with timeline per dead-letter ID.
Query Service: A service that reads from dlq-compacted and dlq-events (or the tracing store) to answer queries: by dedup key, by trace_id, by time range, etc. Could use a REST/gRPC API. The query service can also expose the dead-letter details, including occurrence history.
Replay Service: A service that can trigger replay. Replay could be manual via API or automatic (e.g., schedule). The service reads from dlq-compacted (or directly from state store) for dead-letters that are eligible (within window and not replayed). It then produces the original message to a retry topic, possibly preserving partition. It should mark the dead-letter as replay attempted (maybe update replay_status and replay_count). Since the compacted record is in Kafka, we can produce a new updated record with updated status. The Streams app could also be used for replay, but separate service might be fine.
Management/UI: For operators.
Now, duplicate suppression: The dedup key based on topic+partition+offset ensures that multiple attempts of same message are aggregated. However, note that if a message is processed successfully after some retries, it might still be in DLQ from earlier attempts. But the DLQ is for permanently failed messages; assume that once a message goes to DLQ, it's not retried by the consumer (consumer may skip after sending to DLQ). But the same message might be sent to DLQ again if the consumer restarts and reprocesses? That would be same offset, so dedup.
But if a message is sent to DLQ and later we fix a bug and replay it, after successful processing, we might not want it to appear again as dead-letter. However, if it fails again after replay, it would be a new occurrence, but still same dedup key? The offset is same, but after replay it will be a new message produced to the original topic with a new offset? Actually, replay produces a new message with new offset. So if that fails, it's a different offset. So dedup key will be different. That's fine: we want to capture new failures separately.
Now, tracing: We need to support traces across the pipeline. If original message contains a trace ID (like OpenTelemetry traceparent), we can extract and store. Also, when the dead-letter is ingested, we could generate a new trace ID for the dead-letter handling pipeline? But we want to trace the original processing. So we should propagate the trace ID from the original message into the dead-letter metadata. Additionally, when the dead-letter is handled (e.g., when the deduplication stream processes it), it could generate its own trace IDs for internal tracing but we can link via parent ID.
The system should allow querying dead-letters by trace ID to see all failures associated with that trace. Might be one dead-letter per trace if the trace encompasses one message; but could be multiple if one trace spans multiple messages? Usually trace ID per request, but in streaming, each message may have its own trace ID. So we can index by trace ID.
Implementation: When the Streams app processes a raw dead-letter, it writes an event to dlq-events containing: dedup_key, trace_id (if present), timestamp, failure details, etc. We can have a separate Elasticsearch index that consumes dlq-events and indexes by trace_id, by dedup_key, by time, etc. That allows full-text search and complex queries. Alternatively, if we want to keep simple, we can store events in a database with secondary index on trace_id. But for scalability, Elasticsearch is common for logs.
But the requirement: "tracing" likely means ability to trace the dead-letter's origin and processing history. So we need to provide an API to get the timeline of events for a given dead-letter. That can be served from the events store.
Now, replay windows: We need to define a configuration: e.g., replay.window.days = 7. Only dead-letters that first appeared within last 7 days are eligible for replay. Or maybe based on last failure? Typically, you want to reprocess recent failures after a fix. So we can set a window after which dead-letters are archived (maybe moved to cold storage). The system should automatically expire old entries from the compacted store (by producing tombstones) and also purge events older than window from the events store (or move to archive). We need a retention policy.
Also, replay might be automatic: e.g., a scheduled job that replays all eligible dead-letters after a delay (e.g., 1 hour after failure). Or only manual. We'll support both.
Replay functionality: When replay is triggered (for a specific dedup key or a set), we need to fetch the original message content and its partition/offset. Then produce a new message to the target topic. To maintain order, if we replay many messages for a partition, we should replay in increasing offset order. But if we replay individually, order might not be guaranteed. However, we can design a replay job that sorts by offset per partition and produces sequentially. But we could also let the user handle ordering; we can provide an option to preserve ordering. For simplicity, we can say that replay messages are produced to the target topic with the same key (if any) and partition (using producer's partitioner based on key? Actually, to force partition, we need to specify partition. In Kafka producer, you can specify partition. So we can set partition = original partition. The order of messages within a partition is the order they are produced. If we produce messages one by one, they will be in order of production. If we produce a batch of messages for a partition, we should order them by original offset. So the replay service should fetch messages sorted by offset and produce accordingly.
Also, we need to consider idempotency: replaying a message that already succeeded? We can't know. But we can mark replay status. If a dead-letter is replayed and later fails again, it's a new entry.
Now, design components:
Client Library / Producer: For streaming applications to send dead-letters. Could be integrated in the consumer code. It sends a DeadLetterRecord to dlq-raw topic. The record includes:
dedup_key (or fields to compute it): source_topic, partition, offset.
original_message (payload bytes)
original_headers (map)
failure_info: error code, message, stack trace, consumer_id, processing_stage, etc.
timestamp (event time)
trace_id (extracted from headers or generated)
attempt maybe.
The client library could batch and send, or just produce one-by-one.
Raw DLQ Topic: dlq-raw. High retention? Actually, we only need it for the stream processing; can have short retention (e.g., 24h). Partitioned for parallelism. Number of partitions should match expected throughput.
For each message, compute dedup key (e.g., key = topic+"|"+partition+"|"+offset).
Maintain a state store (rocksdb) keyed by dedup key. The state includes:
first_ts (min timestamp)
last_ts (max timestamp)
count
latest_failure_info (maybe the most recent error details)
latest_original_message (we need to keep the message content for replay; but if we aggregate duplicates, we need to store the message only once; that's fine, as they are identical)
trace_id (could be from first occurrence or latest? Should be same if consistent; but if missing in some, we might take the first non-null)
replay_status (e.g., NONE, REPLAYED, etc.)
replay_timestamp
On receiving a new record for a key, update state: increment count, set last_ts = now, update failure info if needed (maybe keep latest error). If it's the first, store first_ts = now.
Also, produce an event to dlq-events topic. The event could be the raw dead-letter record plus some processed metadata (e.g., current count after update). This event log is append-only and will be used for tracing.
Given the open-ended nature, we should produce a high-level design with components and interactions, focusing on duplicate suppression, tracing, and replay windows.
Let's structure the answer:
Problem Statement & Goals: Briefly define what a streaming dead-letter compaction system does and what we aim to achieve: deduplication, tracing, replay windows. Mention that it sits between streaming consumers and their dead-letter queues, providing a unified service.
Core Concepts:
Dead-letter record structure.
Deduplication key: (topic, partition, offset) or custom.
Storage: Compacted state store (for canonical dead-letters) and Event log (for trace)
Query & Replay APIs
Optional indexing for trace search.
Provide a diagram in text: Raw Dead-letters -> Stream Processor -> (Compacted Store, Event Log) -> Query Service, Replay Service.
Detailed Component Design:
a. Dead-letter Ingestion:
Consumer applications send dead-letters to a well-defined Kafka topic dlq-raw.
Message format: include metadata fields. Idempotent production (use dedup key as message key? Actually we can set key = dedup_key to help partition? But we don't need; the stream processor will compute key.
Optionally, a sidecar agent can forward from existing DLQs.
b. Deduplication & Aggregation Stream Job:
Use Kafka Streams (or Flink) with exactly-once.
Input: dlq-raw.
Key selector: compute dedup_key (e.g., topic + "|" + partition + "|" + offset). This ensures same message maps to same key.
State store: dead-letter-store (persistent, RocksDB). Value: DeadLetterAggregate with fields: first_ts, last_ts, count, latest_failure, original_message (bytes), trace_id, replay_status, replay_attempts, etc.
Processor: For each incoming raw dead-letter:
Look up current aggregate by key (state store).
If absent, create new with first_ts=now, count=1, store original_message, trace_id, failure info, etc.
If present, increment count, update last_ts=now, maybe update failure info if new error code? Keep latest.
Also, emit an event record to dlq-events topic containing details of this occurrence (timestamp, error, maybe the current count). The event can be keyed by an internal dead-letter UUID or by dedup_key? For ordering per dead-letter, we can use the same dedup_key as key, so events for same dead-letter go to same partition, preserving order. The event topic can have retention longer.
Now, we need to produce a detailed design. The user said: "Design a streaming dead-letter compaction system: duplicate suppression, tracing, and replay windows." So we should produce a design document style.
Let's craft the answer with sections.
We'll assume use of Apache Kafka as the streaming platform, Kafka Streams for processing.
We'll describe the system in terms of components:
Dead-Letter Producer API: How applications send dead-letters.
Raw Dead-Letter Topic: Ingestion point.
Deduplication & Aggregation Processor: The core.
Compacted Dead-Letter Topic: For latest state (or state store).
Dead-Letter Event Topic: For full history.
Query & Replay Services: APIs.
Indexing for Tracing: Optional.
Also address duplicate suppression: how we avoid storing duplicates.
Tracing: how we link back.
Replay windows: TTL and eligibility.
Let's write with details.
We'll also discuss alternatives and trade-offs.
Make it comprehensive.
Potential edge cases: What about messages with no offset? Could be from non-Kafka sources; but we can still generate a unique dedup key using a message ID header if provided. We'll allow configurable dedup key strategy.
Also need to handle large messages: maybe store original message in object storage (S3) and only keep reference in dead-letter store to avoid large Kafka messages. But for simplicity, store in the store; but note size limits.
We could mention that for large payloads, we could store the original message in a blob store and store a pointer.
Now, produce the answer.
We'll structure as:
Introduction & Goals
System Overview (diagram in text)
Data Model
Component Deep Dive
4.1. Dead-Letter Ingestion
4.2. Deduplication & Aggregation Stream
4.3. Storage & Compaction
4.4. Tracing & Event Log
4.5. Query Service
4.6. Replay Service
4.7. Replay Window Management
Failure Handling & Exactly-Once Guarantees
Scaling Considerations
Security & Multi-tenancy
Summary
We'll also include pseudocode for the Streams processor.
Let's write in a clear, technical style.
Streaming Dead‑Letter Compaction System
1. Introduction
In distributed streaming systems, consumer applications occasionally fail to process a message. Those messages are often sent to a dead‑letter queue (DLQ) for later inspection. As the volume grows, raw DLQs become unwieldy: the same message may appear many times (duplicate failures), navigation becomes difficult, and automated remediation (replay) is needed.
The Streaming Dead‑Letter Compaction System (DLCS) solves these problems by:
Duplicate suppression – merging all occurrences of the same failed message into a single canonical record.
Tracing – preserving the full failure history and correlating it with distributed traces (e.g., OpenTelemetry) for root‑cause analysis.
Replay windows – keeping dead‑letters only for a configurable period, after which they are eligible for automatic or manual replay and ultimately purged.
The design is built on Apache Kafka and Kafka Streams, leveraging log compaction, stateful processing, and exactly‑once semantics.
dlq-raw – All dead‑letter records are first written here by producers.
Deduplication & Aggregation Stream – Consumes dlq-raw, maintains a state store (dead-letter-store) keyed by a deduplication identifier, updates aggregates, and writes:
The latest aggregate to the changelog topicdlq-compacted (log‑compacted).
A full event for each occurrence to dlq-events (retained for tracing).
Query Service – Exposes REST/gRPC APIs. It reads the latest aggregates from the state store (via interactive queries or a materialized cache) and the event history via an index (e.g., Elasticsearch) built from dlq-events.
Replay Service – Triggers replay of eligible dead‑letters. It produces the original payload to the target topic and sends a replay command to a command topic (dlq-replay-commands), which the Streams app consumes to update the aggregate’s replay status.
3. Data Model
3.1 Raw Dead‑Letter Record (produced to dlq-raw)
Field
Type
Description
dedup_key
string
Computed as `{topic}
original_message
bytes
The failed payload.
original_headers
map
All headers from the original message (including traceparent, etc.).
Current count after merge (so history shows progression).
failure_info
struct
The failure info of this occurrence.
trace_id (opt)
string
Current trace ID.
3.4 Replay Command (to dlq-replay-commands)
Field
Type
Description
dedup_key
string
Target dead‑letter.
command
string
MARK_REPLAYED (or future commands).
requested_ts
long
When the command was issued.
4. Component Deep Dive
4.1 Dead‑Letter Ingestion
Streaming consumer libraries include a helper that, upon an unrecoverable exception, produces a RawDeadLetter to the dlq-raw topic. The message key can be left empty; the Streams job computes the deduplication key.
Idempotency – Producers may use Kafka’s idempotent producer or include a client‑generated UUID to avoid duplicate writes due to retries. However, the deduplication layer is robust even if duplicates arrive.
4.2 Deduplication & Aggregation Stream
A Kafka Streams application (or Flink job) performs exactly‑once processing:
java
StreamsBuilder builder = new StreamsBuilder();
KStream<String, RawDeadLetter> raw = builder.stream("dlq-raw",
Consumed.with(Serdes.String(), rawDeadLetterSerde));
// State store: dead-letter-store (key: dedup_key, value: DeadLetterAggregate)
StoreBuilder<KeyValueStore<String, DeadLetterAggregate>> storeBuilder =
Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore("dead-letter-store"),
Serdes.String(),
deadLetterAggregateSerde);
builder.addStateStore(storeBuilder);
// Process each raw dead‑letter
raw.process(() -> new Processor<>() {
private KeyValueStore<String, DeadLetterAggregate> store;
@Override
public void init(ProcessorContext context) {
this.store = (KeyValueStore<String, DeadLetterAggregate>) context.getStateStore("dead-letter-store");
}
@Override
public void process(String key, RawDeadLetter value) {
String dedupKey = value.getDedupKey(); // e.g., topic|partition|offset
DeadLetterAggregate agg = store.get(dedupKey);
long now = System.currentTimeMillis();
if (agg == null) {
agg = new DeadLetterAggregate();
agg.setFirstFailureTs(now);
agg.setOriginalMessage(value.getOriginalMessage());
agg.setTraceId(value.getTraceId());
}
agg.setLastFailureTs(now);
agg.setOccurrenceCount(agg.getOccurrenceCount() + 1);
agg.setLatestFailureInfo(value.getFailureInfo());
store.put(dedupKey, agg);
// Emit an event to dlq-events (key = dedupKey to keep ordering)
DeadLetterEvent event = new DeadLetterEvent();
event.setEventId(UUID.randomUUID().toString());
event.setDedupKey(dedupKey);
event.setEventTimestamp(now);
event.setOccurrenceCount(agg.getOccurrenceCount());
event.setFailureInfo(value.getFailureInfo());
event.setTraceId(agg.getTraceId());
context.forward(dedupKey, event, To.child("events-sink"));
}
@Override
public void close() {}
}, storeBuilder.name());
// Sink for events
builder.stream("dlq-events", Consumed.with(Serdes.String(), deadLetterEventSerde));
The state store is persistent (RocksDB) and backed by a changelog topic (dlq-compacted) that is log‑compacted. This topic automatically retains the latest aggregate per key and serves as the durable backup.
Exactly‑once: The Streams app is configured with processing.guarantee=exactly_once_v2. Offsets are committed only after the state store and downstream production succeed.
4.3 Storage & Compaction
dlq-compacted – Changelog topic for the state store. It has cleanup.policy=compact and delete.retention.ms set to a large value. It contains the latest aggregate for each dedup key.
dlq-events – Append‑only topic with a longer retention (e.g., 30 days). It stores every raw dead‑letter occurrence as an event, enabling full history reconstruction.
4.4 Tracing & Event Log
The dlq-events topic is the source of truth for tracing. A separate indexer service consumes this topic and writes documents into Elasticsearch (or any searchable store). Index fields include:
dedup_key
trace_id
event_timestamp
error_code
occurrence_count
consumer_id
This allows operators to:
Search all dead‑letters belonging to a specific trace (trace_id filter).
View the timeline of a particular dead‑letter (fetch events by dedup_key sorted by event_timestamp).
Filter by time, error type, etc.
4.5 Query Service
A lightweight REST/gRPC service that:
Reads latest aggregates – Uses Kafka Streams Interactive Queries to query the dead-letter-store of any Streams instance (or reads from a materialized cache that mirrors dlq-compacted).
Example endpoint: GET /dead-letters/{dedup_key} returns the aggregate.
Searches events – Queries Elasticsearch for trace‑centric lookups.
Example: GET /dead-letters?trace_id=xyz returns a list of aggregates whose events contain that trace ID.
Lists aggregates – Supports pagination and filters (?status=REPLAYED&before=...). The filter can be applied against the aggregates cache or via Elasticsearch aggregation.
4.6 Replay Service
The Replay Service can be invoked manually (UI, CLI) or scheduled.
Eligibility – A dead‑letter is replayable if:
Its last_failure_ts is within the replay window (configurable, e.g., 7 days).
Its replay_status is NONE.
Replay workflow:
Query the Query Service for a batch of eligible dead‑letters (keys).
For each key:
Fetch the aggregate (including original_message, partition, offset, original headers).
Produce a new message to the target topic (original topic or a dedicated retry topic):
java
ProducerRecord<byte[], byte[]> rec = new ProducerRecord<>(
targetTopic,
originalPartition,
originalOffset, // not used by broker, but we keep for reference
originalKey,
originalMessage,
originalHeaders);
producer.send(rec).get(); // sync or handle errors
Upon successful production, send a ReplayCommand to dlq-replay-commands:
The Streams application also subscribes to dlq-replay-commands and updates the corresponding aggregate:
Set replay_status = REPLAYED.
Set replay_timestamp = command.requested_ts.
Increment replay_count.
The updated aggregate is written back to the state store, which propagates to dlq-compacted.
A new event is emitted to dlq-events with failure_info indicating replay.
If the replay production fails (e.g., broker error), the service can retry or mark the dead‑letter as SKIPPED after max attempts.
4.7 Replay Window Management
The Streams job periodically (e.g., every hour) runs a punctuator that scans the state store:
java
if (agg.getLastFailureTs() < now - replayWindowMs &&
agg.getReplayStatus() == ReplayStatus.REPLAYED) {
// Expire: delete from store (tombstone)
store.delete(dedupKey);
}
The tombstone propagates to dlq-compacted, causing compaction to remove the key.
Corresponding events in dlq-events are left to natural retention (or can be deleted by a separate log‑cleaner if desired).
The replay window is configurable per deployment or per dead‑letter type (via a field in the raw record).
5. Exactly‑Once Guarantees & Fault Tolerance
Ingestion: The dlq-raw topic is durable. Producers can use idempotent writes or include a client‑side UUID; duplicates are harmless.
Processing: Kafka Streams with exactly_once_v2 ensures each raw dead‑letter is processed exactly once, even in the face of failures. The state store updates and event emission are atomic within the transaction.
State recovery: The changelog topic (dlq-compacted) is compacted; on restart, the state store is rebuilt from it.
Replay commands: Consumed in the same transactional boundary as other inputs, guaranteeing that replay status updates are consistent with the aggregate’s state.
6. Scaling Considerations
Partitioning: dlq-raw and dlq-events should have enough partitions to match the throughput. The number of Streams tasks equals the partition count.
State store size: The state store holds one aggregate per distinct dead‑letter within the replay window. If the volume is high, increase the number of partitions and thus the number of Streams instances, each holding a subset.
Hot keys: If a single message fails repeatedly, its aggregate is updated frequently. This is a single key; however, contention is low because all updates for that key go to the same task (by partition). That’s acceptable; if a single key becomes extremely hot, we could bucket by additional salt, but not typical.
Query service: Can be scaled horizontally if using a shared cache (e.g., Redis) behind a load balancer. Interactive Queries directly hit the Streams instances; a query gateway can route requests to the correct instance using the KeyValueStore query API.
7. Security & Multi‑Tenancy
Authentication & Authorization – Kafka ACLs restrict who can produce to dlq-raw and who can read the compacted/event topics. The Query and Replay services enforce application‑level auth.
Multi‑tenant isolation – The dedup key can be prefixed with a tenant ID if multiple independent systems share the DLCS. The Streams job can filter by tenant if needed.
8. Summary
The proposed Streaming Dead‑Letter Compaction System provides:
Duplicate suppression via a deduplication key and a stateful aggregation stream.
Full tracing by emitting a searchable event for every failure and linking to distributed traces.
Replay windows with automatic expiration and a controlled replay mechanism that preserves original ordering per partition.
All components are built on battle‑tested Kafka primitives (topics, compaction, Streams), ensuring scalability, durability, and exactly‑once processing. The system can be deployed as a set of microservices (Streams app, query service, replay service, indexer) with clear separation of concerns.
Periodically (or on each update), write the current state to dlq-compacted topic with key = dedup_key and value = serialized state. Since Kafka Streams automatically writes updates to a changelog topic (which is compacted) for the state store, we might not need a separate output topic if we use the state store as the source of truth. However, we want to expose the compacted view to other services (query, replay). We could use the state store's queryable store feature, but that's only within the Streams app. So better to have an output topic dlq-compacted that contains the latest state per key, and enable log compaction on it. The Streams app can write to this topic with key = dedup_key and value = state. Compaction will keep the latest. The state store itself is backed by a changelog topic that is also compacted, but that's internal. We can also expose the changelog topic as the compacted store, but it's not recommended to consume directly because it's compacted and may contain tombstone etc. But we can.
Simpler: The Streams app writes the state to dlq-compacted. The dlq-compacted topic has cleanup.policy=compact. Also we need to handle TTL: After a dead-letter is older than replay window and not replayed, we might want to remove it. The Streams app can check last_ts and if it's older than (current time - replay window) and we decide to expire, it can write a tombstone (null value) for that key, causing compaction to delete it. Or we could just keep and let consumers filter by timestamp.
Also, the Streams app can produce the events to dlq-events which is a regular topic with retention.ms set to longer (e.g., 30 days) for tracing history.
The Streams app should be idempotent and handle exactly-once processing semantics (EOS) with Kafka.
Tracing / Indexing Service: Consumes from dlq-events and indexes into a searchable store like Elasticsearch. This allows quick lookup by trace_id, by message content, by time range, etc. Alternatively, we could use a database with secondary indices. Elasticsearch is a common choice for logs/traces. We can also use OpenTelemetry Collector to forward traces. But our events are not spans; they are dead-letter events. We can index them.
Query Service: A REST API that queries the compacted store (maybe via dlq-compacted topic or via a database that mirrors it) and the tracing index. It can retrieve:
List of dead-letters (with pagination, filters like time range, error type, trace_id)
Details of a specific dead-letter (canonical info + event history)
Replay status.
This service could directly query the dlq-compacted topic using a Kafka consumer (but reading a compacted topic to get latest state per key is tricky because you need to know the keys. You might need to consume from beginning and build a local cache, or use Kafka's KeyValue store via Interactive Queries if using Streams. Better: The Streams app can expose its state store via Interactive Queries, so the query service can request the state from the Streams app instance that owns the key. That is efficient and up-to-date. Or we can have the Streams app also write the compacted state to a database (e.g., Cassandra) that the query service reads. That's simpler for decoupling.
Option: Use Kafka Streams with a state store, and have the query service use Kafka Streams Interactive Queries to fetch the state. That is a typical pattern: the processing app provides query endpoint. But then we need to scale the query service? Could embed query in the Streams app.
Alternatively, we could have the compacted topic be the source of truth and have a separate service that continuously materializes it into a key-value store (like a cache). That might be overkill.
Simpler: Since the compacted view is relatively small (only dead-letters within window), we could store it in a database. The Streams app writes updates to the database. Then query service reads from DB. This adds latency but acceptable. We'll design with a database: e.g., DynamoDB or Cassandra. The Streams app can write to the DB using exactly-once semantics? That's tricky. But we can do idempotent writes using the dedup key as primary key. The Streams app can be configured to commit offsets after DB write, but might have duplicates. We can accept at-least-once and make DB writes idempotent (using primary key and version). That's okay.
However, we want to keep the design simple and use Kafka as the central log. I'd propose:
The compacted view is stored in a compacted Kafka topic dlq-compacted.
For querying, we can have a service that uses Kafka's KafkaConsumer to read the compacted topic and maintain a local cache of the latest state per key (by polling). Since the topic is compacted, reading from latest offset only gives the latest state for each key? Actually, to get the latest state for all keys, you need to consume the entire topic from beginning or use the "compact" read? There's a feature: you can use KafkaConsumer with assign and seek to beginning and then read all records; as you read, you'll get updates. But to have a full view, you need to keep the cache updated by reading all new records. That's feasible: the query service can be a long-running consumer that reads from dlq-compacted and builds an in-memory or external cache (e.g., Redis) with the latest state per key. Then it serves queries from that cache. It can also read from the events topic for history. That's a typical materialized view pattern.
But the query service might be stateless; it could query Kafka directly each time, but that would be inefficient. So we can have a dedicated materialized view service that maintains a cache.
Given complexity, we can design: The Streams app maintains a state store; we expose its store via Interactive Queries. The query service then contacts the Streams app to fetch state for a given key. For listing, we might need to scan the state store, which is not directly supported across partitions. Interactive Queries can fetch local store for a partition, but to list all we'd need to query all instances. That's complicated.
Perhaps we can store the compacted data in a distributed database that supports range queries, like Cassandra. Then we can easily query. So the Streams app writes to dlq-compacted topic and also to Cassandra? That's double write. Could instead have the Streams app write directly to Cassandra and use Kafka for the raw ingestion and events. But then we lose the log. However, we can still have raw topic and events topic. The compacted view is in Cassandra. That's acceptable.
Let's decide: To simplify the design description, we can say we use a stateful stream processing engine (e.g., Kafka Streams) that maintains a deduplication state store. The state store is backed by a changelog topic that is compacted. For external querying, we can use Interactive Queries to expose the state store. That's a clean solution within the Kafka ecosystem. We'll describe that.
So:
The Streams app has a state store dead-letter-store with key = dedup_key, value = DeadLetterAggregate.
The store is queriable. We can expose a REST endpoint on each Streams app instance (or have a separate query service that uses Kafka Streams' ReadOnlyKeyValueStore via Interactive Queries to query the store across the cluster).
For trace events, we have dlq-events topic, which can be queried by scanning through it or by indexing into Elasticsearch. We can also have a separate query for events.
However, the requirement likely expects a design using standard streaming concepts; we don't need to decide on specific technology but outline the approach.
Write updated aggregate to the state store.
The state store is automatically backed by a changelog topic that is compacted. This changelog topic can serve as the compacted store for external queries if we expose it.
TTL handling: Periodically, a punctuator scans the store; if an entry's last_ts is older than replay_window and replay_status is REPLAYED (or maybe not), we can delete it from the store (produce tombstone). This effectively expires dead-letters after the window.
c. Storage:
The state store (RocksDB) holds the canonical aggregates.
The changelog topic dlq-compacted is compacted and contains the latest aggregate for each key. This topic is the durable backup and can be used for restoring state.
The event topic dlq-events is time-ordered, retained for longer (e.g., 30 days). Contains a full history of each dead-letter occurrence. This is the source for tracing.
d. Query Service:
Provides REST/gRPC endpoints.
Uses Kafka Streams Interactive Queries to read from the state store of the processing job (or directly from the compacted topic if we materialize into a DB).
For a given dedup key (or by query filters), it can fetch the current aggregate.
For trace history, it can query the dlq-events topic (maybe via an Elasticsearch index). The query service may call into a separate indexing service that maintains an Elasticsearch index populated from dlq-events.
Supports: getDeadLetter(dedup_key), listDeadLetters(filters: time range, error type, trace_id, status), getDeadLetterHistory(dedup_key) (which reads from events).
e. Replay Service:
Can be triggered manually via API or automatically on a schedule.
Input: selection criteria (e.g., all dead-letters with status=NEW and last_ts within window, or specific keys).
For each selected dead-letter, read the original_message from the aggregate state (from the state store or compacted topic).
Produce a new message to the target topic (original topic or retry topic). The producer should set:
partition = original partition (so ordering per partition can be preserved if sorted)
key = original key if any (from headers)
headers = original headers (maybe adjusting some)
value = original_message.
If need to preserve order, the replay job can collect messages per partition and sort by original offset, then produce in that order. Could use multiple producer threads per partition.
After successful production, update the dead-letter aggregate: set replay_status = REPLAYED, replay_timestamp = now, replay_count++. This update goes through the Streams job (by writing a new record to dlq-raw? That would cause re-processing). Better: The replay service can directly write to the state store via the Streams app's Interactive Queries? Not ideal. Alternatively, the replay service can produce a special "replay command" message to a command topic that the Streams app consumes and updates the state. Or the replay service can produce to dlq-raw with a flag indicating it's a replay? That would be odd.
Simpler: The replay service can directly produce to the target topic, and then also update the dead-letter store. To update, we need to write to the state store. We could have the Streams app expose an RPC for updating replay status. But that introduces coupling. Better: The replay service can produce a record to an internal "replay-requests" topic. The Streams job consumes that and for each request, rewrites the aggregate with updated replay status. That keeps the state updates in the Streams job, ensuring consistency. The replay service then waits for acknowledgment? Could be asynchronous.
Alternatively, we can treat replay as just producing the message and marking the dead-letter as replayed; that marking can be done by producing a special event to dlq-events that the Streams job picks up and updates the store. But the Streams job already processes raw dead-letters; it doesn't process updates from events. We could design a separate command topic.
Design: Introduce a dlq-replay-commands topic. Replay service sends a command message with key = dedup_key and value = ReplayCommand (e.g., REPLAY). The Streams job also consumes this topic and updates the corresponding aggregate (set replay_status, etc.). This ensures state mutation is done via the same processing pipeline.
Replay service workflow:
Query for eligible dead-letters (using query service).
For each, fetch original_message (maybe from query service or directly from state store if it has access).
Produce to target topic.
After successful production, send command to dlq-replay-commands to mark as replayed.
The Streams job, upon receiving the command, looks up the aggregate and updates the replay fields. It also writes a new event to dlq-events indicating replay.
If the replay itself fails (e.g., produce error), we may not mark as replayed; we could have retries.
This design keeps all state mutations in one place.
f. Replay Window Management:
The Streams job uses a config replay.window.ms. On each update of an aggregate, it checks if last_ts is older than now - replay.window.ms and replay_status != REPLAYED? Actually, we may want to expire only after window and after replay? But if it's not replayed, maybe we should keep it until window expires, then delete. So: if last_ts < now - replay.window.ms and replay_status is REPLAYED or we decide to purge regardless, we write a tombstone. We could also have a background job that periodically scans and issues tombstone commands.
g. Duplicate Suppression Implementation Details:
The dedup key ensures that multiple raw dead-letters for same message are merged. The aggregate count shows how many times it failed.
The state store uses the key; updates are atomic within the Streams task.
Exactly-once semantics with Kafka Streams (EOS) ensures that each raw dead-letter is processed exactly once, so count is accurate.
The raw topic's retention should be at least the processing time; but we can also enable idempotent production from clients to avoid duplicates at source? Not necessary.
h. Tracing Implementation:
The dead-letter event records contain the trace ID from the original message (if available). They also contain the dedup key and other context.
These events are indexed in Elasticsearch. A separate service (Logstash or custom consumer) reads dlq-events and indexes into ES. Index pattern: deadletter-events-YYYY.MM.DD. Fields: timestamp, dedup_key, trace_id, error, count, etc.
The query service can then search ES for trace_id to get all events, then reconstruct timeline.
Alternatively, the query service can read directly from dlq-events using a consumer group, but that would require scanning potentially large logs. Indexing is better for ad-hoc queries.
Data Formats:
Define protobuf/avro schemas for RawDeadLetter, DeadLetterAggregate, DeadLetterEvent, ReplayCommand.
Use schema registry.
Fault Tolerance & Scalability:
All components are distributed. Kafka partitions provide scalability.
Streams job state is replicated via changelog and standby replicas.
Query service can be stateless if using cache; or can be scaled with Interactive Queries.
Replay service can be run as a job with parallelism.
Security & Access Control: Not core but mention.
Example Flow:
Message fails, client sends RawDeadLetter to dlq-raw.