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(workflows): notify teams when their email sending tier changes (#92406)

Meikel Ratz17e1f7c2d63e
diff --git a/docs/internal/workflows-email-sending-tiers.md b/docs/internal/workflows-email-sending-tiers.md
index 123445728a57..f82ee1090b94 100644
--- a/docs/internal/workflows-email-sending-tiers.md
+++ b/docs/internal/workflows-email-sending-tiers.md
@@ -41,6 +41,9 @@ In order: staff suspension or an AWS-paused tenant drops to tier 0; a dirty 7-da
Rates only count on a meaningful denominator; below the complaint floor, the absolute complaint backstop still applies, including in windows with no sends.
Pinned teams never move automatically.
+While the tier is enforced, the sweep notifies teams it moved: a rate demotion sends an in-app notification plus an email to project admins, and an earned promotion sends an in-app notification only.
+Decay, suspension drops, admin recomputes, and the backfill stay silent.
+
## Rollout order
1. Merge and deploy with both modes `off`. The daily sweep starts computing and storing tiers immediately.
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index 3d222a1a27ce..2721ca96b594 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -801,6 +801,36 @@ def send_email_sending_unsuspended(team_id: int, unsuspended_at: str) -> None:
message.send()
+@shared_task(**EMAIL_TASK_KWARGS)
+@with_team_scope()
+def send_email_sending_tier_demoted(team_id: int, per_day: int, per_hour: int, demoted_at: str) -> None:
+ """
+ Tell a project's admins that its workflow email sending limit was lowered for deliverability
+ problems. Admin+ recipients and no notification-setting gate, matching the suspension emails:
+ the limit stays down until someone acts on the list quality.
+ """
+ if not is_email_available(with_absolute_urls=True):
+ return
+ team = Team.objects.get(id=team_id)
+ memberships_to_email = _get_project_admins_to_notify_of_email_sending_suspension(team)
+ if not memberships_to_email:
+ return
+ message = EmailMessage(
+ campaign_key=f"email_sending_tier_demoted_{team_id}_{demoted_at}",
+ subject=f"Workflow email sending limit lowered for project '{team}'",
+ template_name="email_sending_tier_demoted",
+ template_context={
+ "team": team,
+ "per_day": f"{per_day:,}",
+ "per_hour": f"{per_hour:,}",
+ "reputation_path": f"/project/{team.id}/workflows/reputation",
+ },
+ )
+ for membership in memberships_to_email:
+ message.add_user_recipient(membership.user)
+ message.send()
+
+
def send_batch_export_run_failure(
batch_export_run_id: str | UUIDT,
failure_rate: float = 1.0,
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 8f6136f67ec4..27e02e29d3c2 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -37,6 +37,7 @@
'posthog.tasks.email.send_email_change_emails',
'posthog.tasks.email.send_email_sending_reputation_finding',
'posthog.tasks.email.send_email_sending_suspended',
+ 'posthog.tasks.email.send_email_sending_tier_demoted',
'posthog.tasks.email.send_email_sending_unsuspended',
'posthog.tasks.email.send_email_verification_code',
'posthog.tasks.email.send_error_tracking_issue_assigned',
diff --git a/posthog/templates/email/email_sending_tier_demoted.html b/posthog/templates/email/email_sending_tier_demoted.html
new file mode 100644
index 000000000000..3fe2a7c3a0dd
--- /dev/null
+++ b/posthog/templates/email/email_sending_tier_demoted.html
@@ -0,0 +1,31 @@
+{% extends "email/base.html" %}
+{% block heading %}Your workflow email sending limit was lowered{% endblock %}
+{% block section %}
+ <!-- prettier-ignore -->
+ <p>
+ Recent workflow emails from project <b>{{ team }}</b> caused deliverability problems, such as spam complaints or bounced addresses. To protect your sending reputation, we lowered the project's sending limit to <b>{{ per_day }} emails per day</b> ({{ per_hour }} per hour).
+ </p>
+ <p>Your workflows keep running. Emails over the limit are delayed and sent when capacity frees up, not dropped.</p>
+ <p><b>How to get the limit back up</b></p>
+ <ul>
+ <li>Remove old, purchased, or unengaged addresses from your lists.</li>
+ <li>Check the Reputation tab to see which workflows draw the most complaints and bounces.</li>
+ <li>Keep sending clean and keep using your limit. The limit raises again automatically once your recent sending history is healthy.</li>
+ </ul>
+ <div class="mb mt text-center">
+ <a class="button" href="{% absolute_uri reputation_path %}">View sending health</a>
+ </div>
+ <div class="mt">
+ <p>
+ If the button above doesn't work, paste this link into your browser:
+ <br />
+ <a href="{% absolute_uri reputation_path %}">{% absolute_uri reputation_path %}</a>
+ </p>
+ </div>
+{% endblock %}
+{% block footer %}
+ Need help?
+ <a href="https://posthog.com/questions?{{ utm_tags }}" target="_blank"><b>Contact support</b></a>
+ or
+ <a href="https://posthog.com/docs?{{ utm_tags }}" target="_blank"><b>read our documentation</b></a>.
+{% endblock %}
diff --git a/products/workflows/backend/services/email_sending_tier_notifications.py b/products/workflows/backend/services/email_sending_tier_notifications.py
new file mode 100644
index 000000000000..388a0a58414a
--- /dev/null
+++ b/products/workflows/backend/services/email_sending_tier_notifications.py
@@ -0,0 +1,94 @@
+from django.utils import timezone
+
+import structlog
+
+from posthog.tasks.email import send_email_sending_tier_demoted
+
+from products.notifications.backend.facade.api import (
+ NotificationData,
+ NotificationType,
+ Priority,
+ TargetType,
+ create_notification,
+)
+from products.workflows.backend.services.email_sending_tier import RATE_DEMOTION_REASONS, TierDecision
+from products.workflows.backend.utils.email_sending_tiers import get_email_sending_tier_limits, is_tier_enforced
+
+logger = structlog.get_logger(__name__)
+
+
+def notify_email_sending_tier_changes(decisions: list[TierDecision]) -> None:
+ """
+ Tell teams the periodic sweep moved that their sending limit changed.
+
+ Only while the tier is enforced: in "off" and "shadow" the tier changes nothing a customer can
+ observe, so a notification would describe limits that do not apply. Called from the sweep task
+ only, not from the admin recompute or the backfill command: staff usually set tiers while
+ already talking to the customer, and a backfill would notify the whole fleet at once.
+ """
+ if not is_tier_enforced():
+ return
+ for decision in decisions:
+ if not decision.changed:
+ continue
+ # A notification failure must not fail the sweep or the other teams' notifications: the
+ # tier writes are already applied, and the Reputation tab shows the same state.
+ try:
+ if decision.new_tier < decision.previous_tier and decision.reason in RATE_DEMOTION_REASONS:
+ _notify_demotion(decision)
+ elif decision.new_tier > decision.previous_tier and decision.reason == "clean_and_used":
+ _notify_promotion(decision)
+ # Decay ("inactive") and suspension drops stay silent: a dormant team gains nothing
+ # from a limit email, and the suspension flow sends its own notifications.
+ except Exception:
+ logger.exception("workflows_email_tier_change_notification_failed", team_id=decision.team_id)
+
+
+def _notify_demotion(decision: TierDecision) -> None:
+ limits = get_email_sending_tier_limits(decision.new_tier)
+ # The email goes first and each channel gets its own guard: the email reaches the admins who
+ # can act on the demotion, so an in-app publish failure must not take it down with it.
+ try:
+ send_email_sending_tier_demoted.delay(
+ team_id=decision.team_id,
+ per_day=limits.per_day,
+ per_hour=limits.per_hour,
+ demoted_at=timezone.now().isoformat(),
+ )
+ except Exception:
+ logger.exception("workflows_email_tier_demotion_email_dispatch_failed", team_id=decision.team_id)
+ create_notification(
+ NotificationData(
+ team_id=decision.team_id,
+ notification_type=NotificationType.EMAIL_REPUTATION,
+ priority=Priority.NORMAL,
+ title="Workflow email sending limit lowered",
+ body=(
+ f"Recent sends caused deliverability problems, such as spam complaints or bounces, "
+ f"so this project's limit is now {limits.per_day:,} emails per day. "
+ f"Clean sending raises it again. Check the Reputation tab for details."
+ ),
+ target_type=TargetType.TEAM,
+ target_id=str(decision.team_id),
+ source_url="/workflows/reputation",
+ )
+ )
+
+
+def _notify_promotion(decision: TierDecision) -> None:
+ limits = get_email_sending_tier_limits(decision.new_tier)
+ create_notification(
+ NotificationData(
+ team_id=decision.team_id,
+ notification_type=NotificationType.EMAIL_REPUTATION,
+ priority=Priority.NORMAL,
+ title="Workflow email sending limit raised",
+ body=(
+ f"This project earned a higher sending limit: "
+ f"up to {limits.per_day:,} emails per day and {limits.per_hour:,} per hour."
+ ),
+ target_type=TargetType.TEAM,
+ target_id=str(decision.team_id),
+ source_url="/workflows/reputation",
+ )
+ )
diff --git a/products/workflows/backend/tasks/email_sending_tiers.py b/products/workflows/backend/tasks/email_sending_tiers.py
index c1fe5f0a3779..e6fb41a11210 100644
--- a/products/workflows/backend/tasks/email_sending_tiers.py
+++ b/products/workflows/backend/tasks/email_sending_tiers.py
@@ -4,6 +4,7 @@ from celery import shared_task
from posthog.tasks.utils import CeleryQueue
from products.workflows.backend.services.email_sending_tier import recompute_email_sending_tiers
+from products.workflows.backend.services.email_sending_tier_notifications import notify_email_sending_tier_changes
logger = structlog.get_logger(__name__)
@@ -14,6 +15,7 @@ def recompute_workflows_email_sending_tiers() -> None:
clean the sending was. Runs in every rollout mode: tiers are stored before anything reads them,
so enforcement can be switched on against a settled distribution."""
decisions = recompute_email_sending_tiers()
+ notify_email_sending_tier_changes(decisions)
logger.info(
"workflows_email_sending_tier_sweep_finished",
evaluated_teams=len(decisions),
diff --git a/products/workflows/backend/test/test_email_sending_tier_notifications.py b/products/workflows/backend/test/test_email_sending_tier_notifications.py
new file mode 100644
index 000000000000..a32ae4978351
--- /dev/null
+++ b/products/workflows/backend/test/test_email_sending_tier_notifications.py
@@ -0,0 +1,79 @@
+from unittest.mock import patch
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from products.workflows.backend.services.email_sending_tier import TierDecision
+from products.workflows.backend.services.email_sending_tier_notifications import notify_email_sending_tier_changes
+
+NOTIFICATIONS_MODULE = "products.workflows.backend.services.email_sending_tier_notifications"
+
+
+def _demotion(reason: str) -> TierDecision:
+ return TierDecision(team_id=1, previous_tier=3, new_tier=2, reason=reason)
+
+
+def _promotion() -> TierDecision:
+ return TierDecision(team_id=1, previous_tier=2, new_tier=3, reason="clean_and_used")
+
+
+class TestNotifyEmailSendingTierChanges(SimpleTestCase):
+ def setUp(self) -> None:
+ create_patch = patch(f"{NOTIFICATIONS_MODULE}.create_notification")
+ email_patch = patch(f"{NOTIFICATIONS_MODULE}.send_email_sending_tier_demoted")
+ self.create_notification = create_patch.start()
+ self.email_task = email_patch.start()
+ self.addCleanup(create_patch.stop)
+ self.addCleanup(email_patch.stop)
+
+ @parameterized.expand([("off",), ("shadow",)])
+ def test_nothing_fires_until_the_mode_is_enforce(self, mode: str) -> None:
+ with override_settings(WORKFLOWS_EMAIL_TIER_MODE=mode):
+ notify_email_sending_tier_changes([_demotion("rates_above_threshold"), _promotion()])
+ self.create_notification.assert_not_called()
+ self.email_task.delay.assert_not_called()
+
+ @parameterized.expand([("rates_above_threshold",), ("workflow_auto_paused",), ("ses_reputation_high",)])
+ @override_settings(WORKFLOWS_EMAIL_TIER_MODE="enforce")
+ def test_a_rate_demotion_notifies_in_app_and_by_email(self, reason: str) -> None:
+ notify_email_sending_tier_changes([_demotion(reason)])
+ assert self.create_notification.call_count == 1
+ data = self.create_notification.call_args.args[0]
+ assert data.title == "Workflow email sending limit lowered"
+ assert data.team_id == 1
+ assert self.email_task.delay.call_count == 1
+ assert self.email_task.delay.call_args.kwargs["team_id"] == 1
+
+ @override_settings(WORKFLOWS_EMAIL_TIER_MODE="enforce")
+ def test_a_promotion_notifies_in_app_only(self) -> None:
+ notify_email_sending_tier_changes([_promotion()])
+ assert self.create_notification.call_count == 1
+ assert self.create_notification.call_args.args[0].title == "Workflow email sending limit raised"
+ self.email_task.delay.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("inactive", 3, 2),
+ ("ses_tenant_paused", 3, 0),
+ ("staff_suspension", 3, 0),
+ ("demotion_cooldown", 3, 3),
+ ]
+ )
+ @override_settings(WORKFLOWS_EMAIL_TIER_MODE="enforce")
+ def test_decay_suspensions_and_holds_stay_silent(self, reason: str, previous: int, new: int) -> None:
+ notify_email_sending_tier_changes(
+ [TierDecision(team_id=1, previous_tier=previous, new_tier=new, reason=reason)]
+ )
+ self.create_notification.assert_not_called()
+ self.email_task.delay.assert_not_called()
+
+ @override_settings(WORKFLOWS_EMAIL_TIER_MODE="enforce")
+ def test_one_failing_notification_does_not_stop_the_rest(self) -> None:
+ self.create_notification.side_effect = [Exception("kafka down"), None]
+ second = TierDecision(team_id=2, previous_tier=2, new_tier=3, reason="clean_and_used")
+ notify_email_sending_tier_changes([_demotion("rates_above_threshold"), second])
+ assert self.create_notification.call_count == 2
+ assert self.create_notification.call_args.args[0].team_id == 2
+ # The demotion email must survive the in-app failure: it reaches the admins who can act.
+ assert self.email_task.delay.call_count == 1