Streaming Dead-Letter Compaction System Design
Overview
This design outlines a scalable, fault-tolerant dead-letter queue (DLQ) system for streaming pipelines (e.g., Kafka Streams, Apache Flink, or Kinesis). It handles failed events by routing them to a compacted DLQ topic, incorporating:
Duplicate suppression : Idempotent ingestion using unique keys and stateful checks.
Tracing : Full distributed tracing propagation with links to original spans.
Replay windows : Time-partitioned storage for efficient, bounded replays (e.g., debug failures in a 1-hour window).
Goals :
Minimize storage growth via Kafka log compaction.
Enable O(1) duplicate checks.
Support replay without full-scan scans.
Integrate with observability (e.g., OpenTelemetry).
Assumptions :
Events have a unique event_id (UUID or deterministic hash: hash(business_key + payload_hash)).
Streaming platform: Kafka (topics for main/DLQ streams).
Processing: Kafka Streams app for DLQ handling.
Scale: 100k+ events/sec, 1TB+ DLQ retention.
High-Level Architecture
code Copy code
[Main Stream Topic] --> [Processor App] --fail--> [DLQ Producer] --> [Compacted DLQ Topic]
|
+--> [Success Stream]
[DLQ Topic] <-- [Compactor/Retention] (Kafka-native)
|
+--> [Replay Service] --> [Replay Target (temp topic/debug endpoint)]
|
+--> [Query API/UI] (time-window filter)
[Cross-cutting]:
- Dedup Store: Redis (TTL cache) + Kafka state store (durable).
- Tracing: OpenTelemetry --> Jaeger/Zipkin.
- Monitoring: Prometheus + Grafana (DLQ size, dup rate, replay latency).
Components :
DLQ Producer : Stateless Kafka producer in processor app.
DLQ Stream Processor : Kafka Streams app for compaction, dedup, and enrichment.
Replay Service : gRPC/HTTP API for windowed replays.
Compaction : Kafka topic config (cleanup.policy=compact,delete).
Event Data Model
All events (main + DLQ) use Avro/Protobuf for schema evolution:
protobuf Copy code
message StreamEvent {
string event_id = 1; // Unique idempotency key
int64 timestamp_ms = 2; // Event creation time
string trace_id = 3; // 128-bit trace ID (W3C format)
string span_id = 4; // 64-bit span ID
bytes payload = 5; // Original event
map<string, string> metadata = 6; // e.g., {"source_topic": "main", "partition": "0"}
}
message DlqEvent {
StreamEvent original = 1;
string error_msg = 2;
int32 attempt_num = 3; // Retry count
string dlq_write_ts = 4; // DLQ ingestion time
}
1. Duplicate Suppression
Mechanism : Hybrid cache + compacted state store for <1ms checks at scale.
Key Format : {window_id}:{event_id} (e.g., 2024-10-01T14:{uuid}), where window_id = yyyy-MM-ddTHH (1-hour granularity).
Flow :
DLQ Producer generates key.
Check Redis (SETNX key 1 EX 3600 for 1h TTL): If exists → drop (99% hit rate).
Fallback: Kafka Streams state store (RocksDB-backed changelog topic) queries latest value for key.
Write DlqEvent to compacted DLQ topic (key = above).
Kafka Streams Processor :
java Copy code
public class DlqDeduplicator extends AbstractProcessor<String, DlqEvent> {
private KeyValueStore<String, DlqEvent> stateStore; // Changelog-backed
@Override
public void process(String key, DlqEvent value) {
DlqEvent latest = stateStore.get(key);
if (latest != null) { context().forward(key, null); return; } // Drop dup
stateStore.put(key, value);
context().forward(key, value);
}
}
Guarantees : Exactly-once semantics (Kafka idempotent producer + transactional writes).
Metrics : Dup rate <0.1%, cache hit >99%.
2. Tracing
Propagation : Use OpenTelemetry (OTel) semantic conventions.
In Main Stream : Processor injects trace_id, parent_span_id via TextMapPropagator.
In DLQ :
Producer creates child span: span("dlq.write").setAttribute("error", error_msg).
Links back: span.addLink(original_trace_id, original_span_id).
Exports to Jaeger on DLQ write.
Querying Traces :
DLQ events store full trace context → API fans out to Jaeger for full trace graph.
Example Jaeger query: service=dlq-producer error=true.
Visualization :
code Copy code
Original Span --> [Processor Fail] --> DLQ Span (linked)
3. Replay Windows
Storage : Time-partitioned keys enable bounded scans.
Window Granularity : 1-hour (yyyy-MM-ddTHH), configurable (15m/1h/1d).
Kafka Topic Config (dlq-compacted):
code Copy code
partitions=192 (scale by load)
replication=3
cleanup.policy=compact,delete
compaction.linger.ms=60000 // Batch compactions
segment.ms=3600000 // 1h segments align w/ windows
retention.ms=2592000000 // 30 days
Compaction Behavior :
Per-key: Keeps latest DlqEvent (overrides on retry).
Cross-window: Deletes keys older than retention (via delete policy).
Replay Service (Kafka Consumer + gRPC API):
proto Copy code
service ReplayService {
rpc ReplayWindow(ReplayRequest) returns (stream ReplayEvent);
}
message ReplayRequest {
string start_window = 1; // "2024-10-01T14"
string end_window = 2; // "2024-10-01T15"
string replay_target = 3; // Temp topic or debug sink
}
Implementation :
Consumer seeks to earliest offset for window partitions.
Filter keys: key.startsWith(start_window) and <= end_window.
Replay to target topic (idempotent producer).
Stream progress via Server-Sent Events.
Efficiency : ~10k events/window, <10s replay latency.
Use Cases :
Debug: Replay 1h window to staging processor.
Recovery: Replay + custom fix (e.g., filter bad events).
Deployment & Ops
Scaling :
Component Horizontal Scale Sharding DLQ Producer Per-partition Main topic partitions Streams App Kafka Streams autoscaling State reassignment Replay Stateless pods N/A
Retention Management :
Auto-delete windows >30d.
Alert on size >80% disk.
Fault Tolerance :
DLQ Producer: At-least-once → dedup absorbs.
Streams: Exactly-once + standby replicas.
Cost : ~$0.05/GB/month (Kafka on cloud), compacted to <10% raw size.
Testing :
Chaos: Inject failures, verify dedup/replay.
Load: 1M events/min, 0% data loss.
Potential Extensions
Auto-Retry : Cron job scans DLQ windows → replay to main w/ fixed payload.
ML Anomaly : Flag duplicate spikes as upstream issues.
Multi-Tenant : Tenant prefix in keys.
This design is production-ready, leveraging Kafka-native features for simplicity and cost-efficiency. Questions or refinements?