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): size email reputation windows to each sender's own volume (#73465)

Meikel Ratz651026ac6ac5
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index b96425c9a6fb..913b503df0bd 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -181,6 +181,7 @@ export type CdpConfig = ClickhouseConfig & {
// Email reputation evaluator (daily Temporal-scheduled bounce/complaint snapshots for workflows email)
EMAIL_REPUTATION_EVALUATION_HOUR_UTC: number
EMAIL_REPUTATION_TARGET_VOLUME: number
+ EMAIL_REPUTATION_VOLUME_MULTIPLIER: number
EMAIL_REPUTATION_MIN_WINDOW_HOURS: number
EMAIL_REPUTATION_LOOKBACK_DAYS: number
EMAIL_REPUTATION_MIN_SENDS: number
@@ -348,10 +349,13 @@ export function getDefaultCdpConfig(): CdpConfig {
// Thresholds sit ahead of AWS SES's review lines (5% bounce / 0.1% complaint at ~0.5%
// escalation). Rates are computed SES-style over a window spanning at least
- // MIN_WINDOW_HOURS and at least TARGET_VOLUME sends — whichever reaches further back
- // (capped at LOOKBACK_DAYS). Calculation only for now — enforcement ships separately.
+ // MIN_WINDOW_HOURS and at least the target's representative volume of sends —
+ // max(TARGET_VOLUME, VOLUME_MULTIPLIER × its biggest sending day) — whichever reaches
+ // further back (capped at LOOKBACK_DAYS). Calculation only for now — enforcement
+ // ships separately.
EMAIL_REPUTATION_EVALUATION_HOUR_UTC: 6,
EMAIL_REPUTATION_TARGET_VOLUME: 1000,
+ EMAIL_REPUTATION_VOLUME_MULTIPLIER: 3,
EMAIL_REPUTATION_MIN_WINDOW_HOURS: 24,
EMAIL_REPUTATION_LOOKBACK_DAYS: 30,
EMAIL_REPUTATION_MIN_SENDS: DEFAULT_THRESHOLDS.minSends,
diff --git a/nodejs/src/cdp/services/email-reputation/email-reputation.service.test.ts b/nodejs/src/cdp/services/email-reputation/email-reputation.service.test.ts
index 5a285e68e175..344b3f702ac2 100644
--- a/nodejs/src/cdp/services/email-reputation/email-reputation.service.test.ts
+++ b/nodejs/src/cdp/services/email-reputation/email-reputation.service.test.ts
@@ -8,8 +8,8 @@ import { PostgresUse } from '~/common/utils/db/postgres'
import { createTeam, getTeam, resetTestDatabase } from '~/tests/helpers/sql'
import { Hub } from '~/types'
-import { DEFAULT_THRESHOLDS } from './classifier'
-import { EmailReputationService } from './email-reputation.service'
+import { DEFAULT_THRESHOLDS, ReputationMetrics } from './classifier'
+import { EmailReputationService, representativeVolume } from './email-reputation.service'
import { HourlyEmailMetricsRow } from './types'
const EVALUATED_AT = '2026-07-10T06:00:00.000Z'
@@ -88,10 +88,13 @@ describe('EmailReputationService', () => {
const team = await getTeam(hub.postgres, 2)
teamId = await createTeam(hub.postgres, team!.organization_id)
mockClickhouse = { query: jest.fn() }
+ // multiplier 1 keeps these tests pinning the pure window-walk mechanics (representative
+ // volume = the fixed target); the multiplier's own sizing behavior has its own block below.
service = new EmailReputationService(mockClickhouse as any, hub.postgres, {
targetVolume: 1000,
minWindowHours: 24,
lookbackDays: 30,
+ representativeVolumeMultiplier: 1,
thresholds: DEFAULT_THRESHOLDS,
})
})
@@ -262,4 +265,83 @@ describe('EmailReputationService', () => {
const teamRows = (await getSnapshots()).filter((r) => r.hog_flow_id === null)
expect(teamRows.at(-1)).toMatchObject({ state: 'insufficient_data', emails_sent: '0' })
})
+
+ describe('representative volume sizing (multiplier 3, the default)', () => {
+ const buckets = (rows: [hoursAgo: number, sent: number][]): Map<number, ReputationMetrics> =>
+ new Map(rows.map(([hoursAgo, sent]) => [HOURS_AGO(hoursAgo), { sent, bounced: 0, complained: 0 }]))
+
+ it.each([
+ ['floor wins for tiny senders', buckets([[2, 200]]), 1000],
+ ['multiplier times the biggest day wins for bigger senders', buckets([[2, 5000]]), 15000],
+ [
+ // Anchoring on the biggest single day (not an average) is what keeps a bursty
+ // sender's window spanning multiple campaigns: this sender's daily average is
+ // well under one batch, and average-based sizing would collapse the window.
+ 'bursty sender sizes from the biggest day, not the average',
+ buckets([
+ [2, 10000],
+ [26, 100],
+ [50, 100],
+ ]),
+ 30000,
+ ],
+ ['no sends at all falls back to the floor', new Map(), 1000],
+ [
+ 'a day of only late-arriving bounces contributes zero volume',
+ new Map([[HOURS_AGO(2), { sent: 0, bounced: 50, complained: 0 }]]),
+ 1000,
+ ],
+ ])('%s', (_name, input: Map<number, ReputationMetrics>, expected: number) => {
+ expect(representativeVolume(input, 1000, 3)).toEqual(expected)
+ })
+
+ let scaledService: EmailReputationService
+ beforeEach(() => {
+ scaledService = new EmailReputationService(mockClickhouse as any, hub.postgres, {
+ targetVolume: 1000,
+ minWindowHours: 24,
+ lookbackDays: 30,
+ representativeVolumeMultiplier: 3,
+ thresholds: DEFAULT_THRESHOLDS,
+ })
+ })
+
+ it('one clean campaign cannot wash out yesterday`s disaster', async () => {
+ const flow = await insertEmailFlow()
+ // Yesterday: 1000-send batch at 50% hard bounce. Today: a clean 1000-send batch.
+ // With a fixed 1000-send window today's batch alone would fill it and report 0%
+ // healthy — a false all-clear on the exact signal enforcement decisions use. The
+ // representative volume (3 × the 1000-send max day = 3000) keeps reaching back.
+ mockMetrics([
+ { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(26), sent: 1000, bounced: 500, complained: 0 },
+ { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(2), sent: 1000, bounced: 0, complained: 0 },
+ ])
+
+ await scaledService.evaluateTeamBatch([teamId], EVALUATED_AT)
+
+ const teamRow = (await getSnapshots()).find((r) => r.hog_flow_id === null)
+ // 500 bounced / 2000 sent = 25% — still critical, decaying by dilution not amnesia
+ expect(teamRow).toMatchObject({ state: 'critical', emails_sent: '2000' })
+ expect(teamRow.bounce_rate).toBeCloseTo(0.25)
+ })
+
+ it('a weekly batch sender`s window spans its last batches across silent days', async () => {
+ const flow = await insertEmailFlow()
+ // 10k batch last Monday at 6% bounce, clean 10k batch today, nothing in between.
+ // The representative volume is 3 × 10k: sized from the biggest day, the window
+ // reaches across the silent week to the previous batch instead of judging this
+ // sender on today's single clean campaign.
+ mockMetrics([
+ { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(170), sent: 10000, bounced: 600, complained: 0 },
+ { teamId, appSourceId: flow.id, hourBucket: HOURS_AGO(2), sent: 10000, bounced: 0, complained: 0 },
+ ])
+
+ await scaledService.evaluateTeamBatch([teamId], EVALUATED_AT)
+
+ const teamRow = (await getSnapshots()).find((r) => r.hog_flow_id === null)
+ // 600 / 20000 = 3% — warning: last week's bad batch still counts, diluted by the clean one
+ expect(teamRow).toMatchObject({ state: 'warning', emails_sent: '20000' })
+ expect(teamRow.bounce_rate).toBeCloseTo(0.03)
+ })
+ })
})
diff --git a/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts b/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts
index 77e8fcf0b992..ba5b19750a2c 100644
--- a/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts
+++ b/nodejs/src/cdp/services/email-reputation/email-reputation.service.ts
@@ -22,14 +22,18 @@ interface HogFlowRow {
}
export interface EmailReputationServiceConfig {
- /** Each target's window must contain at least this many sends (SES-style
- * "representative volume") — small senders' windows stretch back until it's met. */
+ /** Floor for each target's representative volume — small senders' windows stretch back
+ * (up to the lookback) until at least this many sends are covered. */
targetVolume: number
/** ...and must span at least this many hours — so a high-volume sender is judged on at
* least a full day of mail, not just the newest buckets that happen to reach the volume. */
minWindowHours: number
/** How far back to scan for that volume. Bounded by app_metrics2's 90-day TTL. */
lookbackDays: number
+ /** Scales each target's representative volume to its own sending scale:
+ * volume = max(targetVolume, multiplier × its biggest sending day in the lookback).
+ * This is what makes the window span multiple campaigns — see representativeVolume(). */
+ representativeVolumeMultiplier: number
thresholds: ReputationThresholds
}
@@ -49,12 +53,15 @@ interface SnapshotRow {
* posthog_emailreputationsnapshot, so the table doubles as a time series for trend dashboards.
*
* Rates are volume-based, mirroring how AWS SES judges the shared sending account: each target's
- * bounce/complaint rate covers at least its most recent `targetVolume` sends AND at least the
- * last `minWindowHours` — whichever reaches further back (walking hourly buckets backwards from
- * the evaluation time, capped at `lookbackDays`). A weekly batch blast keeps counting until
- * enough newer volume dilutes it, and a high-volume sender can't bury a bad morning under a few
- * clean recent hours. Because each window ends at evaluation time, bounces that arrive hours
- * after their send are picked up by the next run automatically.
+ * bounce/complaint rate covers at least its most recent representative volume of sends AND at
+ * least the last `minWindowHours` — whichever reaches further back (walking hourly buckets
+ * backwards from the evaluation time, capped at `lookbackDays`). The representative volume is
+ * sized to the target's own scale — `max(targetVolume, multiplier × its biggest sending day)` —
+ * so the window always spans multiple typical campaigns: a weekly batch blast keeps counting
+ * until enough newer batches dilute it (one clean batch can't wash it out), and a high-volume
+ * sender can't bury a bad morning under a few clean recent hours. Because each window ends at
+ * evaluation time, bounces that arrive hours after their send are picked up by the next run
+ * automatically.
*
* Runs as Temporal activities: the workflow fetches the team list once, then evaluates teams in
* paced batches. All rows of a run share the workflow's `evaluatedAt`, and inserts are
@@ -146,7 +153,7 @@ export class EmailReputationService {
const minWindowStart = Math.floor(Date.parse(evaluatedAt) / 1000) - this.config.minWindowHours * 3600
// Per-workflow: fold each source's hourly buckets into its workflow, then take each
- // workflow's window (>= minWindowHours and >= targetVolume sends).
+ // workflow's window (>= minWindowHours and >= its representative volume of sends).
const workflowBuckets = new Map<string, Map<number, ReputationMetrics>>()
for (const row of rows) {
const flowId = sourceToFlow.get(row.appSourceId)
@@ -167,7 +174,7 @@ export class EmailReputationService {
if (!flow) {
continue
}
- const totals = accumulateRecentVolume(buckets, this.config.targetVolume, minWindowStart)
+ const totals = accumulateRecentVolume(buckets, this.representativeVolume(buckets), minWindowStart)
const { state, bounceRate, complaintRate } = classifyReputation(totals, this.config.thresholds)
snapshots.push({
teamId: flow.team_id,
@@ -194,7 +201,7 @@ export class EmailReputationService {
// via a recent nonzero snapshot, so record an explicit "no recent volume" row rather
// than leaving a stale rate presented as current.
const totals = buckets
- ? accumulateRecentVolume(buckets, this.config.targetVolume, minWindowStart)
+ ? accumulateRecentVolume(buckets, this.representativeVolume(buckets), minWindowStart)
: { sent: 0, bounced: 0, complained: 0 }
const { state, bounceRate, complaintRate } = classifyReputation(totals, this.config.thresholds)
snapshots.push({
@@ -338,6 +345,10 @@ export class EmailReputationService {
return new Map(result.rows.map((row) => [row.id, row]))
}
+ private representativeVolume(buckets: Map<number, ReputationMetrics>): number {
+ return representativeVolume(buckets, this.config.targetVolume, this.config.representativeVolumeMultiplier)
+ }
+
/** Returns true if a row was written, false if it already existed (retry dedupe). */
private async insertSnapshot(snapshot: SnapshotRow, evaluatedAt: string): Promise<boolean> {
const result = await this.postgres.query(
@@ -381,6 +392,34 @@ function addBucket(buckets: Map<number, ReputationMetrics>, row: HourlyEmailMetr
buckets.set(row.hourBucket, acc)
}
+/**
+ * Sizes a target's representative volume from its own sending scale, mirroring AWS SES's stated
+ * principle that rates are computed over "representative volume" sized to limit the influence of
+ * any single campaign:
+ *
+ * volume = max(floor, multiplier × biggest sending day in the buckets)
+ *
+ * Anchoring on the biggest single day (rather than an average) is what makes bursty senders
+ * work: a weekly 10k batch sender averages ~1.4k/day — under one campaign — but their max day
+ * is 10k, so their window spans their last `multiplier` batches. The guarantee this buys: no
+ * single day can contribute more than 1/multiplier of the window, so one clean campaign can
+ * never fully wash out yesterday's disaster, and redemption means sending `multiplier` clean
+ * campaigns. Days are UTC calendar days, matching the daily evaluation cadence.
+ */
+export function representativeVolume(
+ buckets: Map<number, ReputationMetrics>,
+ floor: number,
+ multiplier: number
+): number {
+ const sentByDay = new Map<number, number>()
+ for (const [hour, bucket] of buckets) {
+ const day = Math.floor(hour / 86400)
+ sentByDay.set(day, (sentByDay.get(day) ?? 0) + bucket.sent)
+ }
+ const maxDaily = Math.max(0, ...sentByDay.values())
+ return Math.max(floor, multiplier * maxDaily)
+}
+
/**
* Walk hourly buckets (keyed by epoch seconds) newest-first. Every bucket at or after
* `minWindowStart` is included unconditionally — a high-volume sender is judged on at least that
diff --git a/nodejs/src/cdp/services/email-reputation/temporal/email-reputation-worker.service.ts b/nodejs/src/cdp/services/email-reputation/temporal/email-reputation-worker.service.ts
index e1110e484aec..a7b1c8604c91 100644
--- a/nodejs/src/cdp/services/email-reputation/temporal/email-reputation-worker.service.ts
+++ b/nodejs/src/cdp/services/email-reputation/temporal/email-reputation-worker.service.ts
@@ -99,6 +99,7 @@ export class EmailReputationWorkerService {
targetVolume: this.config.EMAIL_REPUTATION_TARGET_VOLUME,
minWindowHours: this.config.EMAIL_REPUTATION_MIN_WINDOW_HOURS,
lookbackDays: this.config.EMAIL_REPUTATION_LOOKBACK_DAYS,
+ representativeVolumeMultiplier: this.config.EMAIL_REPUTATION_VOLUME_MULTIPLIER,
thresholds: {
minSends: this.config.EMAIL_REPUTATION_MIN_SENDS,
bounceWarning: this.config.EMAIL_REPUTATION_BOUNCE_WARNING_RATE,