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(alerts): notify users when alert checks fail (#79150)

Matt Pua494ba67c4b3e
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index d8c3f2c3cdf6..fcbb39bf2ce5 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -2,6 +2,7 @@ from collections.abc import Collection
from contextlib import ExitStack
from dataclasses import dataclass
from datetime import UTC, datetime
+from zoneinfo import ZoneInfo
from django.utils import timezone
@@ -10,6 +11,7 @@ import structlog
from posthog.schema import AlertCalculationInterval, AlertState, ChartDisplayType, NodeKind, TrendsQuery
+from posthog.rbac.user_access_control import UserAccessControl
from posthog.slo.context import get_current_slo
from posthog.slo.types import SloOperation
from posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restriction
@@ -244,35 +246,53 @@ def send_test_alert_email(alert: AlertConfiguration, recipients: Collection[str]
)
-def send_notifications_for_errors(alert: AlertConfiguration, error: dict) -> list[str]:
+def send_notifications_for_errors(alert: AlertConfiguration, error: dict, idempotency_key: str) -> list[str]:
logger.info("Sending alert error notifications", alert_id=alert.id, error=error)
- email_targets = alert.get_subscribed_users_emails()
-
- # TODO: uncomment this after checking errors sent
- # if email_targets:
- # subject = f"PostHog alert {alert.name} check failed to evaluate"
- # campaign_key = f"alert-firing-notification-{alert.id}-{timezone.now().timestamp()}"
- # insight_url = f"/project/{alert.team.pk}/insights/{alert.insight.short_id}"
- # alert_url = f"{insight_url}?alert_id={alert.id}"
- # message = EmailMessage(
- # campaign_key=campaign_key,
- # subject=subject,
- # template_name="alert_check_failed_to_evaluate",
- # template_context={
- # "alert_error": error,
- # "insight_url": insight_url,
- # "insight_name": alert.insight.name,
- # "alert_url": alert_url,
- # "alert_name": alert.name,
- # },
- # )
- # for target in email_targets:
- # message.add_recipient(email=target)
- # message.send()
+ email_targets = [email for _, email in get_alert_error_notification_recipients(alert) if email]
+ if not email_targets:
+ return []
+ alert_name = alert.name or "Your alert"
+ subject_alert_name = alert.name or "your alert"
+ error_message = str(error.get("message") or "Unknown error").strip()[:1000] or "Unknown error"
+ insight_url = f"/project/{alert.team.pk}/insights/{alert.insight.short_id}"
+ alert_url = f"{insight_url}?alert_id={alert.id}"
+ send_alert_email(
+ recipients=email_targets,
+ campaign_key=f"alert-evaluation-failed-notification-{idempotency_key}",
+ subject=f"PostHog could not evaluate {subject_alert_name}",
+ template_name="alert_check_failed_to_evaluate",
+ template_context={
+ "alert_error": error_message,
+ "alert_url": alert_url,
+ "alert_name": alert_name,
+ "insight_url": insight_url,
+ "insight_name": alert.insight.name,
+ "next_check_at": alert.next_check_at,
+ },
+ )
return email_targets
+def next_scheduled_check_time(alert: AlertConfiguration) -> str | None:
+ if alert.next_check_at is None:
+ return None
+ return alert.next_check_at.astimezone(ZoneInfo(alert.team.timezone)).strftime("%B %-d, %Y at %-I:%M %p %Z")
+
+
+def get_alert_error_notification_recipients(alert: AlertConfiguration) -> list[tuple[int, str]]:
+ candidates = (
+ alert.team.all_users_with_access()
+ .filter(id__in=alert.subscribed_users.values_list("id", flat=True))
+ .only("id", "email")
+ )
+ return [
+ (user.id, user.email)
+ for user in candidates
+ if UserAccessControl(user, team=alert.team).check_access_level_for_object(alert.insight, "viewer")
+ ]
+
+
def dispatch_alert_notification(
alert: AlertConfiguration,
alert_check: AlertCheck,
@@ -320,7 +340,7 @@ def dispatch_alert_notification(
alert_check_id=alert_check.id,
)
return None
- return send_notifications_for_errors(alert, alert_check.error)
+ return send_notifications_for_errors(alert, alert_check.error, idempotency_key=str(alert_check.id))
case AlertState.FIRING:
if not breaches:
raise ValueError(
diff --git a/posthog/templates/email/alert_check_failed_to_evaluate.html b/posthog/templates/email/alert_check_failed_to_evaluate.html
index d1e412ad8f60..b35a86737fc1 100644
--- a/posthog/templates/email/alert_check_failed_to_evaluate.html
+++ b/posthog/templates/email/alert_check_failed_to_evaluate.html
@@ -1,10 +1,26 @@
-{% extends "email/base.html" %} {% load posthog_assets %} {% block section %}
+{% extends "email/base.html" %} {% load posthog_assets %} {% block heading %}{{ alert_name }}{% endblock %} {% block section %}
<p>
- The <a href="{% absolute_uri alert_url %}">{{ alert_name }}</a> alert failed to evaluate for insight <a
- href="{% absolute_uri insight_url %}">{{ insight_name }}</> with the error, below. There could be something wrong with the alert or the insight config.
+ PostHog could not evaluate this alert. This can happen when the insight or alert settings need attention, or
+ when PostHog has a temporary problem.
+ </p>
+ <p>
+ <strong>Insight</strong><br />
+ <a href="{% absolute_uri insight_url %}">{{ insight_name }}</a>
+ </p>
+ <p>
+ <strong>Error</strong><br />
+ <i>{{ alert_error }}</i>
+ </p>
+ <p>
+ Review the alert settings.
+ {% if next_check_at %}
+ PostHog will try again on {{ next_check_at|date:"F j, Y, g:i A T" }}.
+ {% else %}
+ PostHog will try again at the next scheduled check.
+ {% endif %}
+ If it fails again, contact support.
</p>
- <p><i>{{ alert_error }}</i></p>
<div class="mb mt text-center">
- <a class="button" href="{% absolute_uri alert_url %}">Manage alert</a>
+ <a class="button" href="{% absolute_uri alert_url %}">Review alert</a>
</div>
{% endblock %}{% load posthog_filters %}
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 8be35120928f..de689416c512 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -27,7 +27,9 @@ from posthog.tasks.alerts.utils import (
add_alert_check,
disable_invalid_alert,
dispatch_alert_notification,
+ get_alert_error_notification_recipients,
next_check_time,
+ next_scheduled_check_time,
record_alert_delivery,
skip_because_of_weekend,
)
@@ -232,10 +234,6 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
alert_config_type=(alert.config or {}).get("type"),
)
- # Snapshot before add_alert_check mutates alert.state — needed to detect the
- # NOT_FIRING/ERRORED -> FIRING transition that triggers an investigation.
- previous_state = alert.state
-
value: float | None = None
breaches: list[str] | None = None
error: dict | None = None
@@ -303,6 +301,12 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
should_gate_notification = False
should_run_metrics_investigation = False
with transaction.atomic():
+ alert = (
+ AlertConfiguration.objects.select_for_update(of=("self",))
+ .select_related("insight", "team", "threshold")
+ .get(id=inputs.alert_id)
+ )
+ previous_state = alert.state
alert_check, should_notify = add_alert_check(
alert,
value,
@@ -384,6 +388,52 @@ def dispatch_alert_firing_realtime_notification(alert: AlertConfiguration, breac
logger.exception("alerts.realtime_notification_failed", alert_id=str(alert.id))
+def dispatch_alert_error_in_app_notifications(alert: AlertConfiguration, alert_check: AlertCheck) -> None:
+ """Create one best-effort in-app notification per eligible recipient for an errored check."""
+ error = alert_check.error if isinstance(alert_check.error, dict) else {}
+ error_message = str(error.get("message") or "Unknown error").strip().rstrip(".")[:1000] or "Unknown error"
+ alert_name = alert.name or "Alert"
+ source_url = f"/project/{alert.team_id}/insights/{alert.insight.short_id}?alert_id={alert.id}"
+ next_check_at = next_scheduled_check_time(alert)
+ next_check_message = (
+ f"PostHog will try again on {next_check_at}."
+ if next_check_at
+ else "PostHog will try again at the next scheduled check."
+ )
+
+ for user_id, _ in get_alert_error_notification_recipients(alert):
+ try:
+ create_notification(
+ NotificationData(
+ team_id=alert.team_id,
+ notification_type=NotificationType.PIPELINE_FAILURE,
+ priority=Priority.NORMAL,
+ title=f"{alert_name[:75]} could not be evaluated",
+ body=(
+ f"PostHog could not evaluate this alert: {error_message}. "
+ "This can happen when the insight or alert settings need attention, or when PostHog has a "
+ f"temporary problem. Review the alert settings. {next_check_message} If it fails again, "
+ "contact support."
+ ),
+ target_type=TargetType.USER,
+ target_id=str(user_id),
+ resource_type="insight",
+ resource_id=str(alert.insight.short_id),
+ source_url=source_url,
+ source_type=None,
+ source_id=str(alert_check.id),
+ idempotency_key=f"alert-evaluation-failure:{alert_check.id}:{user_id}",
+ )
+ )
+ except Exception:
+ logger.exception(
+ "alerts.error_realtime_notification_failed",
+ alert_id=str(alert.id),
+ alert_check_id=str(alert_check.id),
+ user_id=user_id,
+ )
+
+
# Idempotency: empty targets_notified = not yet delivered; non-empty = already delivered.
# Lets Temporal retry notify_alert safely after a transient failure past the send.
@temporalio.activity.defn
@@ -393,7 +443,9 @@ async def notify_alert(inputs: NotifyAlertActivityInputs) -> None:
@database_sync_to_async(thread_sensitive=False, executor=_NOTIFICATION_DELIVERY_EXECUTOR)
def _notify() -> None:
# Mismatched pair surfaces as DoesNotExist instead of notifying the wrong alert.
- alert_check = AlertCheck.objects.select_related("alert_configuration", "alert_configuration__team").get(
+ alert_check = AlertCheck.objects.select_related(
+ "alert_configuration", "alert_configuration__team", "alert_configuration__insight"
+ ).get(
pk=inputs.alert_check_id,
alert_configuration_id=inputs.alert_id,
)
@@ -424,6 +476,8 @@ async def notify_alert(inputs: NotifyAlertActivityInputs) -> None:
# past this point sees `targets_notified` populated and skips the whole _notify.
if alert_check.state == AlertState.FIRING.value and inputs.breaches:
dispatch_alert_firing_realtime_notification(alert, inputs.breaches)
+ elif alert_check.state == AlertState.ERRORED.value:
+ dispatch_alert_error_in_app_notifications(alert, alert_check)
async with Heartbeater():
await _notify()
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 48694c4054f6..5da4aee20fe4 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -25,7 +25,11 @@ from posthog.constants import AvailableFeature
from posthog.exceptions import ClickHouseAtCapacity
from posthog.models import User
from posthog.slo.types import SloOperation, SloOutcome
-from posthog.tasks.alerts.utils import AlertEvaluationResult
+from posthog.tasks.alerts.utils import (
+ AlertEvaluationResult,
+ get_alert_error_notification_recipients,
+ send_notifications_for_errors,
+)
from posthog.temporal.alerts.activities import cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alert
from posthog.temporal.alerts.types import (
EvaluateAlertActivityInputs,
@@ -558,8 +562,13 @@ class TestNotifyAlert:
)
async def test_sends_error_notifications_when_errored(self, alert_with_user) -> None:
+ next_check_at = datetime(2026, 8, 12, 14, 30, tzinfo=UTC)
+ await sync_to_async(AlertConfiguration.objects.filter(pk=alert_with_user.pk).update)(
+ next_check_at=next_check_at
+ )
+ alert_with_user.next_check_at = next_check_at
check = await _create_alert_check(
- alert_with_user, state=AlertState.ERRORED, error={"message": "boom", "traceback": "..."}
+ alert_with_user, state=AlertState.ERRORED, error={"message": "boom.", "traceback": "..."}
)
with (
@@ -568,6 +577,7 @@ class TestNotifyAlert:
"posthog.tasks.alerts.utils.send_notifications_for_errors",
return_value=["[email protected]"],
) as mock_errors,
+ patch("posthog.temporal.alerts.activities.create_notification") as mock_create_notification,
):
env = ActivityEnvironment()
await env.run(
@@ -577,6 +587,96 @@ class TestNotifyAlert:
mock_errors.assert_called_once()
mock_breaches.assert_not_called()
+ assert mock_errors.call_args.kwargs["idempotency_key"] == str(check.id)
+ notification = mock_create_notification.call_args.args[0]
+ assert notification.notification_type.value == "pipeline_failure"
+ assert notification.priority.value == "normal"
+ subscriber_id = await sync_to_async(lambda: alert_with_user.subscribed_users.get().id)()
+ assert notification.target_id == str(subscriber_id)
+ assert notification.resource_id == str(alert_with_user.insight.short_id)
+ assert notification.source_id == str(check.id)
+ assert notification.source_type is None
+ assert (
+ notification.source_url
+ == f"/project/{alert_with_user.team_id}/insights/{alert_with_user.insight.short_id}?alert_id={alert_with_user.id}"
+ )
+ assert "boom. This can happen" in notification.body
+ assert "boom.." not in notification.body
+ assert "when PostHog has a temporary problem" in notification.body
+ assert "Review the alert settings" in notification.body
+ assert "PostHog will try again on August 12, 2026 at 2:30 PM UTC" in notification.body
+ assert "contact support" in notification.body
+
+ refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
+ assert refreshed.targets_notified == {"users": ["[email protected]"]}
+
+ @pytest.mark.parametrize("message", [None, "", " "])
+ async def test_error_notification_uses_fallback_for_missing_reason(self, alert_with_user, message) -> None:
+ check = await _create_alert_check(alert_with_user, state=AlertState.ERRORED, error={"message": message})
+
+ with (
+ patch(
+ "posthog.tasks.alerts.utils.send_notifications_for_errors",
+ return_value=["[email protected]"],
+ ),
+ patch("posthog.temporal.alerts.activities.create_notification") as mock_create_notification,
+ ):
+ env = ActivityEnvironment()
+ await env.run(
+ notify_alert,
+ NotifyAlertActivityInputs(alert_id=str(alert_with_user.id), alert_check_id=str(check.id)),
+ )
+
+ notification = mock_create_notification.call_args.args[0]
+ assert "Unknown error" in notification.body
+ assert "None" not in notification.body
+
+ async def test_error_email_includes_next_scheduled_check(self, alert_with_user) -> None:
+ next_check_at = datetime(2026, 8, 12, 14, 30, tzinfo=UTC)
+ await sync_to_async(AlertConfiguration.objects.filter(pk=alert_with_user.pk).update)(
+ next_check_at=next_check_at
+ )
+ alert_with_user.next_check_at = next_check_at
+
+ with patch("posthog.tasks.alerts.utils.send_alert_email") as mock_send_alert_email:
+ recipients = await sync_to_async(send_notifications_for_errors)(
+ alert_with_user, {"message": "boom"}, "notification-key"
+ )
+
+ subscriber_email = await sync_to_async(lambda: alert_with_user.subscribed_users.get().email)()
+ assert recipients == [subscriber_email]
+ assert mock_send_alert_email.call_args.kwargs["template_context"]["next_check_at"] == next_check_at
+
+ async def test_error_notification_does_not_include_an_unsubscribed_creator(self, alert, auser) -> None:
+ await sync_to_async(AlertConfiguration.objects.filter(pk=alert.id).update)(created_by_id=auser.id)
+ recipients = await sync_to_async(get_alert_error_notification_recipients)(alert)
+
+ assert recipients == []
+
+ async def test_error_notification_excludes_subscriber_without_insight_access(self, alert_with_user) -> None:
+ with patch(
+ "posthog.tasks.alerts.utils.UserAccessControl.check_access_level_for_object",
+ return_value=False,
+ ):
+ recipients = await sync_to_async(get_alert_error_notification_recipients)(alert_with_user)
+
+ assert recipients == []
+
+ async def test_error_realtime_notification_failure_does_not_block_recording_delivery(self, alert_with_user) -> None:
+ check = await _create_alert_check(alert_with_user, state=AlertState.ERRORED, error={"message": "boom"})
+
+ with (
+ patch(
+ "posthog.tasks.alerts.utils.send_notifications_for_errors",
+ return_value=["[email protected]"],
+ ),
+ patch("posthog.temporal.alerts.activities.create_notification", side_effect=RuntimeError("kafka down")),
+ ):
+ env = ActivityEnvironment()
+ await env.run(
+ notify_alert,
+ NotifyAlertActivityInputs(alert_id=str(alert_with_user.id), alert_check_id=str(check.id)),
+ )
refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
assert refreshed.targets_notified == {"users": ["[email protected]"]}
diff --git a/products/alerts/backend/insight_alert_state_machine.py b/products/alerts/backend/insight_alert_state_machine.py
index 55ba838e6318..414dd90416cc 100644
--- a/products/alerts/backend/insight_alert_state_machine.py
+++ b/products/alerts/backend/insight_alert_state_machine.py
@@ -28,7 +28,7 @@ if TYPE_CHECKING:
INSIGHT_ALERT_POLICY = AlertPolicy(
max_consecutive_failures=None,
- notify_error_on_every_failure=True,
+ notify_error_on_every_failure=False,
renotify_while_firing=True,
notify_resolve=False,
errors_set_errored_state=True,
@@ -41,7 +41,7 @@ def snapshot_from_alert(alert: AlertConfiguration) -> AlertSnapshot:
cooldown=timedelta(0),
last_notified_at=alert.last_notified_at,
snooze_until=alert.snoozed_until,
- consecutive_failures=0,
+ consecutive_failures=1 if alert.state == InsightAlertState.ERRORED else 0,
)
diff --git a/products/alerts/backend/test/test_email_notifications.py b/products/alerts/backend/test/test_email_notifications.py
index b79a2d153c00..0784e266cace 100644
--- a/products/alerts/backend/test/test_email_notifications.py
+++ b/products/alerts/backend/test/test_email_notifications.py
@@ -59,3 +59,30 @@ def test_alert_firing_email_labels_test_delivery_without_claiming_the_alert_is_f
assert "This is a test delivery" in html
assert "alert is firing" not in html
+
+
+def test_alert_evaluation_failure_email_includes_the_reason_and_next_check_timing() -> None:
+ html = render_to_string(
+ "email/alert_check_failed_to_evaluate.html",
+ {
+ "alert_error": "The query could not run.",
+ "alert_url": "/project/1/insights/example?alert_id=1",
+ "alert_name": "Example alert",
+ "insight_url": "/project/1/insights/example",
+ "insight_name": "Example insight",
+ },
+ )
+
+ assert "The query could not run." in html
+ assert "PostHog could not evaluate this alert." in html
+ assert "PostHog has a temporary problem" in html
+ assert "Insight" in html
+ assert "Error" in html
+ assert "Review the alert settings" in html
+ assert "PostHog will try again" in html
+ assert "next scheduled check" in html
+ assert "contact" in html
+ assert "support" in html
+ assert "Review alert" in html
+ assert "alert_id=1" in html
+ assert "Example insight" in html
diff --git a/products/alerts/backend/test/test_insight_alert_state_machine.py b/products/alerts/backend/test/test_insight_alert_state_machine.py
index 98270798f64d..351dcd870ed5 100644
--- a/products/alerts/backend/test/test_insight_alert_state_machine.py
+++ b/products/alerts/backend/test/test_insight_alert_state_machine.py
@@ -44,13 +44,24 @@ def test_clear_check_resolves_without_notification() -> None:
assert not should_notify(outcome)
-def test_error_enters_errored_without_broken_escalation() -> None:
- alert = alert_with_state(InsightAlertState.ERRORED)
+def test_error_notifies_once_until_a_successful_check_resets_the_streak() -> None:
+ alert = alert_with_state(InsightAlertState.NOT_FIRING)
- for _ in range(10):
- outcome = evaluate_alert_check(alert, threshold_breached=False, error_message="query failed", now=NOW)
- assert outcome.new_state == AlertState.ERRORED
- assert should_notify(outcome)
+ first_failure = evaluate_alert_check(alert, threshold_breached=False, error_message="query failed", now=NOW)
+ assert first_failure.new_state == AlertState.ERRORED
+ assert should_notify(first_failure)
+
+ alert.state = InsightAlertState.ERRORED
+ repeated_failure = evaluate_alert_check(alert, threshold_breached=False, error_message="query failed", now=NOW)
+ assert repeated_failure.new_state == AlertState.ERRORED
+ assert not should_notify(repeated_failure)
+
+ recovery = evaluate_alert_check(alert, threshold_breached=False, error_message=None, now=NOW)
+ assert recovery.new_state == AlertState.NOT_FIRING
+
+ alert.state = InsightAlertState.NOT_FIRING
+ new_failure = evaluate_alert_check(alert, threshold_breached=False, error_message="query failed", now=NOW)
+ assert should_notify(new_failure)
def test_control_plane_transitions_use_shared_outcomes() -> None:
diff --git a/products/notifications/backend/facade/contracts.py b/products/notifications/backend/facade/contracts.py
index e92bae31e8ae..b665a8fe189b 100644
--- a/products/notifications/backend/facade/contracts.py
+++ b/products/notifications/backend/facade/contracts.py
@@ -33,3 +33,4 @@ class NotificationData:
priority: Priority = Priority.NORMAL
metadata: dict[str, Any] | None = None
resolver: RecipientsResolver | None = field(default=None, compare=False)
+ idempotency_key: str | None = None
diff --git a/products/notifications/backend/logic.py b/products/notifications/backend/logic.py
index d80a4d110564..aded51f81700 100644
--- a/products/notifications/backend/logic.py
+++ b/products/notifications/backend/logic.py
@@ -202,25 +202,36 @@ def create_notification(data: NotificationData) -> NotificationEvent | None:
)
return None
- event = NotificationEvent.objects.create(
- organization=organization,
- team=team,
- notification_type=data.notification_type,
- priority=data.priority,
- title=data.title,
- body=data.body,
- resource_type=data.resource_type.value
+ event_data = {
+ "organization": organization,
+ "team": team,
+ "notification_type": data.notification_type,
+ "priority": data.priority,
+ "title": data.title,
+ "body": data.body,
+ "resource_type": data.resource_type.value
if isinstance(data.resource_type, NotificationOnlyResourceType)
else data.resource_type,
- resource_id=data.resource_id,
- source_url=data.source_url,
- source_type=data.source_type,
- source_id=data.source_id,
- target_type=data.target_type,
- target_id=data.target_id,
- resolved_user_ids=resolved_user_ids,
- metadata=data.metadata,
- )
+ "resource_id": data.resource_id,
+ "source_url": data.source_url,
+ "source_type": data.source_type,
+ "source_id": data.source_id,
+ "target_type": data.target_type,
+ "target_id": data.target_id,
+ "resolved_user_ids": resolved_user_ids,
+ "metadata": data.metadata,
+ }
+ if data.idempotency_key:
+ event, created = NotificationEvent.objects.get_or_create(
+ organization_id=organization.id,
+ team_id=data.team_id,
+ idempotency_key=data.idempotency_key,
+ defaults=event_data,
+ )
+ if not created:
+ return event
+ else:
+ event = NotificationEvent.objects.create(**event_data)
def _on_commit() -> None:
_publish_to_kafka(event)
diff --git a/products/notifications/backend/migrations/0022_add_notification_idempotency_key.py b/products/notifications/backend/migrations/0022_add_notification_idempotency_key.py
new file mode 100644
index 000000000000..24adb14774b1
--- /dev/null
+++ b/products/notifications/backend/migrations/0022_add_notification_idempotency_key.py
@@ -0,0 +1,28 @@
+# Generated by Django 5.2.17 on 2026-08-07 16:39
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("notifications", "0021_alter_notificationevent_notification_type"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddField(
+ model_name="notificationevent",
+ name="idempotency_key",
+ field=models.CharField(blank=True, max_length=128, null=True),
+ ),
+ ],
+ database_operations=[
+ migrations.AddField(
+ model_name="notificationevent",
+ name="idempotency_key",
+ field=models.CharField(blank=True, max_length=128, null=True),
+ ),
+ ],
+ ),
+ ]
diff --git a/products/notifications/backend/migrations/0023_add_notification_idempotency_key_index.py b/products/notifications/backend/migrations/0023_add_notification_idempotency_key_index.py
new file mode 100644
index 000000000000..c97b01f48cc5
--- /dev/null
+++ b/products/notifications/backend/migrations/0023_add_notification_idempotency_key_index.py
@@ -0,0 +1,50 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("notifications", "0022_add_notification_idempotency_key"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddConstraint(
+ model_name="notificationevent",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("idempotency_key__isnull", False), ("team__isnull", False)),
+ fields=("team", "idempotency_key"),
+ name="notification_event_team_idempotency_key_uniq",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="notificationevent",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("idempotency_key__isnull", False), ("team__isnull", True)),
+ fields=("organization", "idempotency_key"),
+ name="notification_event_organization_idempotency_key_uniq",
+ ),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="notification_event_team_idempotency_key_uniq",
+ table_name="notifications_notificationevent",
+ columns="(team_id, idempotency_key) WHERE idempotency_key IS NOT NULL AND team_id IS NOT NULL",
+ unique=True,
+ ),
+ CreateIndexConcurrently(
+ index_name="notification_event_organization_idempotency_key_uniq",
+ table_name="notifications_notificationevent",
+ columns=(
+ "(organization_id, idempotency_key) WHERE idempotency_key IS NOT NULL AND team_id IS NULL"
+ ),
+ unique=True,
+ ),
+ ],
+ ),
+ ]
diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txt
index 3e86d8e2fc48..e37adfd027e7 100644
--- a/products/notifications/backend/migrations/max_migration.txt
+++ b/products/notifications/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0021_alter_notificationevent_notification_type
+0023_add_notification_idempotency_key_index
diff --git a/products/notifications/backend/models.py b/products/notifications/backend/models.py
index 334950d5673c..85a9bb7c844b 100644
--- a/products/notifications/backend/models.py
+++ b/products/notifications/backend/models.py
@@ -17,6 +17,7 @@ class NotificationEvent(UUIDModel):
source_url = models.CharField(max_length=512, blank=True, default="")
source_type = models.CharField(max_length=64, null=True, blank=True)
source_id = models.CharField(max_length=64, null=True, blank=True)
+ idempotency_key = models.CharField(max_length=128, null=True, blank=True)
target_type = models.CharField(max_length=16, choices=[(t.value, t.name) for t in TargetType])
target_id = models.CharField(max_length=64)
resolved_user_ids = models.JSONField(default=list)
@@ -25,6 +26,18 @@ class NotificationEvent(UUIDModel):
class Meta:
ordering = ["-created_at"]
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "idempotency_key"],
+ condition=models.Q(idempotency_key__isnull=False, team__isnull=False),
+ name="notification_event_team_idempotency_key_uniq",
+ ),
+ models.UniqueConstraint(
+ fields=["organization", "idempotency_key"],
+ condition=models.Q(idempotency_key__isnull=False, team__isnull=True),
+ name="notification_event_organization_idempotency_key_uniq",
+ ),
+ ]
indexes = [
models.Index(fields=["organization", "-created_at"]),
]
diff --git a/products/notifications/backend/tests/test_logic.py b/products/notifications/backend/tests/test_logic.py
index 3ff59bae868c..000d79ee60d6 100644
--- a/products/notifications/backend/tests/test_logic.py
+++ b/products/notifications/backend/tests/test_logic.py
@@ -49,6 +49,50 @@ class TestCreateNotification(BaseTest):
assert event.notification_type == "comment_mention"
assert NotificationEvent.objects.count() == 1
+ @patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.notifications.backend.logic._publish_to_kafka")
+ def test_create_notification_deduplicates_idempotency_key(self, mock_publish, mock_ff):
+ data = NotificationData(
+ team_id=self.team.id,
+ notification_type=NotificationType.COMMENT_MENTION,
+ title="Test notification",
+ body="Test body",
+ target_type=TargetType.USER,
+ target_id=str(self.user.id),
+ idempotency_key="test-notification",
+ )
+
+ with self.captureOnCommitCallbacks(execute=True):
+ first = create_notification(data)
+ with self.captureOnCommitCallbacks(execute=True):
+ second = create_notification(data)
+
+ assert first is not None
+ assert second is not None
+ assert second.id == first.id
+ assert NotificationEvent.objects.count() == 1
+ mock_publish.assert_called_once()
+
+ @patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.notifications.backend.logic._publish_to_kafka")
+ def test_create_notification_scopes_idempotency_key_to_team(self, mock_publish, mock_ff):
+ second_team = Team.objects.create(organization=self.organization, name="Second team")
+
+ for team in (self.team, second_team):
+ create_notification(
+ NotificationData(
+ team_id=team.id,
+ notification_type=NotificationType.COMMENT_MENTION,
+ title="Test notification",
+ body="Test body",
+ target_type=TargetType.USER,
+ target_id=str(self.user.id),
+ idempotency_key="shared-key",
+ )
+ )
+
+ assert NotificationEvent.objects.filter(idempotency_key="shared-key").count() == 2
+
@patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)
@patch("products.notifications.backend.logic._publish_to_kafka")
def test_create_notification_for_organization(self, mock_publish, mock_ff):