Skip to content

: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.

feat(kafka): add team skip, rate limit, and graceful stop to DLQ replay (#94428)

Frank Hamand4361b1949964
diff --git a/posthog/kafka_client/dlq_replay.py b/posthog/kafka_client/dlq_replay.py
index fea3c5d17d65..03cc837cae58 100644
--- a/posthog/kafka_client/dlq_replay.py
+++ b/posthog/kafka_client/dlq_replay.py
@@ -1,12 +1,17 @@
+import time
from collections.abc import Callable, Sequence
from typing import Any, Optional, cast
-from confluent_kafka import Consumer, Producer
+from confluent_kafka import Consumer, KafkaError, KafkaException, Producer
from posthog.kafka_client.routing import get_profile_settings
Header = tuple[str, bytes]
+# The logs/traces ingestion consumer records the resolved team on every quarantined
+# message, so a replay can read past a team's records without reproducing them.
+TEAM_ID_HEADER = "team_id"
+
# 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(
@@ -24,6 +29,20 @@ DLQ_DIAGNOSTIC_HEADERS = frozenset(
# left on the DLQ instead of cycling between the two topics.
REPLAY_COUNT_HEADER = "dlq_replay_count"
+# Commit failures that mean this batch's partitions moved to another group member. The new
+# owner re-reads from the last committed offset, so the run can carry on. Any other commit
+# failure left the offsets where they were, so the run must stop instead of reporting a
+# drain it did not achieve.
+REBALANCE_COMMIT_ERRORS = frozenset(
+ {
+ KafkaError.REBALANCE_IN_PROGRESS, # type: ignore[attr-defined]
+ KafkaError.UNKNOWN_MEMBER_ID, # type: ignore[attr-defined]
+ KafkaError.ILLEGAL_GENERATION, # type: ignore[attr-defined]
+ KafkaError._STATE, # type: ignore[attr-defined]
+ KafkaError._NO_OFFSET, # type: ignore[attr-defined]
+ }
+)
+
def _replay_count(headers: Sequence[Header]) -> int:
for key, value in headers:
@@ -35,6 +54,57 @@ def _replay_count(headers: Sequence[Header]) -> int:
return 0
+def _team_id(headers: Sequence[Header]) -> Optional[int]:
+ for key, value in headers:
+ if key == TEAM_ID_HEADER:
+ try:
+ return int(value.decode("utf-8"))
+ except (ValueError, UnicodeDecodeError):
+ return None
+ return None
+
+
+def _throttle_delay(produced: int, max_messages_per_second: Optional[float], elapsed_seconds: float) -> float:
+ """Seconds to wait so the produce rate stays at or below max_messages_per_second.
+
+ Zero when no limit is set, nothing was produced, or the batch already took longer
+ than the budget for its size.
+ """
+ if not max_messages_per_second or produced <= 0:
+ return 0.0
+ target_seconds = produced / max_messages_per_second
+ return max(0.0, target_seconds - elapsed_seconds)
+
+
+def _sleep_until(deadline: float, should_stop: Callable[[], bool], slice_seconds: float = 0.5) -> None:
+ """Sleep until deadline, in slices, and return early once should_stop is true.
+
+ A rate-limit wait can run for many seconds. One sleep call for the full wait would hold
+ a stop signal until it expires, past the termination grace period of the pod.
+ """
+ while not should_stop():
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return
+ time.sleep(min(slice_seconds, remaining))
+
+
+def classify_message(
+ raw_headers: Optional[Sequence[Header]], skip_team_ids: frozenset[int], max_replays: int
+) -> tuple[str, Optional[list[Header]]]:
+ """Decide what to do with a DLQ message: skip, exhausted, or replay.
+
+ Returns the replay headers only for "replay"; the other outcomes leave the message
+ on the DLQ and carry no headers.
+ """
+ if skip_team_ids and _team_id(raw_headers or []) in skip_team_ids:
+ return "skip", None
+ headers = build_replay_headers(raw_headers, max_replays)
+ if headers is None:
+ return "exhausted", None
+ return "replay", headers
+
+
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.
@@ -85,6 +155,10 @@ def drain_dlq(
dry_run: bool = False,
bootstrap_servers: Optional[str] = None,
security_protocol: Optional[str] = None,
+ skip_team_ids: frozenset[int] = frozenset(),
+ max_messages_per_second: Optional[float] = None,
+ unassigned_timeout_seconds: float = 60.0,
+ should_stop: Callable[[], bool] = lambda: False,
log: Callable[[str], None] = print,
) -> dict[str, int]:
"""Drain a Kafka DLQ topic back into its target topic using a consumer group.
@@ -95,6 +169,13 @@ def drain_dlq(
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.
+
+ Records whose team is in skip_team_ids are read past without reproducing, so their
+ offsets advance but they stay on the DLQ. max_messages_per_second caps the produce
+ rate. should_stop is polled between batches so a caller can stop the run after the
+ current batch commits, rather than abandoning it mid-flight. A run that holds no
+ partitions for unassigned_timeout_seconds gives up, so a spare member of an
+ over-subscribed group exits instead of polling forever.
"""
source = get_profile_settings(topic=source_topic)
target = get_profile_settings(topic=target_topic)
@@ -132,6 +213,7 @@ def drain_dlq(
replayed = 0
exhausted = 0
+ skipped = 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
@@ -145,14 +227,34 @@ def drain_dlq(
try:
consumer.subscribe([source_topic])
idle = 0
+ unassigned_since: Optional[float] = None
while True:
+ if should_stop():
+ log("stop requested; exiting after the last committed batch")
+ break
+
+ batch_started = time.monotonic()
messages = consumer.consume(num_messages=batch_size, timeout=poll_timeout_seconds)
if not messages:
+ # An empty poll while the group holds no partitions is a rebalance in
+ # progress, not a drained topic. Only count idle polls once we have an
+ # assignment, so a run that starts alongside others does not exit early.
+ # A group with more members than partitions leaves one member with no
+ # assignment for good, so bound that wait rather than poll forever.
+ if not consumer.assignment():
+ if unassigned_since is None:
+ unassigned_since = time.monotonic()
+ if time.monotonic() - unassigned_since >= unassigned_timeout_seconds:
+ log(f"no partitions assigned after {unassigned_timeout_seconds}s; exiting")
+ break
+ continue
+ unassigned_since = None
idle += 1
if idle >= idle_polls:
break
continue
idle = 0
+ unassigned_since = None
delivery_failures.clear()
produced_in_batch = 0
@@ -164,12 +266,15 @@ def drain_dlq(
continue
raw_headers = cast(Optional[list[Header]], message.headers())
- headers = build_replay_headers(raw_headers, max_replays)
- if headers is None:
+ action, headers = classify_message(raw_headers, skip_team_ids, max_replays)
+ if action == "skip":
+ skipped += 1
+ continue
+ if action == "exhausted":
exhausted += 1
continue
- if dry_run or producer is None:
+ if dry_run or producer is None or headers is None:
replayed += 1
continue
@@ -185,18 +290,38 @@ def drain_dlq(
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)
+ # that all skipped or hit max_replays would otherwise hold the group behind
+ # it and the lag would never reach zero.
+ try:
+ consumer.commit(asynchronous=False)
+ except KafkaException as commit_error:
+ if _commit_error_code(commit_error) not in REBALANCE_COMMIT_ERRORS:
+ errors += 1
+ log(f"commit failed; stopping so the batch is not counted as drained: {commit_error}")
+ break
+ # A rebalance can revoke this batch's partitions before the commit
+ # lands. The new owner re-reads from the last committed offset, so drop
+ # the commit and keep going rather than crash the run.
+ log(f"commit skipped after a rebalance; records will be re-read: {commit_error}")
- log(f"progress: replayed={replayed} exhausted={exhausted} errors={errors}")
+ delay = _throttle_delay(produced_in_batch, max_messages_per_second, time.monotonic() - batch_started)
+ if delay > 0:
+ _sleep_until(time.monotonic() + delay, should_stop)
+
+ log(f"progress: replayed={replayed} exhausted={exhausted} skipped={skipped} 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}
+ log(f"done: replayed={replayed} exhausted={exhausted} skipped={skipped} errors={errors} dry_run={dry_run}")
+ return {"replayed": replayed, "exhausted": exhausted, "skipped": skipped, "errors": errors}
+
+
+def _commit_error_code(error: KafkaException) -> Optional[int]:
+ if not error.args or not isinstance(error.args[0], KafkaError):
+ return None
+ return error.args[0].code()
def _produce(
diff --git a/posthog/kafka_client/test/test_dlq_replay.py b/posthog/kafka_client/test/test_dlq_replay.py
index 269ee7188737..798414b68098 100644
--- a/posthog/kafka_client/test/test_dlq_replay.py
+++ b/posthog/kafka_client/test/test_dlq_replay.py
@@ -1,3 +1,4 @@
+import time
from collections.abc import Callable
from types import SimpleNamespace
from typing import Any, Optional
@@ -5,9 +6,19 @@ from typing import Any, Optional
from unittest import TestCase
from unittest.mock import patch
+from confluent_kafka import KafkaError, KafkaException
from parameterized import parameterized
-from posthog.kafka_client.dlq_replay import REPLAY_COUNT_HEADER, build_replay_headers, drain_dlq
+from posthog.kafka_client.dlq_replay import (
+ REPLAY_COUNT_HEADER,
+ _sleep_until,
+ _throttle_delay,
+ build_replay_headers,
+ drain_dlq,
+)
+
+REBALANCE_IN_PROGRESS = KafkaError.REBALANCE_IN_PROGRESS # type: ignore[attr-defined]
+TIMED_OUT = KafkaError._TIMED_OUT # type: ignore[attr-defined]
class BuildReplayHeadersTest(TestCase):
@@ -86,8 +97,15 @@ class FakeMessage:
class FakeConsumer:
- def __init__(self, batches: list[list[FakeMessage]]) -> None:
+ def __init__(
+ self,
+ batches: list[list[FakeMessage]],
+ assignments: Optional[list[list[str]]] = None,
+ commit_error: Optional[Exception] = None,
+ ) -> None:
self._batches = list(batches)
+ self._assignments = list(assignments) if assignments is not None else None
+ self._commit_error = commit_error
self.commits = 0
def subscribe(self, _topics: list[str]) -> None:
@@ -96,8 +114,15 @@ class FakeConsumer:
def consume(self, num_messages: int, timeout: float) -> list[FakeMessage]:
return self._batches.pop(0) if self._batches else []
+ def assignment(self) -> list[str]:
+ if self._assignments is None:
+ return ["tp"]
+ return self._assignments.pop(0) if self._assignments else []
+
def commit(self, asynchronous: bool = True) -> None:
self.commits += 1
+ if self._commit_error is not None:
+ raise self._commit_error
def close(self) -> None:
pass
@@ -125,9 +150,13 @@ class FakeProducer:
class DrainDlqTest(TestCase):
def _drain(
- self, batches: list[list[FakeMessage]], producer: FakeProducer, **kwargs: Any
+ self,
+ batches: list[list[FakeMessage]],
+ producer: FakeProducer,
+ consumer: Optional[FakeConsumer] = None,
+ **kwargs: Any,
) -> tuple[dict[str, int], FakeConsumer]:
- consumer = FakeConsumer(batches)
+ consumer = consumer or FakeConsumer(batches)
with (
patch("posthog.kafka_client.dlq_replay.Consumer", return_value=consumer),
patch("posthog.kafka_client.dlq_replay.Producer", return_value=producer),
@@ -157,7 +186,7 @@ class DrainDlqTest(TestCase):
result, consumer = self._drain([batch], producer)
- assert result == {"replayed": 2, "exhausted": 0, "errors": 0}
+ assert result == {"replayed": 2, "exhausted": 0, "skipped": 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"}
@@ -167,7 +196,7 @@ class DrainDlqTest(TestCase):
result, consumer = self._drain([[FakeMessage(b"one")]], producer)
- assert result == {"replayed": 0, "exhausted": 0, "errors": 1}
+ assert result == {"replayed": 0, "exhausted": 0, "skipped": 0, "errors": 1}
assert consumer.commits == 0
def test_batch_of_exhausted_messages_still_commits(self) -> None:
@@ -176,7 +205,7 @@ class DrainDlqTest(TestCase):
result, consumer = self._drain([[FakeMessage(b"one", at_cap), FakeMessage(b"two", at_cap)]], producer)
- assert result == {"replayed": 0, "exhausted": 2, "errors": 0}
+ assert result == {"replayed": 0, "exhausted": 2, "skipped": 0, "errors": 0}
assert consumer.commits == 1
assert producer.produced == []
@@ -185,6 +214,109 @@ class DrainDlqTest(TestCase):
result, consumer = self._drain([[FakeMessage(b"one")]], producer, dry_run=True)
- assert result == {"replayed": 1, "exhausted": 0, "errors": 0}
+ assert result == {"replayed": 1, "exhausted": 0, "skipped": 0, "errors": 0}
assert consumer.commits == 0
assert producer.produced == []
+
+ def test_skips_configured_team_ids_without_producing_but_still_commits(self) -> None:
+ producer = FakeProducer()
+ batch = [
+ FakeMessage(b"keep", [("team_id", b"1")]),
+ FakeMessage(b"drop", [("team_id", b"2")]),
+ ]
+
+ result, consumer = self._drain([batch], producer, skip_team_ids=frozenset({2}))
+
+ assert result == {"replayed": 1, "exhausted": 0, "skipped": 1, "errors": 0}
+ assert consumer.commits == 1
+ assert [record["value"] for record in producer.produced] == [b"keep"]
+
+ def test_stop_exits_after_committing_the_current_batch(self) -> None:
+ producer = FakeProducer()
+ calls = {"n": 0}
+
+ def should_stop() -> bool:
+ calls["n"] += 1
+ return calls["n"] >= 2
+
+ result, consumer = self._drain(
+ [[FakeMessage(b"first")], [FakeMessage(b"second")]], producer, should_stop=should_stop
+ )
+
+ assert result["replayed"] == 1
+ assert consumer.commits == 1
+ assert [record["value"] for record in producer.produced] == [b"first"]
+
+ @parameterized.expand(
+ [
+ ("waits_out_the_join_rebalance", [[], [], [FakeMessage(b"one")]], [[], [], ["tp"], ["tp"]], 60.0, 1),
+ ("gives_up_when_never_assigned", [], [], 0.0, 0),
+ ]
+ )
+ def test_empty_polls_without_an_assignment(
+ self,
+ _name: str,
+ batches: list[list[FakeMessage]],
+ assignments: list[list[str]],
+ unassigned_timeout_seconds: float,
+ expected_replayed: int,
+ ) -> None:
+ producer = FakeProducer()
+ consumer = FakeConsumer(batches=batches, assignments=assignments)
+
+ result, _ = self._drain(
+ [],
+ producer,
+ consumer=consumer,
+ idle_polls=2,
+ unassigned_timeout_seconds=unassigned_timeout_seconds,
+ )
+
+ assert result["replayed"] == expected_replayed
+
+ @parameterized.expand(
+ [
+ ("rebalance_keeps_going", REBALANCE_IN_PROGRESS, 0, [b"one", b"two"]),
+ ("other_failure_stops_the_run", TIMED_OUT, 1, [b"one"]),
+ ]
+ )
+ def test_commit_failure(self, _name: str, code: int, expected_errors: int, expected_produced: list[bytes]) -> None:
+ producer = FakeProducer()
+ consumer = FakeConsumer(
+ [[FakeMessage(b"one")], [FakeMessage(b"two")]],
+ commit_error=KafkaException(KafkaError(code)),
+ )
+
+ result, _ = self._drain([], producer, consumer=consumer)
+
+ assert result["errors"] == expected_errors
+ assert [record["value"] for record in producer.produced] == expected_produced
+
+
+class SleepUntilTest(TestCase):
+ def test_stops_sleeping_once_a_stop_is_requested(self) -> None:
+ calls = {"n": 0}
+
+ def should_stop() -> bool:
+ calls["n"] += 1
+ return calls["n"] > 2
+
+ with patch("posthog.kafka_client.dlq_replay.time.sleep") as sleep:
+ _sleep_until(time.monotonic() + 30.0, should_stop, slice_seconds=0.01)
+
+ assert sleep.call_count == 2
+
+
+class ThrottleDelayTest(TestCase):
+ @parameterized.expand(
+ [
+ ("no_limit", 10, None, 0.5, 0.0),
+ ("nothing_produced", 0, 100.0, 0.0, 0.0),
+ ("already_slower_than_budget", 10, 100.0, 0.5, 0.0),
+ ("needs_to_wait", 10, 100.0, 0.02, 0.08),
+ ]
+ )
+ def test_throttle_delay(
+ self, _name: str, produced: int, rate: Optional[float], elapsed: float, expected: float
+ ) -> None:
+ self.assertAlmostEqual(_throttle_delay(produced, rate, elapsed), expected, places=6)
diff --git a/posthog/management/commands/replay_kafka_dlq.py b/posthog/management/commands/replay_kafka_dlq.py
index 0e7de7455004..fe8c0a508e45 100644
--- a/posthog/management/commands/replay_kafka_dlq.py
+++ b/posthog/management/commands/replay_kafka_dlq.py
@@ -1,3 +1,4 @@
+import signal
from argparse import ArgumentParser
from typing import Any
@@ -6,6 +7,10 @@ from django.core.management.base import BaseCommand, CommandError
from posthog.kafka_client.dlq_replay import drain_dlq
+def _parse_team_ids(raw: str) -> frozenset[int]:
+ return frozenset(int(part) for part in raw.split(",") if part.strip())
+
+
class Command(BaseCommand):
help = "Replay a Kafka DLQ topic back into its target topic using a consumer group."
@@ -23,9 +28,29 @@ class Command(BaseCommand):
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(
+ "--skip-team-ids",
+ type=_parse_team_ids,
+ default=frozenset(),
+ help="Comma-separated team ids to read past without replaying; they stay on the DLQ",
+ )
+ parser.add_argument(
+ "--max-messages-per-second",
+ type=float,
+ default=None,
+ help="Cap the replay produce rate; unset means no limit",
+ )
parser.add_argument("--dry-run", action="store_true", help="Count without producing or committing")
def handle(self, *args: Any, **options: Any) -> None:
+ stop_requested = {"value": False}
+
+ def request_stop(_signum: int, _frame: Any) -> None:
+ stop_requested["value"] = True
+
+ signal.signal(signal.SIGTERM, request_stop)
+ signal.signal(signal.SIGINT, request_stop)
+
result = drain_dlq(
source_topic=options["source_topic"],
target_topic=options["target_topic"],
@@ -37,9 +62,15 @@ class Command(BaseCommand):
dry_run=options["dry_run"],
bootstrap_servers=options["bootstrap_servers"],
security_protocol=options["security_protocol"],
+ skip_team_ids=options["skip_team_ids"],
+ max_messages_per_second=options["max_messages_per_second"],
+ should_stop=lambda: stop_requested["value"],
log=lambda message: self.stdout.write(message),
)
- counts = f"Replayed {result['replayed']}, exhausted {result['exhausted']}, errors {result['errors']}"
+ counts = (
+ f"Replayed {result['replayed']}, exhausted {result['exhausted']}, "
+ f"skipped {result['skipped']}, 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))