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.

fix(session): emit risk telemetry once per anomaly, not per request (#69685)

Tom Piccirello157cc7203610
diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.py
index 8d8613891bfb..7cee920751e2 100644
--- a/posthog/models/activity_logging/signal_handlers.py
+++ b/posthog/models/activity_logging/signal_handlers.py
@@ -848,6 +848,10 @@ def post_login(sender, user, request: HttpRequest, **kwargs):
# fresh password/2FA/SSO login satisfies TimeSensitiveActionPermission.
request.session[settings.SESSION_LAST_REAUTH_AT_KEY] = time.time()
request.session.pop(settings.SESSION_STEP_UP_REQUIRED_KEY, None)
+ # Clear the risk-telemetry dedup markers so the first anomaly after this (re)login re-emits instead
+ # of being suppressed by the pre-login signature. Pairs with the baseline reset below.
+ request.session.pop(settings.SESSION_RISK_LAST_SIG_KEY, None)
+ request.session.pop(settings.SESSION_RISK_LAST_EMIT_AT_KEY, None)
# Defensive risk-baseline reset: login() rotates the session key, so the new row's risk columns
# are already NULL and this is normally a no-op. It guarantees a clean baseline after a high-tier
diff --git a/posthog/session/risk.py b/posthog/session/risk.py
index 8767010d8670..9e3e0202a886 100644
--- a/posthog/session/risk.py
+++ b/posthog/session/risk.py
@@ -6,6 +6,7 @@ from typing import Optional
from django.conf import settings
from django.contrib.auth import BACKEND_SESSION_KEY
+from django.contrib.sessions.backends.base import SessionBase
from django.http import HttpRequest
from django.utils import timezone
@@ -187,6 +188,32 @@ def advance_baseline(session_key: str, baseline: Baseline, ctx: Context, *, now:
)
+def _risk_signature(tier: RiskTier, signals: set[RiskSignal]) -> str:
+ """Identity of an anomaly for dedup purposes: its tier + the set of signals that produced it. An
+ escalation (new/added signal, higher tier) is a new incident; the same signals flapping is not."""
+ return f"{tier.name}:{','.join(sorted(signal.value for signal in signals))}"
+
+
+def _should_emit_risk(session: SessionBase, tier: RiskTier, signals: set[RiskSignal], *, now: datetime) -> bool:
+ """Dedup gate. A flagged session is re-scored on every request; without this it would emit
+ telemetry and re-assert step-up every time, inflating counts and hammering the session store.
+
+ Returns True (and records the signature + timestamp on the session) only when the anomaly's
+ signature differs from the last emitted one or the re-emit cooldown has elapsed, so a persistent
+ anomaly surfaces once per window instead of once per request. Never touches the baseline, so
+ detection integrity is unaffected: the request is still scored the same next time.
+ """
+ signature = _risk_signature(tier, signals)
+ last_signature = session.get(settings.SESSION_RISK_LAST_SIG_KEY)
+ last_emit_at = session.get(settings.SESSION_RISK_LAST_EMIT_AT_KEY) or 0.0
+ now_epoch = now.timestamp()
+ if signature == last_signature and (now_epoch - last_emit_at) < settings.RISK_REEMIT_COOLDOWN_S:
+ return False
+ session[settings.SESSION_RISK_LAST_SIG_KEY] = signature
+ session[settings.SESSION_RISK_LAST_EMIT_AT_KEY] = now_epoch
+ return True
+
+
def evaluate_session_risk(request: HttpRequest) -> RiskTier:
"""Per-request risk orchestrator. Returns the *effective* tier the middleware should act on.
@@ -225,31 +252,46 @@ def evaluate_session_risk(request: HttpRequest) -> RiskTier:
effective = RiskTier.NONE
enforced = False
+ needs_step_up = False
if tier == RiskTier.HIGH and flags.session_end:
effective = RiskTier.HIGH
enforced = True
elif tier >= RiskTier.MEDIUM and flags.step_up:
# Step-up is a side effect gated elsewhere; the middleware does not short-circuit on it. This
# also catches a HIGH detection when session_end is off but step_up is on (graceful degradation).
+ needs_step_up = True
+ enforced = True
+
+ # `effective` is computed above and returned regardless, so session-end is never suppressed.
+ should_emit = _should_emit_risk(request.session, tier, signals, now=now)
+
+ # Enforcement is independent of the telemetry dedup: apply step-up whenever it is needed and not
+ # already set, even when the identical anomaly's telemetry is being deduped. Otherwise enabling
+ # step-up mid-session would leave an already-flagged session unenforced until the cooldown expires.
+ set_step_up = needs_step_up and not request.session.get(settings.SESSION_STEP_UP_REQUIRED_KEY)
+ if set_step_up:
request.session[settings.SESSION_STEP_UP_REQUIRED_KEY] = True
- # Persist now rather than relying on SessionMiddleware, which skips save() on a 5xx response —
- # otherwise a server error on this request would silently drop the step-up requirement.
+
+ # Persist the step-up flag and/or the dedup markers _should_emit_risk just wrote, now rather than
+ # relying on SessionMiddleware, which skips save() on a 5xx response — otherwise a server error
+ # here would drop the step-up requirement.
+ if should_emit or set_step_up:
request.session.save()
- enforced = True
- # Telemetry must never break the request: a capture failure here would otherwise 500 an
- # otherwise-valid authenticated request from the request-phase middleware.
- try:
- posthoganalytics.capture(
- distinct_id=str(user.distinct_id),
- event="session_risk_detected",
- properties={
- "signals": sorted(signal.value for signal in signals),
- "tier": tier.name,
- "enforced": enforced,
- },
- )
- except Exception:
- logger.exception("session_risk telemetry capture failed")
+ if should_emit:
+ # Telemetry must never break the request: a capture failure here would otherwise 500 an
+ # otherwise-valid authenticated request from the request-phase middleware.
+ try:
+ posthoganalytics.capture(
+ distinct_id=str(user.distinct_id),
+ event="session_risk_detected",
+ properties={
+ "signals": sorted(signal.value for signal in signals),
+ "tier": tier.name,
+ "enforced": enforced,
+ },
+ )
+ except Exception:
+ logger.exception("session_risk telemetry capture failed")
return effective
diff --git a/posthog/session/test/test_risk_middleware.py b/posthog/session/test/test_risk_middleware.py
index 7c3707cc1d26..56054ac28b04 100644
--- a/posthog/session/test/test_risk_middleware.py
+++ b/posthog/session/test/test_risk_middleware.py
@@ -12,6 +12,7 @@ from django.test import RequestFactory, override_settings
from django.utils import timezone
from loginas import settings as la_settings
+from parameterized import parameterized
from posthog.models import User
from posthog.session.middleware import SessionRiskMiddleware
@@ -154,6 +155,61 @@ class TestEvaluateSessionRisk(BaseTest):
self.assertEqual(evaluate_session_risk(request), RiskTier.NONE)
self.assertTrue(request.session.get("step_up_required"))
+ @parameterized.expand([("within_cooldown", 3600.0, 1), ("cooldown_elapsed", 0.0, 2)])
+ def test_persistent_anomaly_emits_once_per_cooldown(self, _name, cooldown, expected_calls):
+ # A flagged session is re-scored on every request; the same anomaly must emit once per cooldown
+ # window, not once per request (the bug that inflated per-user counts into the hundreds).
+ request = self._authed_request_with_baseline(self._make_user())
+ with (
+ override_settings(RISK_REEMIT_COOLDOWN_S=cooldown),
+ patch("posthog.session.risk.current_request_context", return_value=UA_CHANGE_CTX),
+ patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, True, False)),
+ patch("posthog.session.risk.posthoganalytics.capture") as mock_capture,
+ ):
+ evaluate_session_risk(request)
+ evaluate_session_risk(request)
+ self.assertEqual(mock_capture.call_count, expected_calls)
+
+ @patch("posthog.session.risk.posthoganalytics.capture")
+ @patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, True, True))
+ def test_new_signature_re_emits_within_cooldown(self, _flags, mock_capture):
+ # An escalation to a different anomaly (MEDIUM ua_change -> HIGH impossible travel) is a new
+ # incident and must re-emit even inside the cooldown window.
+ request = self._authed_request_with_baseline(self._make_user())
+ with patch("posthog.session.risk.current_request_context", return_value=UA_CHANGE_CTX):
+ evaluate_session_risk(request)
+ with patch("posthog.session.risk.current_request_context", return_value=IMPOSSIBLE_TRAVEL_CTX):
+ evaluate_session_risk(request)
+ self.assertEqual(mock_capture.call_count, 2)
+
+ @patch("posthog.session.risk.current_request_context", return_value=IMPOSSIBLE_TRAVEL_CTX)
+ @patch("posthog.session.risk.posthoganalytics.capture")
+ @patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, False, True))
+ def test_dedup_suppresses_telemetry_not_session_end(self, _flags, mock_capture, _ctx):
+ # Dedup gates only the emit, never the acted-on tier: a repeated HIGH request within the
+ # cooldown still returns HIGH so the middleware ends the session.
+ request = self._authed_request_with_baseline(self._make_user())
+ first = evaluate_session_risk(request)
+ second = evaluate_session_risk(request)
+ self.assertEqual(first, RiskTier.HIGH)
+ self.assertEqual(second, RiskTier.HIGH)
+ mock_capture.assert_called_once()
+
+ @patch("posthog.session.risk.current_request_context", return_value=UA_CHANGE_CTX)
+ @patch("posthog.session.risk.posthoganalytics.capture")
+ def test_step_up_applied_when_enabled_after_report_only(self, mock_capture, _ctx):
+ # Enabling step-up mid-session must enforce an already-flagged session even though the
+ # identical anomaly's telemetry is deduped within the cooldown: enforcement is independent
+ # of the emit gate, otherwise a rollout flip leaves flagged sessions unenforced for an hour.
+ request = self._authed_request_with_baseline(self._make_user())
+ with patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, False, False)):
+ evaluate_session_risk(request) # report-only: emits telemetry, sets no step-up
+ self.assertNotIn("step_up_required", request.session)
+ with patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, True, False)):
+ evaluate_session_risk(request) # step-up now enabled, same anomaly within cooldown
+ self.assertTrue(request.session.get("step_up_required"))
+ mock_capture.assert_called_once() # telemetry stays deduped
+
@patch("posthog.session.risk.current_request_context", return_value=IMPOSSIBLE_TRAVEL_CTX)
@patch("posthog.session.risk.posthoganalytics.capture")
@patch("posthog.session.risk.risk_flags", return_value=RiskFlags(True, True, True))
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index a271f62e2312..e4a1f18f918d 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -339,6 +339,11 @@ SESSION_RISK_ENABLED = get_from_env("SESSION_RISK_ENABLED", not TEST, type_cast=
# one source of truth, like SESSION_COOKIE_CREATED_AT_KEY above.
SESSION_STEP_UP_REQUIRED_KEY = get_from_env("SESSION_STEP_UP_REQUIRED_KEY", "step_up_required")
SESSION_LAST_REAUTH_AT_KEY = get_from_env("SESSION_LAST_REAUTH_AT_KEY", "last_reauth_at")
+# Dedup state for risk telemetry/enforcement: the last-emitted anomaly signature and when. A flagged
+# session is re-scored every request, but we only re-emit/re-enforce on a new signature or after the
+# cooldown, so one persistent anomaly can't fire on every request. Cleared on (re)login by post_login.
+SESSION_RISK_LAST_SIG_KEY = get_from_env("SESSION_RISK_LAST_SIG_KEY", "risk_last_sig")
+SESSION_RISK_LAST_EMIT_AT_KEY = get_from_env("SESSION_RISK_LAST_EMIT_AT_KEY", "risk_last_emit_at")
# Impossible-travel risk thresholds (see posthog/session/risk.py). Tunable without a code change.
RISK_DISTANCE_FLOOR_KM = get_from_env("RISK_DISTANCE_FLOOR_KM", 500.0, type_cast=float)
@@ -347,6 +352,10 @@ RISK_VELOCITY_MAX_KMH = get_from_env("RISK_VELOCITY_MAX_KMH", 1000.0, type_cast=
# How often a low-risk request refreshes the known-good baseline snapshot (geo/UA + baseline_at).
# Throttles the per-request write; the baseline geo lags by at most this interval, fine for scoring.
RISK_BASELINE_REFRESH_S = get_from_env("RISK_BASELINE_REFRESH_S", 300.0, type_cast=float)
+# How long the same anomaly signature stays deduped before it re-emits telemetry / re-asserts step-up.
+# Bounds a persistent anomaly to one detection per window instead of one per request, while still
+# resurfacing a long-lived anomaly periodically.
+RISK_REEMIT_COOLDOWN_S = get_from_env("RISK_REEMIT_COOLDOWN_S", 3600.0, type_cast=float)
PROJECT_SWITCHING_TOKEN_ALLOWLIST = get_list(os.getenv("PROJECT_SWITCHING_TOKEN_ALLOWLIST", "sTMFPsFhdP1Ssg"))