:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(kafka): add consumer-group DLQ replay management command (#94320)
Frank Hamand7b03bc274e67
diff --git a/posthog/kafka_client/dlq_replay.py b/posthog/kafka_client/dlq_replay.pynew file mode 100644index 000000000000..fea3c5d17d65--- /dev/null+++ b/posthog/kafka_client/dlq_replay.py@@ -0,0 +1,222 @@+from collections.abc import Callable, Sequence+from typing import Any, Optional, cast++from confluent_kafka import Consumer, Producer++from posthog.kafka_client.routing import get_profile_settings++Header = tuple[str, bytes]++# Diagnostic headers the logs/traces ingestion consumer attaches when it quarantines a+# message. They describe the old failure and must not travel back onto the target topic.+DLQ_DIAGNOSTIC_HEADERS = frozenset(+ {+ "error_message",+ "error_name",+ "failed_at",+ "source_topic",+ "source_partition",+ "source_offset",+ }+)++# Counts how many times a message has been replayed, so a message that keeps failing is+# left on the DLQ instead of cycling between the two topics.+REPLAY_COUNT_HEADER = "dlq_replay_count"+++def _replay_count(headers: Sequence[Header]) -> int:+ for key, value in headers:+ if key == REPLAY_COUNT_HEADER:+ try:+ return int(value.decode("utf-8"))+ except (ValueError, UnicodeDecodeError):+ return 0+ return 0+++def build_replay_headers(headers: Optional[Sequence[Header]], max_replays: int) -> Optional[list[Header]]:+ """Return the headers to replay with, or None when the message is exhausted.++ Strips the DLQ diagnostic headers, keeps the original ones, and increments the+ replay-count guard. Returns None when the message has already been replayed+ max_replays times, so the caller leaves it on the DLQ.+ """+ existing = list(headers or [])+ count = _replay_count(existing)+ if count >= max_replays:+ return None+ kept = [+ (key, value) for (key, value) in existing if key not in DLQ_DIAGNOSTIC_HEADERS and key != REPLAY_COUNT_HEADER+ ]+ kept.append((REPLAY_COUNT_HEADER, str(count + 1).encode("utf-8")))+ return kept+++def _client_config(+ hosts: list[str],+ security_protocol: Optional[str],+ sasl_mechanism: Optional[str],+ sasl_user: Optional[str],+ sasl_password: Optional[str],+) -> dict[str, Any]:+ config: dict[str, Any] = {+ "bootstrap.servers": ",".join(hosts),+ "security.protocol": security_protocol or "PLAINTEXT",+ }+ if sasl_mechanism:+ config["sasl.mechanism"] = sasl_mechanism+ if sasl_user:+ config["sasl.username"] = sasl_user+ if sasl_password:+ config["sasl.password"] = sasl_password+ return config+++def drain_dlq(+ *,+ source_topic: str,+ target_topic: str,+ group_id: str,+ max_replays: int = 2,+ batch_size: int = 500,+ idle_polls: int = 2,+ poll_timeout_seconds: float = 5.0,+ dry_run: bool = False,+ bootstrap_servers: Optional[str] = None,+ security_protocol: Optional[str] = None,+ log: Callable[[str], None] = print,+) -> dict[str, int]:+ """Drain a Kafka DLQ topic back into its target topic using a consumer group.++ Reads the source topic with a committed consumer group (so progress is resumable and+ visible as lag), reproduces each message to the target with the diagnostic headers+ stripped, and stops once the topic is drained (idle_polls consecutive empty polls).+ Commits a batch only after the broker acknowledges every record in it, so an+ interrupted run resumes rather than replaying from the start, and a record the broker+ rejected stays on the DLQ. A dry run counts without producing or committing.+ """+ source = get_profile_settings(topic=source_topic)+ target = get_profile_settings(topic=target_topic)++ consumer_hosts = [bootstrap_servers] if bootstrap_servers else source.hosts+ producer_hosts = [bootstrap_servers] if bootstrap_servers else target.hosts++ consumer_conf: dict[str, Any] = {+ **_client_config(+ consumer_hosts,+ security_protocol or source.security_protocol,+ source.sasl_mechanism,+ source.sasl_user,+ source.sasl_password,+ ),+ "group.id": group_id,+ "enable.auto.commit": False,+ "auto.offset.reset": "earliest",+ }++ consumer = Consumer(consumer_conf)+ producer: Optional[Producer] = None+ if not dry_run:+ producer_conf: dict[str, Any] = {+ **_client_config(+ producer_hosts,+ security_protocol or target.security_protocol,+ target.sasl_mechanism,+ target.sasl_user,+ target.sasl_password,+ ),+ "acks": "all",+ }+ producer = Producer(producer_conf)++ replayed = 0+ exhausted = 0+ errors = 0+ # confluent-kafka reports a rejected record through the delivery callback, not through+ # produce() or flush(). Without this the run would commit offsets for records the+ # broker never took, and those records would be gone from the next replay.+ delivery_failures: list[str] = []++ def on_delivery(err: Any, _message: Any) -> None:+ if err is not None:+ delivery_failures.append(str(err))++ try:+ consumer.subscribe([source_topic])+ idle = 0+ while True:+ messages = consumer.consume(num_messages=batch_size, timeout=poll_timeout_seconds)+ if not messages:+ idle += 1+ if idle >= idle_polls:+ break+ continue+ idle = 0++ delivery_failures.clear()+ produced_in_batch = 0+ for message in messages:+ err = message.error()+ if err is not None:+ errors += 1+ log(f"consume error: {err}")+ continue++ raw_headers = cast(Optional[list[Header]], message.headers())+ headers = build_replay_headers(raw_headers, max_replays)+ if headers is None:+ exhausted += 1+ continue++ if dry_run or producer is None:+ replayed += 1+ continue++ _produce(producer, target_topic, message.value(), headers, on_delivery, log)+ produced_in_batch += 1++ if producer is not None:+ producer.flush()+ failed = len(delivery_failures)+ replayed += produced_in_batch - failed+ errors += failed+ if failed:+ log(f"delivery failed for {failed} record(s); stopping without commit: {delivery_failures[0]}")+ break+ # Commit even when the batch produced nothing, because a batch of records+ # that all hit max_replays would otherwise hold the group behind it and the+ # lag would never reach zero.+ consumer.commit(asynchronous=False)++ log(f"progress: replayed={replayed} exhausted={exhausted} errors={errors}")+ finally:+ consumer.close()+ if producer is not None:+ producer.flush()++ log(f"done: replayed={replayed} exhausted={exhausted} errors={errors} dry_run={dry_run}")+ return {"replayed": replayed, "exhausted": exhausted, "errors": errors}+++def _produce(+ producer: Producer,+ topic: str,+ value: Optional[bytes],+ headers: list[Header],+ on_delivery: Callable[[Any, Any], None],+ log: Callable[[str], None],+) -> None:+ while True:+ try:+ producer.produce(+ topic=topic,+ value=value,+ key=None,+ headers=cast(Any, headers),+ on_delivery=on_delivery,+ )+ return+ except BufferError:+ # Local produce queue is full; let it drain, then retry the same message.+ producer.poll(1.0)diff --git a/posthog/kafka_client/test/test_dlq_replay.py b/posthog/kafka_client/test/test_dlq_replay.pynew file mode 100644index 000000000000..269ee7188737--- /dev/null+++ b/posthog/kafka_client/test/test_dlq_replay.py@@ -0,0 +1,190 @@+from collections.abc import Callable+from types import SimpleNamespace+from typing import Any, Optional++from unittest import TestCase+from unittest.mock import patch++from parameterized import parameterized++from posthog.kafka_client.dlq_replay import REPLAY_COUNT_HEADER, build_replay_headers, drain_dlq+++class BuildReplayHeadersTest(TestCase):+ def test_strips_diagnostics_keeps_originals_and_sets_first_replay_count(self) -> None:+ headers = [+ ("token", b"phc_abc"),+ ("team_id", b"42"),+ ("error_message", b"boom"),+ ("error_name", b"ValueError"),+ ("failed_at", b"2026-09-03T00:00:00Z"),+ ("source_topic", b"ingestion-traces"),+ ("source_partition", b"3"),+ ("source_offset", b"17"),+ ]++ result = build_replay_headers(headers, max_replays=2)++ assert result is not None+ as_dict = dict(result)+ assert as_dict == {"token": b"phc_abc", "team_id": b"42", REPLAY_COUNT_HEADER: b"1"}++ def test_none_headers_yields_only_replay_count(self) -> None:+ result = build_replay_headers(None, max_replays=2)+ assert result == [(REPLAY_COUNT_HEADER, b"1")]++ @parameterized.expand(+ [+ ("first_replay", 0, 2, b"1"),+ ("second_replay", 1, 2, b"2"),+ ("higher_cap", 3, 5, b"4"),+ ]+ )+ def test_increments_existing_replay_count(+ self, _name: str, current: int, max_replays: int, expected: bytes+ ) -> None:+ headers = [(REPLAY_COUNT_HEADER, str(current).encode("utf-8"))]++ result = build_replay_headers(headers, max_replays=max_replays)++ assert result is not None+ assert dict(result)[REPLAY_COUNT_HEADER] == expected+ assert sum(1 for key, _ in result if key == REPLAY_COUNT_HEADER) == 1++ @parameterized.expand(+ [+ ("at_cap", 2, 2),+ ("over_cap", 5, 2),+ ("zero_cap", 0, 0),+ ]+ )+ def test_returns_none_when_exhausted(self, _name: str, current: int, max_replays: int) -> None:+ headers = [(REPLAY_COUNT_HEADER, str(current).encode("utf-8"))]++ assert build_replay_headers(headers, max_replays=max_replays) is None++ def test_garbage_replay_count_treated_as_zero(self) -> None:+ result = build_replay_headers([(REPLAY_COUNT_HEADER, b"not-a-number")], max_replays=2)++ assert result is not None+ assert dict(result)[REPLAY_COUNT_HEADER] == b"1"+++class FakeMessage:+ def __init__(self, value: bytes, headers: Optional[list[tuple[str, bytes]]] = None) -> None:+ self._value = value+ self._headers = headers++ def error(self) -> None:+ return None++ def headers(self) -> Optional[list[tuple[str, bytes]]]:+ return self._headers++ def value(self) -> bytes:+ return self._value+++class FakeConsumer:+ def __init__(self, batches: list[list[FakeMessage]]) -> None:+ self._batches = list(batches)+ self.commits = 0++ def subscribe(self, _topics: list[str]) -> None:+ pass++ def consume(self, num_messages: int, timeout: float) -> list[FakeMessage]:+ return self._batches.pop(0) if self._batches else []++ def commit(self, asynchronous: bool = True) -> None:+ self.commits += 1++ def close(self) -> None:+ pass+++class FakeProducer:+ def __init__(self, delivery_error: Optional[str] = None) -> None:+ self.delivery_error = delivery_error+ self.produced: list[dict[str, Any]] = []+ self._pending: list[Callable[[Any, Any], None]] = []++ def produce(self, **kwargs: Any) -> None:+ self.produced.append(kwargs)+ self._pending.append(kwargs["on_delivery"])++ def flush(self, timeout: Optional[float] = None) -> int:+ pending, self._pending = self._pending, []+ for callback in pending:+ callback(self.delivery_error, None)+ return 0++ def poll(self, timeout: float) -> int:+ return 0+++class DrainDlqTest(TestCase):+ def _drain(+ self, batches: list[list[FakeMessage]], producer: FakeProducer, **kwargs: Any+ ) -> tuple[dict[str, int], FakeConsumer]:+ consumer = FakeConsumer(batches)+ with (+ patch("posthog.kafka_client.dlq_replay.Consumer", return_value=consumer),+ patch("posthog.kafka_client.dlq_replay.Producer", return_value=producer),+ patch(+ "posthog.kafka_client.dlq_replay.get_profile_settings",+ return_value=SimpleNamespace(+ hosts=["localhost:9092"],+ security_protocol="PLAINTEXT",+ sasl_mechanism=None,+ sasl_user=None,+ sasl_password=None,+ ),+ ),+ ):+ result = drain_dlq(+ source_topic="topic-dlq",+ target_topic="topic",+ group_id="dlq-replay-test",+ log=lambda _message: None,+ **kwargs,+ )+ return result, consumer++ def test_commits_once_per_delivered_batch(self) -> None:+ producer = FakeProducer()+ batch = [FakeMessage(b"one", [("error_name", b"ValueError")]), FakeMessage(b"two")]++ result, consumer = self._drain([batch], producer)++ assert result == {"replayed": 2, "exhausted": 0, "errors": 0}+ assert consumer.commits == 1+ assert [record["value"] for record in producer.produced] == [b"one", b"two"]+ assert dict(producer.produced[0]["headers"]) == {REPLAY_COUNT_HEADER: b"1"}++ def test_delivery_failure_is_reported_and_not_committed(self) -> None:+ producer = FakeProducer(delivery_error="Broker: Message too large")++ result, consumer = self._drain([[FakeMessage(b"one")]], producer)++ assert result == {"replayed": 0, "exhausted": 0, "errors": 1}+ assert consumer.commits == 0++ def test_batch_of_exhausted_messages_still_commits(self) -> None:+ producer = FakeProducer()+ at_cap = [(REPLAY_COUNT_HEADER, b"2")]++ result, consumer = self._drain([[FakeMessage(b"one", at_cap), FakeMessage(b"two", at_cap)]], producer)++ assert result == {"replayed": 0, "exhausted": 2, "errors": 0}+ assert consumer.commits == 1+ assert producer.produced == []++ def test_dry_run_counts_without_producing_or_committing(self) -> None:+ producer = FakeProducer()++ result, consumer = self._drain([[FakeMessage(b"one")]], producer, dry_run=True)++ assert result == {"replayed": 1, "exhausted": 0, "errors": 0}+ assert consumer.commits == 0+ assert producer.produced == []diff --git a/posthog/management/commands/replay_kafka_dlq.py b/posthog/management/commands/replay_kafka_dlq.pynew file mode 100644index 000000000000..0e7de7455004--- /dev/null+++ b/posthog/management/commands/replay_kafka_dlq.py@@ -0,0 +1,45 @@+from argparse import ArgumentParser+from typing import Any++from django.core.management.base import BaseCommand, CommandError++from posthog.kafka_client.dlq_replay import drain_dlq+++class Command(BaseCommand):+ help = "Replay a Kafka DLQ topic back into its target topic using a consumer group."++ def add_arguments(self, parser: ArgumentParser) -> None:+ parser.add_argument("--source-topic", required=True, help="DLQ topic to read from")+ parser.add_argument("--target-topic", required=True, help="Topic to replay messages to")+ parser.add_argument(+ "--group-id",+ default="dlq-replay-ingestion-traces",+ help="Consumer group id; reuse the same id to resume an interrupted run",+ )+ parser.add_argument("--max-replays", type=int, default=2, help="Skip a message replayed this many times")+ parser.add_argument("--batch-size", type=int, default=500, help="Messages to consume per poll")+ parser.add_argument("--idle-polls", type=int, default=2, help="Stop after this many consecutive empty polls")+ parser.add_argument("--poll-timeout-seconds", type=float, default=5.0, help="Seconds to wait per poll")+ parser.add_argument("--bootstrap-servers", default=None, help="Override brokers instead of topic routing")+ parser.add_argument("--security-protocol", default=None, help="Override the security protocol")+ parser.add_argument("--dry-run", action="store_true", help="Count without producing or committing")++ def handle(self, *args: Any, **options: Any) -> None:+ result = drain_dlq(+ source_topic=options["source_topic"],+ target_topic=options["target_topic"],+ group_id=options["group_id"],+ max_replays=options["max_replays"],+ batch_size=options["batch_size"],+ idle_polls=options["idle_polls"],+ poll_timeout_seconds=options["poll_timeout_seconds"],+ dry_run=options["dry_run"],+ bootstrap_servers=options["bootstrap_servers"],+ security_protocol=options["security_protocol"],+ log=lambda message: self.stdout.write(message),+ )+ counts = f"Replayed {result['replayed']}, exhausted {result['exhausted']}, errors {result['errors']}"+ if result["errors"]:+ raise CommandError(f"{counts}. The DLQ is not drained, so rerun with the same --group-id.")+ self.stdout.write(self.style.SUCCESS(counts))