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(notifications): dispatch alert_firing realtime notifications (#56152)

Yasen80ed79d607ed
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 10d1549c89a2..13bd87220f97 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -41,6 +41,15 @@ from posthog.temporal.alerts.types import (
)
from posthog.temporal.common.heartbeat import Heartbeater
+from products.notifications.backend.facade.api import (
+ NotificationData,
+ NotificationType,
+ Priority,
+ SourceType,
+ TargetType,
+ create_notification,
+)
+
logger = structlog.get_logger(__name__)
@@ -263,6 +272,39 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
return await _evaluate()
+def dispatch_alert_firing_realtime_notification(alert: AlertConfiguration, breaches: list[str]) -> None:
+ """Fan out one realtime in-app notification per subscribed user when an alert fires.
+
+ Exceptions are caught and logged internally so a realtime delivery failure does not
+ poison the email path or the alert-check transaction.
+ """
+ try:
+ body = "; ".join(breaches[:3])
+ if len(breaches) > 3:
+ body += f" (+{len(breaches) - 3} more)"
+ title = f"Alert firing: {alert.name}"[:100]
+ source_url = f"/project/{alert.team.project_id}/insights/{alert.insight.short_id}#alert={alert.id}"
+ for user_id in alert.subscribed_users.values_list("id", flat=True):
+ create_notification(
+ NotificationData(
+ team_id=alert.team_id,
+ notification_type=NotificationType.ALERT_FIRING,
+ priority=Priority.NORMAL,
+ title=title,
+ body=body,
+ 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=SourceType.INSIGHT,
+ source_id=str(alert.insight.short_id),
+ )
+ )
+ except Exception:
+ logger.exception("alerts.realtime_notification_failed", alert_id=str(alert.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
@@ -299,6 +341,11 @@ async def notify_alert(inputs: NotifyAlertActivityInputs) -> None:
# need to dispatch, and the gating path relies on it for idempotency.
AlertCheck.objects.filter(id=alert_check.id).update(notification_sent_at=datetime.now(UTC))
+ # Realtime in-app dispatch sits AFTER record_alert_delivery so a Temporal retry
+ # 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)
+
async with Heartbeater():
await _notify()
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 44607f9dfb54..c22a01a02485 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -509,3 +509,62 @@ class TestNotifyAlert:
# targets_notified stays empty so Temporal retry re-attempts delivery
refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
assert refreshed.targets_notified == {}
+
+ async def test_firing_dispatches_realtime_notification(self, alert_with_user) -> None:
+ check = await _create_alert_check(alert_with_user, state=AlertState.FIRING)
+
+ with (
+ patch(
+ "posthog.tasks.alerts.utils.send_notifications_for_breaches",
+ 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),
+ breaches=["value above threshold"],
+ ),
+ )
+
+ assert mock_create_notification.call_count == 1
+ data = mock_create_notification.call_args.args[0]
+ assert data.notification_type.value == "alert_firing"
+ assert data.team_id == alert_with_user.team_id
+ assert data.resource_type == "insight"
+ assert data.target_type.value == "user"
+ assert data.source_type.value == "insight"
+ assert data.source_id == str(alert_with_user.insight.short_id)
+ assert data.resource_id == str(alert_with_user.insight.short_id)
+ assert data.title.startswith("Alert firing:")
+
+ async def test_realtime_failure_does_not_break_email_path(self, alert_with_user) -> None:
+ check = await _create_alert_check(alert_with_user, state=AlertState.FIRING)
+
+ with (
+ patch(
+ "posthog.tasks.alerts.utils.send_notifications_for_breaches",
+ return_value=["[email protected]"],
+ ) as mock_breaches,
+ patch(
+ "posthog.temporal.alerts.activities.create_notification",
+ side_effect=RuntimeError("kafka down"),
+ ),
+ ):
+ env = ActivityEnvironment()
+ # Must not raise; realtime dispatch swallows errors internally.
+ await env.run(
+ notify_alert,
+ NotifyAlertActivityInputs(
+ alert_id=str(alert_with_user.id),
+ alert_check_id=str(check.id),
+ breaches=["value above threshold"],
+ ),
+ )
+
+ mock_breaches.assert_called_once()
+ refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
+ assert refreshed.targets_notified == {"users": ["[email protected]"]}
diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.py
index 0ba3976f372c..ab8a4b9cd494 100644
--- a/products/notifications/backend/facade/enums.py
+++ b/products/notifications/backend/facade/enums.py
@@ -7,6 +7,7 @@ from posthog.scopes import APIScopeObject
class NotificationType(str, Enum):
COMMENT_MENTION = "comment_mention"
+ ALERT_FIRING = "alert_firing"
class Priority(str, Enum):
diff --git a/products/notifications/backend/migrations/0005_alter_notificationevent_notification_type.py b/products/notifications/backend/migrations/0005_alter_notificationevent_notification_type.py
new file mode 100644
index 000000000000..f6a9af63916c
--- /dev/null
+++ b/products/notifications/backend/migrations/0005_alter_notificationevent_notification_type.py
@@ -0,0 +1,23 @@
+# Generated by Django 5.2.13 on 2026-05-05 08:32
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("notifications", "0004_alter_notificationevent_notification_type"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="notificationevent",
+ name="notification_type",
+ field=models.CharField(
+ choices=[
+ ("comment_mention", "COMMENT_MENTION"),
+ ("alert_firing", "ALERT_FIRING"),
+ ],
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txt
index 88b9410f863b..4d3c8d3ee621 100644
--- a/products/notifications/backend/migrations/max_migration.txt
+++ b/products/notifications/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0004_alter_notificationevent_notification_type
+0005_alter_notificationevent_notification_type