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): cap marketing messages per person across all workflows (#109843)

Harley Alexander4be6f6333d1f
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 495f7dee5948..d9811c027fee 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -1740,6 +1740,20 @@ export interface TeamWorkflowsConfigApi {
* @nullable
*/
default_email_integration_id?: number | null
+ /**
+ * Most marketing messages one person can get in the window, across all workflows. Set this together with marketing_frequency_cap_window_days. Set both to null to turn the cap off.
+ * @minimum 1
+ * @maximum 1000
+ * @nullable
+ */
+ marketing_frequency_cap_max_messages?: number | null
+ /**
+ * Length of the rolling frequency cap window in days. Set this together with marketing_frequency_cap_max_messages. Set both to null to turn the cap off.
+ * @minimum 1
+ * @maximum 30
+ * @nullable
+ */
+ marketing_frequency_cap_window_days?: number | null
}
export interface TeamFeatureFlagPolicyConfigApi {
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 3d50ef8dd5be..36140a55c801 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -80,6 +80,7 @@ import { HeatmapCaptureSettings } from 'products/web_analytics/frontend/heatmaps
import { HeatmapScreenshotCookieSettings } from 'products/web_analytics/frontend/heatmaps/components/HeatmapScreenshotCookieSettings'
import { WorkflowsEmailTrackingConsentSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsEmailTrackingConsentSettings'
import { WorkflowsEngagementEventsSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsEngagementEventsSettings'
+import { WorkflowsFrequencyCapSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings'
import { WorkflowsTaskLimitsSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsTaskLimitsSettings'
import { IntegrationsList } from '../../lib/integrations/IntegrationsList'
@@ -1880,6 +1881,14 @@ export const SETTINGS_MAP: SettingSection[] = [
'opt-out',
],
},
+ {
+ id: 'workflows-frequency-cap',
+ title: 'Frequency cap',
+ description:
+ 'The most marketing messages one person can get in a rolling number of days, across all workflows and broadcasts. Sends past the cap are skipped and the workflow moves on to the next step. Transactional messages are never capped and do not count. A workflow run without a person, for example one triggered by an event without a person profile, is not capped. Leave both fields empty to turn the cap off.',
+ component: <WorkflowsFrequencyCapSettings />,
+ keywords: ['workflows', 'frequency', 'cap', 'limit', 'fatigue', 'marketing', 'broadcast', 'email'],
+ },
{
id: 'workflows-ai-task-limits',
title: 'AI task limits',
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 4d1a1972b910..b8c68aa91dac 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -317,6 +317,7 @@ export type SettingId =
| 'web-analytics-pre-aggregated-tables'
| 'web-revenue-events'
| 'web-vitals-autocapture'
+ | 'workflows-frequency-cap'
| 'workflows-ai-task-limits'
| 'workflows-email-tracking-consent'
| 'workflows-engagement-events'
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 8dcdfa8426de..fac18b886508 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -945,6 +945,9 @@ export interface WorkflowsConfig {
workflow_task_rate_limit_per_day?: number | null
workflow_task_team_rate_limit_per_day?: number | null
default_email_integration_id?: number | null
+ // Null on either disables the marketing frequency cap.
+ marketing_frequency_cap_max_messages?: number | null
+ marketing_frequency_cap_window_days?: number | null
}
export interface FeatureFlagPolicyConfig {
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index ca8f6d512e58..6596c48208cf 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -208,6 +208,11 @@ export interface CdpCoreServicesDeps {
* open connections against the SES Valkey instance.
*/
emailValidationValkey: RedisV2 | null
+ /**
+ * Dedicated frequency cap Valkey pool, opened only on the same pods as `emailValidationValkey`.
+ * `null` elsewhere, and when no host is configured, which turns the cap off.
+ */
+ frequencyCapValkey: RedisV2 | null
}
/**
@@ -516,7 +521,13 @@ export function createCdpCoreServices(
hogExecutorAsync
)
- const recipientPreferencesService = new RecipientPreferencesService(recipientsManager, emailSuppressionService)
+ const recipientPreferencesService = new RecipientPreferencesService(
+ recipientsManager,
+ emailSuppressionService,
+ deps.frequencyCapValkey
+ ? { teamWorkflowsConfig: teamWorkflowsConfigService, valkey: deps.frequencyCapValkey }
+ : undefined
+ )
// MX verdicts live on the dedicated SES Valkey (same instance as the SES rate
// limiter, separate pool). The pool is created by the server only on pods
// whose capabilities execute email actions; everywhere else this is null
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 88f0ed5a1877..db7c1adcd63d 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -97,6 +97,13 @@ export type CdpConfig = ClickhouseConfig & {
SES_RATE_LIMITER_VALKEY_PASSWORD: string
SES_RATE_LIMITER_VALKEY_TLS: boolean
+ // Dedicated Valkey for the marketing frequency cap. It holds one sorted set per capped person,
+ // so it stays off the shared CDP Valkey and the SES Valkey. Unset turns the cap off.
+ CDP_FREQUENCY_CAP_VALKEY_HOST: string
+ CDP_FREQUENCY_CAP_VALKEY_PORT: number
+ CDP_FREQUENCY_CAP_VALKEY_PASSWORD: string
+ CDP_FREQUENCY_CAP_VALKEY_TLS: boolean
+
CDP_SES_RATE_LIMIT_REFILL_PER_SECOND: number
CDP_SES_RATE_LIMIT_CAPACITY: number
CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS: number
@@ -312,6 +319,11 @@ export function getDefaultCdpConfig(): CdpConfig {
SES_RATE_LIMITER_VALKEY_PASSWORD: '',
SES_RATE_LIMITER_VALKEY_TLS: false,
+ CDP_FREQUENCY_CAP_VALKEY_HOST: isTestEnv() || isDevEnv() ? '127.0.0.1' : '',
+ CDP_FREQUENCY_CAP_VALKEY_PORT: isTestEnv() || isDevEnv() ? 6390 : 6379,
+ CDP_FREQUENCY_CAP_VALKEY_PASSWORD: '',
+ CDP_FREQUENCY_CAP_VALKEY_TLS: false,
+
CDP_SES_RATE_LIMIT_REFILL_PER_SECOND: 100,
CDP_SES_RATE_LIMIT_CAPACITY: 50,
CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS: 250,
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
index b42a7bef0273..457146051e11 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -110,6 +110,7 @@ describe('HogFunctionHandler', () => {
)
mockRecipientPreferencesService = {
shouldSkipAction: jest.fn().mockResolvedValue(null),
+ isFrequencyCapped: jest.fn().mockResolvedValue(false),
} as any
mockEmailValidationService = {
getSkipReason: jest.fn().mockResolvedValue(null),
@@ -447,6 +448,41 @@ describe('HogFunctionHandler', () => {
expect(mockFetch).not.toHaveBeenCalled()
})
+ // A broadcast run carries a parentRunId, and its run view reads metrics keyed on that ID.
+ it.each([
+ ['a workflow run', undefined],
+ ['a broadcast run', 'broadcast-run-id'],
+ ])(
+ 'should skip the send and emit message_frequency_capped when the recipient reached the frequency cap for %s',
+ async (_label, parentRunId) => {
+ ;(mockRecipientPreferencesService.isFrequencyCapped as jest.Mock).mockResolvedValueOnce(true)
+ invocation.parentRunId = parentRunId
+
+ const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {
+ queue: 'hog',
+ queuePriority: 0,
+ })
+
+ const handlerResult = await hogFunctionHandler.execute({ invocation, action, result: invocationResult })
+
+ expect(handlerResult.nextAction?.id).toBe('exit')
+ expect(invocationResult.logs[0].message).toContain(
+ `[Action:function] Skipping send: recipient reached the frequency cap.`
+ )
+ expect(invocationResult.metrics).toEqual([
+ {
+ team_id: team.id,
+ app_source_id: parentRunId ?? invocation.functionId,
+ instance_id: action.id,
+ metric_kind: 'other',
+ metric_name: 'message_frequency_capped',
+ count: 1,
+ },
+ ])
+ expect(mockFetch).not.toHaveBeenCalled()
+ }
+ )
+
it('should skip the send and emit email_bounce_prevented when validation predicts a hard bounce', async () => {
;(mockEmailValidationService.getSkipReason as jest.Mock).mockResolvedValueOnce(
'Skipping send: the domain "dead.invalid" has no reachable mail servers, so this message would hard bounce.'
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index eaf1cd65b207..434d1c0b6219 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -428,6 +428,40 @@ export class HogFunctionHandler implements ActionHandler {
}
}
+ // This check runs last because it also records the send against the cap. If it ran before the
+ // opt-out, suppression or bounce checks, a send that one of them skips would still use a slot.
+ if (
+ !hogExecutorOptions?.isTest &&
+ (await this.recipientPreferencesService.isFrequencyCapped(hogFunctionInvocation, action))
+ ) {
+ return {
+ finished: true,
+ skipped: true,
+ invocation: hogFunctionInvocation,
+ logs: [
+ {
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: 'Skipping send: recipient reached the frequency cap.',
+ },
+ ],
+ metrics: [
+ {
+ team_id: hogFunctionInvocation.teamId,
+ app_source_id: hogFunctionInvocation.parentRunId ?? hogFunctionInvocation.functionId,
+ instance_id: action.id,
+ metric_kind: 'other',
+ metric_name: 'message_frequency_capped',
+ count: 1,
+ },
+ ],
+ capturedPostHogEvents: [],
+ warehouseWebhookPayloads: [],
+ messageAssets: [],
+ conversionWatchers: [],
+ }
+ }
+
return instrumentFn({ key: 'hogFlow.action.hogFunction.executeWithAsyncFunctions', sendException: false }, () =>
this.hogFlowFunctionsService.executeWithAsyncFunctions(hogFunctionInvocation, hogExecutorOptions)
)
diff --git a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts b/nodejs/src/cdp/services/managers/team-workflows-config.service.ts
index 1a943b4f4df0..b725198f5b19 100644
--- a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts
+++ b/nodejs/src/cdp/services/managers/team-workflows-config.service.ts
@@ -19,14 +19,21 @@ export type TeamWorkflowsConfig = {
ses_tenant_provider_suspended: boolean
/** Trust tier that picks the team's hourly and daily workflow email caps. */
email_sending_tier: number
+ /** Max marketing messages one person gets per window. Null on either field means no cap. */
+ marketing_frequency_cap_max_messages: number | null
+ marketing_frequency_cap_window_days: number | null
}
+export type FrequencyCap = { max_messages: number | null; window_days: number | null }
+
const DEFAULT_CONFIG: TeamWorkflowsConfig = {
capture_workflows_engagement_events: false,
email_tracking_consent_mode: 'off',
email_sending_suspended: false,
ses_tenant_provider_suspended: false,
email_sending_tier: 0,
+ marketing_frequency_cap_max_messages: null,
+ marketing_frequency_cap_window_days: null,
}
/**
@@ -106,6 +113,14 @@ export class TeamWorkflowsConfigService {
}
}
+ public async getFrequencyCap(teamId: number): Promise<FrequencyCap> {
+ const config = await this.get(teamId)
+ return {
+ max_messages: config.marketing_frequency_cap_max_messages,
+ window_days: config.marketing_frequency_cap_window_days,
+ }
+ }
+
private async fetchConfigs(teamIds: string[]): Promise<Record<string, TeamWorkflowsConfig>> {
const result = await this.postgres.query<{
team_id: number
@@ -114,6 +129,8 @@ export class TeamWorkflowsConfigService {
email_sending_suspended: boolean
ses_tenant_provider_suspended: boolean
email_sending_tier: number
+ marketing_frequency_cap_max_messages: number | null
+ marketing_frequency_cap_window_days: number | null
}>(
PostgresUse.COMMON_READ,
// Only DISABLED blocks: ENABLED and REINSTATED both permit sending, and '' means the
@@ -121,7 +138,7 @@ export class TeamWorkflowsConfigService {
`SELECT team_id, capture_workflows_engagement_events, email_tracking_consent_mode,
email_sending_suspended_at IS NOT NULL AS email_sending_suspended,
ses_tenant_sending_status = 'DISABLED' AS ses_tenant_provider_suspended,
- email_sending_tier
+ email_sending_tier, marketing_frequency_cap_max_messages, marketing_frequency_cap_window_days
FROM workflows_teamworkflowsconfig
WHERE team_id = ANY($1)`,
[teamIds.map(Number)],
@@ -139,6 +156,8 @@ export class TeamWorkflowsConfigService {
email_sending_suspended: row.email_sending_suspended,
ses_tenant_provider_suspended: row.ses_tenant_provider_suspended,
email_sending_tier: row.email_sending_tier ?? 0,
+ marketing_frequency_cap_max_messages: row.marketing_frequency_cap_max_messages,
+ marketing_frequency_cap_window_days: row.marketing_frequency_cap_window_days,
}
}
return configs
diff --git a/nodejs/src/cdp/services/messaging/frequency-cap-valkey-pool.ts b/nodejs/src/cdp/services/messaging/frequency-cap-valkey-pool.ts
new file mode 100644
index 000000000000..5c73e256d99f
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/frequency-cap-valkey-pool.ts
@@ -0,0 +1,45 @@
+import type { CommonConfig } from '~/common/config'
+import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
+import { logger } from '~/common/utils/logger'
+
+import type { CdpConfig } from '../../config'
+
+export type FrequencyCapValkeyConfig = Pick<
+ CdpConfig,
+ | 'CDP_FREQUENCY_CAP_VALKEY_HOST'
+ | 'CDP_FREQUENCY_CAP_VALKEY_PORT'
+ | 'CDP_FREQUENCY_CAP_VALKEY_PASSWORD'
+ | 'CDP_FREQUENCY_CAP_VALKEY_TLS'
+> &
+ Pick<CommonConfig, 'REDIS_POOL_MIN_SIZE' | 'REDIS_POOL_MAX_SIZE'>
+
+/**
+ * Creates a connection to the dedicated frequency cap Valkey instance. Returns null when the host
+ * is unset, and the frequency cap is then off in that environment.
+ */
+export function createFrequencyCapValkeyPool(config: FrequencyCapValkeyConfig): RedisV2 | null {
+ const name = 'workflows-frequency-cap'
+ if (!config.CDP_FREQUENCY_CAP_VALKEY_HOST) {
+ logger.info('🧢', `[${name}] no frequency cap Valkey host configured — frequency cap disabled`)
+ return null
+ }
+
+ logger.info(
+ '🧢',
+ `[${name}] writer=${config.CDP_FREQUENCY_CAP_VALKEY_HOST}:${config.CDP_FREQUENCY_CAP_VALKEY_PORT} tls=${config.CDP_FREQUENCY_CAP_VALKEY_TLS}`
+ )
+
+ return createRedisV2PoolFromConfig({
+ connection: {
+ url: config.CDP_FREQUENCY_CAP_VALKEY_HOST,
+ options: {
+ port: config.CDP_FREQUENCY_CAP_VALKEY_PORT,
+ password: config.CDP_FREQUENCY_CAP_VALKEY_PASSWORD,
+ tls: config.CDP_FREQUENCY_CAP_VALKEY_TLS ? {} : undefined,
+ },
+ name,
+ },
+ poolMinSize: config.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: config.REDIS_POOL_MAX_SIZE,
+ })
+}
diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
index b88f4d96d23e..07a804a34db1 100644
--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
@@ -2,6 +2,9 @@ import { FixtureHogFlowBuilder } from '~/cdp/_tests/builders/hogflow.builder'
import { createExampleInvocation } from '~/cdp/_tests/fixtures'
import { HogFlowAction } from '~/cdp/schema/hogflow'
import { CyclotronJobInvocationHogFunction } from '~/cdp/types'
+import { defaultConfig } from '~/common/config/config'
+import { deleteKeysWithPrefix } from '~/common/redis/_tests/redis'
+import { RedisV2 } from '~/common/redis/redis-v2'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresUse } from '~/common/utils/db/postgres'
import { logger } from '~/common/utils/logger'
@@ -10,7 +13,9 @@ import { createTestTeamFixture } from '~/tests/helpers/sql'
import { Hub, Team } from '~/types'
import { RecipientsManagerService } from '../managers/recipients-manager.service'
+import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'
import { EmailSuppressionService, emailSuppressionConfigFromEnv } from './email-suppression.service'
+import { createFrequencyCapValkeyPool } from './frequency-cap-valkey-pool'
import { RecipientPreferencesService } from './recipient-preferences.service'
import { RecipientTokensService } from './recipient-tokens.service'
@@ -656,6 +661,103 @@ describe('RecipientPreferencesService', () => {
})
})
+ describe('isFrequencyCapped', () => {
+ let valkey: RedisV2
+ let frequencyCap: { max_messages: number | null; window_days: number | null }
+ let teamWorkflowsConfig: TeamWorkflowsConfigService
+ let cappedService: RecipientPreferencesService
+
+ const emailAction = (
+ categoryType?: 'marketing' | 'transactional'
+ ): Extract<HogFlowAction, { type: 'function_email' }> => ({
+ id: 'email',
+ name: 'Send email',
+ description: '',
+ type: 'function_email',
+ filters: null,
+ config: {
+ template_id: 'template-email',
+ message_category_type: categoryType,
+ inputs: { email: { value: { to: { email: '[email protected]' } } } },
+ },
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ })
+
+ beforeAll(() => {
+ // One pool for the block: RedisV2 has no close, so a pool per test would leave its connections open.
+ valkey = createFrequencyCapValkeyPool(defaultConfig)!
+ })
+
+ beforeEach(async () => {
+ await deleteKeysWithPrefix(valkey, `@posthog/workflows-frequency-cap/${team.id}/`)
+ frequencyCap = { max_messages: 2, window_days: 7 }
+ teamWorkflowsConfig = new TeamWorkflowsConfigService(hub.postgres, hub.pubSub)
+ jest.spyOn(teamWorkflowsConfig, 'getFrequencyCap').mockImplementation(() => Promise.resolve(frequencyCap))
+ cappedService = new RecipientPreferencesService(mockRecipientsManager, mockEmailSuppressionService, {
+ teamWorkflowsConfig,
+ valkey,
+ })
+ })
+
+ const sendAt = async (action: HogFlowAction, at: number): Promise<boolean> => {
+ jest.spyOn(Date, 'now').mockReturnValue(at)
+ return cappedService.isFrequencyCapped(createFunctionStepInvocation(action as any), action)
+ }
+
+ it('caps marketing sends past the limit until the window moves past the oldest send', async () => {
+ const day = 24 * 60 * 60 * 1000
+ const start = 1_800_000_000_000
+
+ expect(await sendAt(emailAction(), start)).toBe(false)
+ expect(await sendAt(emailAction(), start + day)).toBe(false)
+ expect(await sendAt(emailAction(), start + 2 * day)).toBe(true)
+ expect(await sendAt(emailAction(), start + 7 * day + 1)).toBe(false)
+ })
+
+ it('lets a re-entered step visit keep its slot from the send time and counts a later visit', async () => {
+ frequencyCap = { max_messages: 1, window_days: 1 }
+ const hour = 60 * 60 * 1000
+ const start = 1_800_000_000_000
+ const action = emailAction()
+ const invocation = createFunctionStepInvocation(action)
+ invocation.state.actionId = action.id
+ invocation.state.actionStepCount = 1
+ const checkAt = async (at: number): Promise<boolean> => {
+ jest.spyOn(Date, 'now').mockReturnValue(at)
+ return cappedService.isFrequencyCapped(invocation, action)
+ }
+
+ // The email queue runs the step a second time after the hog queue routed it there and paced it.
+ expect(await checkAt(start)).toBe(false)
+ expect(await checkAt(start + 23 * hour)).toBe(false)
+
+ invocation.state.actionStepCount = 3
+ expect(await checkAt(start + 25 * hour)).toBe(true)
+ })
+
+ it.each([
+ [
+ 'the config lookup',
+ () => jest.spyOn(teamWorkflowsConfig, 'getFrequencyCap').mockRejectedValue(new Error('unavailable')),
+ ],
+ ['the Valkey pool', () => jest.spyOn(valkey, 'useClient').mockRejectedValue(new Error('unavailable'))],
+ ])('lets the send through when %s fails', async (_, fail) => {
+ fail()
+ expect(await sendAt(emailAction(), 1_800_000_000_000)).toBe(false)
+ })
+
+ it.each([
+ ['transactional sends', emailAction('transactional'), { max_messages: 0, window_days: 7 }],
+ ['teams with no cap', emailAction(), { max_messages: null, window_days: null }],
+ ])('never caps %s', async (_, action, cap) => {
+ frequencyCap = cap
+ for (let i = 0; i < 3; i++) {
+ expect(await sendAt(action, 1_800_000_000_000 + i)).toBe(false)
+ }
+ })
+ })
+
describe('recipient token URLs', () => {
let tokensService: RecipientTokensService
diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
index 6ce834f21e01..36aa833071bf 100644
--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
@@ -1,8 +1,11 @@
import { HogFlowAction } from '~/cdp/schema/hogflow'
+import { RedisV2 } from '~/common/redis/redis-v2'
import { logger } from '~/common/utils/logger'
import { CyclotronJobInvocationHogFunction } from '../../types'
+import { workflowStepDispatchKeyFromInvocation } from '../../utils/workflow-step-dispatch-key'
import { RecipientsManagerService } from '../managers/recipients-manager.service'
+import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'
import { EmailSuppressionService } from './email-suppression.service'
type MessageFunctionActionType = 'function_email' | 'function_sms' | 'function_push'
@@ -29,12 +32,68 @@ const extractEmailsFromAddressList = (value: unknown): string[] => {
.filter((addr) => addr.length > 0)
}
+// One Lua script, so two concurrent sends to one person cannot both pass with one slot left. Each slot
+// is keyed on the step visit. The email queue and send retries run the same step visit again, so a
+// visit that already holds a slot passes. That run also moves the slot score to now, because the email
+// queue can delay the actual send by hours and the window must start when the email goes out.
+const FREQUENCY_CAP_SCRIPT = `
+redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', tonumber(ARGV[1]) - tonumber(ARGV[2]))
+if not redis.call('ZSCORE', KEYS[1], ARGV[4]) and redis.call('ZCARD', KEYS[1]) >= tonumber(ARGV[3]) then return 1 end
+redis.call('ZADD', KEYS[1], ARGV[1], ARGV[4])
+redis.call('PEXPIRE', KEYS[1], ARGV[2])
+return 0
+`
+
export class RecipientPreferencesService {
constructor(
private recipientsManager: RecipientsManagerService,
- private emailSuppressionService: EmailSuppressionService
+ private emailSuppressionService: EmailSuppressionService,
+ private frequencyCap?: { teamWorkflowsConfig: TeamWorkflowsConfigService; valkey: RedisV2 }
) {}
+ /** Returns true when the person is at the cap. Otherwise records this send against the cap and returns false. */
+ public async isFrequencyCapped(
+ invocation: CyclotronJobInvocationHogFunction,
+ action: HogFlowAction
+ ): Promise<boolean> {
+ const personId = invocation.state.globals.person?.id
+ if (
+ !this.frequencyCap ||
+ !personId ||
+ !this.isSubjectToRecipientPreferences(action) ||
+ action.config.message_category_type === 'transactional'
+ ) {
+ return false
+ }
+ try {
+ const { max_messages, window_days } = await this.frequencyCap.teamWorkflowsConfig.getFrequencyCap(
+ invocation.teamId
+ )
+ if (!max_messages || !window_days) {
+ return false
+ }
+ const capped = await this.frequencyCap.valkey.useClient(
+ { name: 'workflows-frequency-cap', failOpen: true },
+ (client) =>
+ client.eval(
+ FREQUENCY_CAP_SCRIPT,
+ 1,
+ `@posthog/workflows-frequency-cap/${invocation.teamId}/${personId}`,
+ Date.now(),
+ window_days * 24 * 60 * 60 * 1000,
+ max_messages,
+ workflowStepDispatchKeyFromInvocation(invocation) ?? `${invocation.id}:${action.id}`
+ ) as Promise<number>
+ )
+ return capped === 1
+ } catch (error) {
+ // Fail open: a config or Valkey pool error must never block a send. failOpen above only
+ // covers errors inside the Valkey callback.
+ logger.error(`Failed to check the frequency cap for team ${invocation.teamId}:`, error)
+ return false
+ }
+ }
+
public async shouldSkipAction(
invocation: CyclotronJobInvocationHogFunction,
action: HogFlowAction
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 4f268fefb5c4..4bf874df99db 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -260,6 +260,7 @@ export type MinimalAppMetric = {
| 'email_bounced_transient'
| 'email_bounced_undetermined'
| 'email_bounce_prevented'
+ | 'message_frequency_capped'
| 'email_suppressed'
| 'email_suspended'
| 'email_paused'
diff --git a/nodejs/src/cdp/workflows-e2e.serial.test.ts b/nodejs/src/cdp/workflows-e2e.serial.test.ts
index 49856a250529..7777a149ff96 100644
--- a/nodejs/src/cdp/workflows-e2e.serial.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.serial.test.ts
@@ -80,6 +80,7 @@ import { CyclotronJobQueueKafka } from './services/job-queue/job-queue-kafka'
import { CyclotronJobQueuePostgresV2 } from './services/job-queue/job-queue-postgres-v2'
import { CyclotronJobQueueRateLimitedPostgresV2 } from './services/job-queue/job-queue-rate-limited-postgres-v2'
import { JobQueue } from './services/job-queue/job-queue.interface'
+import { createFrequencyCapValkeyPool } from './services/messaging/frequency-cap-valkey-pool'
import { HogInvocationResultsService } from './services/monitoring/hog-invocation-results.service'
import { RateLimiterService } from './services/rate-limiter/rate-limiter.service'
import { HogFunctionInvocationGlobals } from './types'
@@ -3043,6 +3044,120 @@ describe('Workflows E2E (email queue)', () => {
}, 10000)
})
+ it('sends up to the frequency cap per person, then skips and completes the run', async () => {
+ // The email step runs on the hogflow worker and again on the email worker. Each pass checks the cap,
+ // so with a cap of one the first run only sends if the second pass reuses its slot.
+ await hub.postgres.query(
+ PostgresUse.COMMON_WRITE,
+ `INSERT INTO workflows_teamworkflowsconfig
+ (team_id, capture_workflows_engagement_events, email_tracking_consent_mode,
+ email_sending_suspension_reason, ses_tenant_sending_status, email_sending_tier,
+ marketing_frequency_cap_max_messages, marketing_frequency_cap_window_days)
+ VALUES ($1, false, 'off', '', '', 0, 1, 1)`,
+ [team.id],
+ 'set-team-frequency-cap'
+ )
+ const frequencyCapValkey = createFrequencyCapValkeyPool(hub)!
+ await deleteKeysWithPrefix(frequencyCapValkey, `@posthog/workflows-frequency-cap/${team.id}/`)
+
+ // The cap is per person, and these workers resolve the person from the event's distinct_id.
+ const person: InternalPersonWithDistinctId = {
+ id: '1',
+ uuid: '5b0c4a6e-2f0c-4a43-9c1e-7f6a1d0b9e21',
+ team_id: team.id,
+ properties: { email: '[email protected]' },
+ properties_last_updated_at: {},
+ properties_last_operation: null,
+ created_at: DateTime.utc(),
+ version: 1,
+ is_identified: true,
+ is_user_id: null,
+ last_seen_at: null,
+ distinct_id: 'capped-distinct-id',
+ }
+ const personDeps = {
+ ...deps,
+ personRepository: {
+ fetchPerson: jest.fn().mockResolvedValue(person),
+ fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([person]),
+ fetchPersonsByPersonIds: jest.fn().mockResolvedValue([person]),
+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),
+ },
+ }
+ await Promise.all([hogflowWorker.stop(), emailWorker.stop()])
+ hogflowWorker = new CdpCyclotronWorkerHogFlow(
+ hub,
+ personDeps,
+ new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)
+ )
+ emailWorker = new CdpCyclotronWorkerEmail(
+ hub,
+ personDeps,
+ new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)
+ )
+ await Promise.all([hogflowWorker.start(), emailWorker.start()])
+
+ const hogFlow = new FixtureHogFlowBuilder()
+ .withTeamId(team.id)
+ .withStatus('active')
+ .withExitCondition('exit_only_at_end')
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: { type: 'event', filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {} },
+ },
+ email_1: {
+ type: 'function_email',
+ config: {
+ template_id: 'template-workflows-e2e-email',
+ inputs: {
+ email: {
+ value: {
+ to: { email: '[email protected]', name: 'Recipient' },
+ from: { integrationId: 1, email: '[email protected]' },
+ subject: 'Frequency cap',
+ text: 'Test text',
+ html: '<p>Test html</p>',
+ },
+ },
+ },
+ },
+ },
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [
+ { from: 'trigger', to: 'email_1', type: 'continue' },
+ { from: 'email_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+ await insertHogFlow(hub.postgres, hogFlow)
+
+ const { backgroundTask } = await eventsConsumer.processBatch([
+ createGlobals({ uuid: new UUIDT().toString(), distinct_id: 'capped-distinct-id' } as any),
+ createGlobals({ uuid: new UUIDT().toString(), distinct_id: 'capped-distinct-id' } as any),
+ ])
+ await backgroundTask
+
+ await waitForExpect(() => {
+ const sumCounts = (filter: (m: any) => boolean) =>
+ mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
+ .filter(filter)
+ .reduce((sum: number, m: any) => sum + m.value.count, 0)
+
+ expect(sumCounts((m) => m.value.metric_name === 'succeeded' && m.value.instance_id === 'exit')).toBe(2)
+ expect(sumCounts((m) => m.value.metric_name === 'email_sent')).toBe(1)
+ expect(sumCounts((m) => m.value.metric_name === 'message_frequency_capped')).toBe(1)
+ }, 15000)
+
+ const jobs = await queryCyclotronJobs()
+ expect(jobs.filter((j: any) => j.status === 'completed')).toHaveLength(2)
+ expect(jobs.filter((j: any) => j.status === 'failed')).toHaveLength(0)
+ })
+
it('does not emit duplicate Resuming / Executing / pause logs for the email-queue routing reschedule', async () => {
// Email steps reschedule themselves once to switch onto the dedicated email queue
// (see HogFunctionHandler.execute in actions/hog_function.ts). That second dequeue
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index 2ba7bbdf73e2..2183449ee9ce 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -47,6 +47,7 @@ import { HogFlowBatchPersonQueryService } from './cdp/services/hogflows/hogflow-
import { CyclotronJobQueueKafka } from './cdp/services/job-queue/job-queue-kafka'
import { CyclotronJobQueuePostgresV2 } from './cdp/services/job-queue/job-queue-postgres-v2'
import { CyclotronJobQueueRateLimitedPostgresV2 } from './cdp/services/job-queue/job-queue-rate-limited-postgres-v2'
+import { createFrequencyCapValkeyPool } from './cdp/services/messaging/frequency-cap-valkey-pool'
import { hasEmailSigningKey } from './cdp/services/messaging/helpers/tracking-code'
import { HogInvocationResultsService } from './cdp/services/monitoring/hog-invocation-results.service'
import { createSesRateLimiterValkeyPool } from './cdp/services/rate-limiter/rate-limiter-valkey-pool'
@@ -131,10 +132,10 @@ export class PluginServer implements NodeServer {
cdpQuotaServices = this.createCdpQuotaServices(teamManager)
}
- // Build typed deps objects for consumers. `emailValidationValkey` is null in
- // the shared deps and set only by the cyclotron workers that run the hogflow
- // email action (see `withEmailValidationValkey` at their loaders below) — no
- // other consumer touches the SES Valkey.
+ // Build typed deps objects for consumers. `emailValidationValkey` and `frequencyCapValkey`
+ // are null in the shared deps and set only by the cyclotron workers that run the hogflow
+ // email action (see `withEmailActionValkeys` at their loaders below) — no
+ // other consumer touches the SES or frequency cap Valkey.
const cdpDeps: CdpConsumerBaseDeps | undefined = needsCdp
? {
postgres: this.postgres!,
@@ -149,6 +150,7 @@ export class PluginServer implements NodeServer {
groupRepository: cdpServices!.groupRepository,
quotaLimiting: cdpQuotaServices!.quotaLimiting,
emailValidationValkey: null,
+ frequencyCapValkey: null,
}
: undefined
@@ -300,11 +302,7 @@ export class PluginServer implements NodeServer {
// instances naturally; locally we'd silently double-process when
// both capabilities are enabled in the same process.
const queue = new CyclotronJobQueuePostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config)
- const worker = new CdpCyclotronWorkerHogFlow(
- this.config,
- this.withEmailValidationValkey(cdpDeps!),
- queue
- )
+ const worker = new CdpCyclotronWorkerHogFlow(this.config, this.withEmailActionValkeys(cdpDeps!), queue)
await worker.start()
return worker.service
})
@@ -364,7 +362,7 @@ export class PluginServer implements NodeServer {
throttledPollDelayMs: this.config.CDP_SES_RATE_LIMIT_THROTTLED_POLL_DELAY_MS,
})
: new CyclotronJobQueuePostgresV2(this.config.CONSUMER_BATCH_SIZE, this.config)
- const worker = new CdpCyclotronWorkerEmail(this.config, this.withEmailValidationValkey(cdpDeps!), queue)
+ const worker = new CdpCyclotronWorkerEmail(this.config, this.withEmailActionValkeys(cdpDeps!), queue)
await worker.start()
return worker.service
})
@@ -450,9 +448,15 @@ export class PluginServer implements NodeServer {
* for the SES rate limiter shouldn't hold connections from pods that never validate.
* Null when no SES Valkey host is configured (local dev), in which case
* EmailValidationService degrades to its local cache + DNS.
+ *
+ * Also grants the dedicated frequency cap Valkey pool, which the same send path checks.
*/
- private withEmailValidationValkey(deps: CdpConsumerBaseDeps): CdpConsumerBaseDeps {
- return { ...deps, emailValidationValkey: createSesRateLimiterValkeyPool(this.config, 'email-mx-validation') }
+ private withEmailActionValkeys(deps: CdpConsumerBaseDeps): CdpConsumerBaseDeps {
+ return {
+ ...deps,
+ emailValidationValkey: createSesRateLimiterValkeyPool(this.config, 'email-mx-validation'),
+ frequencyCapValkey: createFrequencyCapValkeyPool(this.config),
+ }
}
private getCleanupResources(): CleanupResources {
diff --git a/nodejs/tests/helpers/cdp.ts b/nodejs/tests/helpers/cdp.ts
index fd54a2a9ae23..b5faf4e220fd 100644
--- a/nodejs/tests/helpers/cdp.ts
+++ b/nodejs/tests/helpers/cdp.ts
@@ -12,6 +12,7 @@ import {
WARPSTREAM_CYCLOTRON_PRODUCER,
WARPSTREAM_INGESTION_PRODUCER,
} from '../../src/cdp/outputs/producers'
+import { createFrequencyCapValkeyPool } from '../../src/cdp/services/messaging/frequency-cap-valkey-pool'
import { createSesRateLimiterValkeyPool } from '../../src/cdp/services/rate-limiter/rate-limiter-valkey-pool'
import { InternalCaptureService } from '../../src/common/services/internal-capture'
import { Hub } from '../../src/types'
@@ -63,5 +64,6 @@ export function createCdpConsumerDeps(hub: Hub, kafkaProducer?: KafkaProducerWra
groupRepository: noopGroupReadRepository,
quotaLimiting: hub.quotaLimiting,
emailValidationValkey: createSesRateLimiterValkeyPool(hub, 'email-mx-validation'),
+ frequencyCapValkey: createFrequencyCapValkeyPool(hub),
}
}
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 592fcdc50e55..bce0bedc06ac 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -994,6 +994,26 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContr
f"{MAX_SELF_SERVE_WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY}."
),
)
+ marketing_frequency_cap_max_messages = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=1,
+ max_value=1000,
+ help_text=(
+ "Most marketing messages one person can get in the window, across all workflows. "
+ "Set this together with marketing_frequency_cap_window_days. Set both to null to turn the cap off."
+ ),
+ )
+ marketing_frequency_cap_window_days = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=1,
+ max_value=30,
+ help_text=(
+ "Length of the rolling frequency cap window in days. "
+ "Set this together with marketing_frequency_cap_max_messages. Set both to null to turn the cap off."
+ ),
+ )
default_email_integration_id = serializers.IntegerField(
required=False,
@@ -1013,6 +1033,8 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContr
"workflow_task_rate_limit_per_day",
"workflow_task_team_rate_limit_per_day",
"default_email_integration_id",
+ "marketing_frequency_cap_max_messages",
+ "marketing_frequency_cap_window_days",
]
def _enforce_self_serve_ceiling(self, field: str, value: int | None, ceiling: int) -> int | None:
@@ -1057,6 +1079,28 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContr
raise serializers.ValidationError("Verify this sender's domain before making it the default.")
return value
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ # As a nested field of the team serializer there is no stored row to merge a partial update with.
+ # validate_team_workflows_config runs this serializer again with the row, and that run does the check.
+ if self.parent:
+ return attrs
+ cap_fields = ("marketing_frequency_cap_max_messages", "marketing_frequency_cap_window_days")
+ cap = {field: attrs[field] for field in cap_fields if field in attrs}
+ if len(cap) == 1 and self.instance is not None:
+ # Read the stored row, because `Team.workflows_config` is a cached_property on the Team instance
+ # and can hold values from before an earlier update.
+ stored = TeamWorkflowsConfig.objects.filter(pk=self.instance.pk).values(*cap_fields).first() or {}
+ cap = {**stored, **cap}
+ # The worker treats either null as no cap, so a half-set cap would save but never apply.
+ if cap:
+ missing = [field for field in cap_fields if cap.get(field) is None]
+ if len(missing) == 1:
+ other = next(field for field in cap_fields if field != missing[0])
+ raise serializers.ValidationError(
+ {missing[0]: f"Set this together with {other}, or set both to null to turn the frequency cap off."}
+ )
+ return attrs
+
def validate_team_workflows_config(team: Team | None, value: dict[str, Any] | None) -> dict[str, Any] | None:
if value is None:
diff --git a/products/workflows/backend/test/test_team_workflows_config.py b/products/workflows/backend/test/test_team_workflows_config.py
index 22b8034238ff..e091a47a04d1 100644
--- a/products/workflows/backend/test/test_team_workflows_config.py
+++ b/products/workflows/backend/test/test_team_workflows_config.py
@@ -50,6 +50,8 @@ class TestTeamWorkflowsConfig(APIBaseTest):
"workflow_task_rate_limit_per_day": None,
"workflow_task_team_rate_limit_per_day": None,
"default_email_integration_id": None,
+ "marketing_frequency_cap_max_messages": None,
+ "marketing_frequency_cap_window_days": None,
}
def test_patch_enables_capture(self) -> None:
@@ -112,6 +114,8 @@ class TestTeamWorkflowsConfig(APIBaseTest):
"workflow_task_rate_limit_per_day": None,
"workflow_task_team_rate_limit_per_day": None,
"default_email_integration_id": None,
+ "marketing_frequency_cap_max_messages": None,
+ "marketing_frequency_cap_window_days": None,
}
@parameterized.expand(
@@ -148,3 +152,54 @@ class TestTeamWorkflowsConfig(APIBaseTest):
response = self.client.patch(self.url, {"workflows_config": {"default_email_integration_id": None}})
assert response.status_code == status.HTTP_200_OK
assert TeamWorkflowsConfig.objects.get(team=self.team).default_email_integration_id is None
+
+ @parameterized.expand(
+ [
+ ["count with no saved window", None, {"marketing_frequency_cap_max_messages": 3}, 400, (None, None)],
+ [
+ "window longer than 30 days",
+ None,
+ {"marketing_frequency_cap_max_messages": 3, "marketing_frequency_cap_window_days": 31},
+ 400,
+ (None, None),
+ ],
+ ["count change on a saved cap", (2, 7), {"marketing_frequency_cap_max_messages": 3}, 200, (3, 7)],
+ ["one field cleared on a saved cap", (2, 7), {"marketing_frequency_cap_window_days": None}, 400, (2, 7)],
+ [
+ "both fields cleared",
+ (2, 7),
+ {"marketing_frequency_cap_max_messages": None, "marketing_frequency_cap_window_days": None},
+ 200,
+ (None, None),
+ ],
+ ]
+ )
+ def test_patch_frequency_cap_needs_both_fields_or_neither(
+ self,
+ _name: str,
+ saved: tuple[int, int] | None,
+ patch: dict,
+ expected_status: int,
+ expected_cap: tuple[int | None, int | None],
+ ) -> None:
+ if saved:
+ response = self.client.patch(
+ self.url,
+ {
+ "workflows_config": {
+ "marketing_frequency_cap_max_messages": saved[0],
+ "marketing_frequency_cap_window_days": saved[1],
+ }
+ },
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ response = self.client.patch(self.url, {"workflows_config": patch})
+
+ assert response.status_code == expected_status, response.json()
+ stored = (
+ TeamWorkflowsConfig.objects.filter(team=self.team)
+ .values_list("marketing_frequency_cap_max_messages", "marketing_frequency_cap_window_days")
+ .first()
+ )
+ assert (stored or (None, None)) == expected_cap
diff --git a/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx b/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx
index 6263425b6711..d7423626c048 100644
--- a/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx
+++ b/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx
@@ -53,6 +53,12 @@ export function EmailMetricsSummary({
)
const sentTotal = sumTimeSeries(getSingleTrendSeries('email_sent'))
+ // A frequency-capped send is skipped before the provider sees it, so it is not part of `sent`.
+ // Its rate reads against every attempted send, the same denominator as the Issues column.
+ const attemptedTotal =
+ sentTotal +
+ sumTimeSeries(getSingleTrendSeries('email_bounce_prevented')) +
+ sumTimeSeries(getSingleTrendSeries('message_frequency_capped'))
return (
<>
@@ -60,9 +66,11 @@ export function EmailMetricsSummary({
{EMAIL_METRIC_KEYS.map((key) => {
const metric = WORKFLOW_EMAIL_METRICS[key]
const canDrillDown = !!onMetricClick && !!EMAIL_METRIC_INVOCATION_FILTERS[key]
- const shareOfSent =
- key !== 'email_sent' && sentTotal > 0
- ? percentage(sumTimeSeries(getSingleTrendSeries(key)) / sentTotal, 1)
+ const readsAgainstAttempts = key === 'message_frequency_capped'
+ const shareTotal = readsAgainstAttempts ? attemptedTotal : sentTotal
+ const share =
+ key !== 'email_sent' && shareTotal > 0
+ ? percentage(sumTimeSeries(getSingleTrendSeries(key)) / shareTotal, 1)
: null
return (
<WorkflowMetricCard
@@ -76,7 +84,13 @@ export function EmailMetricsSummary({
colorIfZero={getColorVar('muted')}
onClick={canDrillDown ? () => onMetricClick(key) : undefined}
onClickTooltip={`View invocations with a ${metric.name.toLowerCase()} log entry in this timeframe`}
- footer={shareOfSent ? <span>{shareOfSent} of sent</span> : null}
+ footer={
+ share ? (
+ <span>
+ {share} of {readsAgainstAttempts ? 'attempts' : 'sent'}
+ </span>
+ ) : null
+ }
compact={compact}
/>
)
diff --git a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx
index 55f40c1d23d3..5da1ae19ed60 100644
--- a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx
@@ -28,7 +28,7 @@ const TRACKED_SENDS_TOOLTIP =
'Untracked sends can never record opens or clicks, so engagement is shown against tracked sends (sent minus untracked). Counts and rates compare activity within the selected date range, so opens of emails sent before the range can push a rate above 100%.'
const ISSUE_RATES_TOOLTIP =
- 'Bounces and spam complaints are shown as a share of emails sent. A prevented bounce is skipped before it is sent, so it is shown as a share of every send the step attempted (sent plus prevented).'
+ 'Bounces and spam complaints are shown as a share of emails sent. A prevented bounce or a frequency-capped send is skipped before it is sent, so it is shown as a share of every send the step attempted (sent plus skipped).'
// Opens and clicks are only possible on tracked sends, so pair the raw count with the denominator it
// should be read against, plus the rate over that denominator. A step with no tracked sends shows a
@@ -127,9 +127,10 @@ export function WorkflowMetricsSummary({
key: 'issues',
tooltip: ISSUE_RATES_TOOLTIP,
render: (_, row) => {
- // A prevented bounce is skipped before the provider sees it, so it is not part of
- // `sent` and its rate reads against everything the step attempted to send.
- const attempted = row.sent + row.bouncePrevented
+ // A prevented bounce or a frequency-capped send is skipped before the provider sees
+ // it, so neither is part of `sent` and their rates read against everything the
+ // step attempted to send.
+ const attempted = row.sent + row.bouncePrevented + row.frequencyCapped
const classifiedBounces = row.bouncedHard + row.bouncedSoft + row.bouncedUnknown
const bounceIssues: { label: string; value: number; metric: EmailMetricName }[] = [
{ label: 'hard bounced', value: row.bouncedHard, metric: 'email_bounced_hard' },
@@ -167,6 +168,13 @@ export function WorkflowMetricsSummary({
type: 'warning' as const,
metric: 'email_bounce_prevented' as EmailMetric,
},
+ {
+ label: 'frequency capped',
+ value: row.frequencyCapped,
+ total: attempted,
+ type: 'warning' as const,
+ metric: 'message_frequency_capped' as EmailMetric,
+ },
].filter((issue) => issue.value > 0)
if (issues.length === 0) {
return <span className="text-muted">—</span>
diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts
index 73b2bcd83ced..14c9cb8567f0 100644
--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts
+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts
@@ -119,6 +119,15 @@ describe('buildEmailMetricInvocationSearchParams', () => {
'email_bounce_prevented',
{ inv_date_from: dateFrom, inv_date_to: dateTo, inv_search: 'Skipping send', inv_log_levels: 'INFO' },
],
+ [
+ 'message_frequency_capped',
+ {
+ inv_date_from: dateFrom,
+ inv_date_to: dateTo,
+ inv_search: 'reached the frequency cap',
+ inv_log_levels: 'INFO',
+ },
+ ],
])('maps %s to the expected Invocations-tab params', (metricKey, expected) => {
expect(buildEmailMetricInvocationSearchParams(metricKey, dateFrom, dateTo)).toEqual(expected)
})
@@ -179,6 +188,7 @@ describe('buildEmailMetricRows', () => {
email_bounced_hard: 4,
email_bounced_transient: 2,
email_bounce_prevented: 2,
+ message_frequency_capped: 3,
email_blocked: 4,
email_untracked: 7,
},
@@ -196,6 +206,7 @@ describe('buildEmailMetricRows', () => {
bouncedSoft: 2,
bouncedUnknown: 0,
bouncePrevented: 2,
+ frequencyCapped: 3,
markedAsSpam: 4,
untracked: 7,
trackedSends: 93,
diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
index ff94e1b27a8f..b197f606e9be 100644
--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
@@ -119,6 +119,7 @@ export type EmailMetric =
| 'email_untracked'
| 'email_suspended'
| 'email_paused'
+ | 'message_frequency_capped'
// The bounce rollup's per-type rows. They are fetched and shown as a breakdown of Bounced rather
// than as metrics of their own, so they stay out of `EmailMetric`, whose keys are enumerated to
@@ -154,6 +155,7 @@ export type EmailMetricRow = {
bouncedSoft: number
bouncedUnknown: number
bouncePrevented: number
+ frequencyCapped: number
// Spam complaints. Stored under the email_blocked metric name for continuity with
// historical data (see the SES webhook handler's Complaint mapping).
markedAsSpam: number
@@ -196,6 +198,7 @@ export const METRIC_COLORS: Record<string, string> = {
'Link clicked': getColorVar('data-color-5'),
Bounced: getColorVar('data-color-6'),
'Bounce prevented': getColorVar('data-color-7'),
+ 'Frequency capped': getColorVar('data-color-8'),
'Marked as spam': getColorVar('data-color-9'),
Untracked: getColorVar('data-color-10'),
Suspended: getColorVar('data-color-11'),
@@ -302,6 +305,13 @@ export const WORKFLOW_EMAIL_METRICS: Record<
color: METRIC_COLORS['Bounce prevented'],
metricNames: ['email_bounce_prevented'],
},
+ message_frequency_capped: {
+ name: 'Frequency capped',
+ description:
+ 'Total number of emails that were not sent because the person already got the most marketing messages the project allows in the cap window. The workflow moves on to the next step. Change the cap under Project settings > Workflows > Frequency cap.',
+ color: METRIC_COLORS['Frequency capped'],
+ metricNames: ['message_frequency_capped'],
+ },
email_blocked: {
name: 'Marked as spam',
description:
@@ -384,6 +394,7 @@ export const EMAIL_METRIC_INVOCATION_FILTERS: Partial<
email_bounced_undetermined: { search: 'Undetermined bounce', levels: ['WARN'] },
// MX-validation skips log "Skipping send: …" at INFO (see HogFunctionHandler in the plugin server).
email_bounce_prevented: { search: 'Skipping send', levels: ['INFO'] },
+ message_frequency_capped: { search: 'reached the frequency cap', levels: ['INFO'] },
email_blocked: { search: 'Complaint', levels: ['WARN', 'ERROR'] },
// Suspension skips log "Skipping send: email sending is suspended …" at WARN (EmailService).
email_suspended: { search: 'Skipping send', levels: ['WARN'] },
@@ -432,6 +443,7 @@ const EMAIL_METRICS: EmailMetricName[] = [
'email_untracked',
'email_suspended',
'email_paused',
+ 'message_frequency_capped',
]
const PUSH_METRICS: PushMetric[] = ['push_sent', 'push_skipped', 'push_failed', 'push_opened']
@@ -1537,6 +1549,7 @@ export function buildEmailMetricRows(
bouncedSoft: totals.email_bounced_transient ?? 0,
bouncedUnknown: totals.email_bounced_undetermined ?? 0,
bouncePrevented: totals.email_bounce_prevented ?? 0,
+ frequencyCapped: totals.message_frequency_capped ?? 0,
markedAsSpam,
untracked,
trackedSends: Math.max(0, sent - untracked),
diff --git a/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsx b/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsx
new file mode 100644
index 000000000000..e0bfab0e3971
--- /dev/null
+++ b/products/workflows/frontend/scenes/settings/WorkflowsFrequencyCapSettings.tsx
@@ -0,0 +1,123 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { teamLogic } from 'scenes/teamLogic'
+
+// Kept in step with the max_value on TeamWorkflowsConfigSerializer.
+const MAX_MESSAGES = 1000
+const MAX_WINDOW_DAYS = 30
+
+// A cleared number input reports NaN, which must save as null to turn the cap off.
+function toInputValue(value: number | null | undefined): number | null {
+ return typeof value === 'number' && Number.isFinite(value) ? value : null
+}
+
+function errorFor(value: number | null, other: number | null, max: number): string | undefined {
+ if (value === null) {
+ return other === null ? undefined : 'Fill in both fields, or clear both to turn the cap off'
+ }
+ return Number.isInteger(value) && value >= 1 && value <= max
+ ? undefined
+ : `Enter a whole number from 1 to ${max.toLocaleString()}`
+}
+
+export function WorkflowsFrequencyCapSettings(): JSX.Element {
+ const { currentTeam, currentTeamLoading } = useValues(teamLogic)
+ const { updateCurrentTeam } = useActions(teamLogic)
+ const restrictedReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
+
+ const savedMaxMessages = toInputValue(currentTeam?.workflows_config?.marketing_frequency_cap_max_messages)
+ const savedWindowDays = toInputValue(currentTeam?.workflows_config?.marketing_frequency_cap_window_days)
+
+ const [maxMessages, setMaxMessages] = useState<number | null>(savedMaxMessages)
+ const [windowDays, setWindowDays] = useState<number | null>(savedWindowDays)
+
+ useEffect(() => {
+ setMaxMessages(savedMaxMessages)
+ setWindowDays(savedWindowDays)
+ }, [savedMaxMessages, savedWindowDays])
+
+ const maxMessagesError = errorFor(maxMessages, windowDays, MAX_MESSAGES)
+ const windowDaysError = errorFor(windowDays, maxMessages, MAX_WINDOW_DAYS)
+ const unchanged = maxMessages === savedMaxMessages && windowDays === savedWindowDays
+
+ return (
+ <div className="@container">
+ <div className="flex flex-wrap gap-4">
+ <LemonField.Pure
+ className="flex-1 min-w-60"
+ label="Messages per person"
+ htmlFor="workflows-frequency-cap-max-messages"
+ error={maxMessagesError}
+ >
+ <LemonInput
+ id="workflows-frequency-cap-max-messages"
+ type="number"
+ min={1}
+ max={MAX_MESSAGES}
+ value={maxMessages ?? undefined}
+ onChange={(value) => setMaxMessages(toInputValue(value))}
+ placeholder="No cap"
+ disabledReason={restrictedReason}
+ data-attr="workflows-frequency-cap-max-messages"
+ />
+ </LemonField.Pure>
+ <LemonField.Pure
+ className="flex-1 min-w-60"
+ label="Within this many days"
+ htmlFor="workflows-frequency-cap-window-days"
+ error={windowDaysError}
+ >
+ <LemonInput
+ id="workflows-frequency-cap-window-days"
+ type="number"
+ min={1}
+ max={MAX_WINDOW_DAYS}
+ value={windowDays ?? undefined}
+ onChange={(value) => setWindowDays(toInputValue(value))}
+ placeholder="No cap"
+ disabledReason={restrictedReason}
+ data-attr="workflows-frequency-cap-window-days"
+ />
+ </LemonField.Pure>
+ </div>
+ <div className="mt-4">
+ <LemonButton
+ type="primary"
+ loading={currentTeamLoading}
+ onClick={() =>
+ updateCurrentTeam({
+ workflows_config: {
+ capture_workflows_engagement_events:
+ currentTeam?.workflows_config?.capture_workflows_engagement_events ?? false,
+ marketing_frequency_cap_max_messages: maxMessages,
+ marketing_frequency_cap_window_days: windowDays,
+ },
+ })
+ }
+ disabledReason={
+ restrictedReason ??
+ (maxMessagesError || windowDaysError
+ ? 'Fix the fields above to save'
+ : unchanged
+ ? 'No changes to save'
+ : currentTeamLoading
+ ? 'Saving'
+ : undefined)
+ }
+ data-attr="workflows-frequency-cap-save"
+ >
+ Save
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5ea3cdc694a9..69d8476c138e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -82088,6 +82088,20 @@ export namespace Schemas {
* @nullable
*/
default_email_integration_id?: number | null;
+ /**
+ * Most marketing messages one person can get in the window, across all workflows. Set this together with marketing_frequency_cap_window_days. Set both to null to turn the cap off.
+ * @minimum 1
+ * @maximum 1000
+ * @nullable
+ */
+ marketing_frequency_cap_max_messages?: number | null;
+ /**
+ * Length of the rolling frequency cap window in days. Set this together with marketing_frequency_cap_max_messages. Set both to null to turn the cap off.
+ * @minimum 1
+ * @maximum 30
+ * @nullable
+ */
+ marketing_frequency_cap_window_days?: number | null;
}
export interface TeamFeatureFlagPolicyConfig {
diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.ts
index 2c832e512eba..b63eaaf2dc8a 100644
--- a/services/mcp/src/generated/core/api.ts
+++ b/services/mcp/src/generated/core/api.ts
@@ -353,6 +353,10 @@ export const organizationsProjectsCreateBodyWorkflowsConfigWorkflowTaskRateLimit
export const organizationsProjectsCreateBodyWorkflowsConfigWorkflowTaskTeamRateLimitPerDayMin = 0
+export const organizationsProjectsCreateBodyWorkflowsConfigMarketingFrequencyCapMaxMessagesMax = 1000
+
+export const organizationsProjectsCreateBodyWorkflowsConfigMarketingFrequencyCapWindowDaysMax = 30
+
export const organizationsProjectsCreateBodyDefaultDataThemeMin = -2147483648
export const organizationsProjectsCreateBodyDefaultDataThemeMax = 2147483647
@@ -2767,6 +2771,22 @@ export const OrganizationsProjectsCreateBody = () => zod
.describe(
"ID of the verified email integration that new broadcasts and workflow email steps use as their sender. Null means no default. Set automatically when the project's first email sender is verified, and cleared when that integration is deleted."
),
+ marketing_frequency_cap_max_messages: zod
+ .number()
+ .min(1)
+ .max(organizationsProjectsCreateBodyWorkflowsConfigMarketingFrequencyCapMaxMessagesMax)
+ .nullish()
+ .describe(
+ 'Most marketing messages one person can get in the window, across all workflows. Set this together with marketing_frequency_cap_window_days. Set both to null to turn the cap off.'
+ ),
+ marketing_frequency_cap_window_days: zod
+ .number()
+ .min(1)
+ .max(organizationsProjectsCreateBodyWorkflowsConfigMarketingFrequencyCapWindowDaysMax)
+ .nullish()
+ .describe(
+ 'Length of the rolling frequency cap window in days. Set this together with marketing_frequency_cap_max_messages. Set both to null to turn the cap off.'
+ ),
})
.optional(),
feature_flag_policy_config: zod
@@ -3064,6 +3084,10 @@ export const organizationsProjectsPartialUpdateBodyWorkflowsConfigWorkflowTaskRa
export const organizationsProjectsPartialUpdateBodyWorkflowsConfigWorkflowTaskTeamRateLimitPerDayMin = 0
+export const organizationsProjectsPartialUpdateBodyWorkflowsConfigMarketingFrequencyCapMaxMessagesMax = 1000
+
+export const organizationsProjectsPartialUpdateBodyWorkflowsConfigMarketingFrequencyCapWindowDaysMax = 30
+
export const organizationsProjectsPartialUpdateBodyDefaultDataThemeMin = -2147483648
export const organizationsProjectsPartialUpdateBodyDefaultDataThemeMax = 2147483647
@@ -5486,6 +5510,22 @@ export const OrganizationsProjectsPartialUpdateBody = () => zod
.describe(
"ID of the verified email integration that new broadcasts and workflow email steps use as their sender. Null means no default. Set automatically when the project's first email sender is verified, and cleared when that integration is deleted."
),
+ marketing_frequency_cap_max_messages: zod
+ .number()
+ .min(1)
+ .max(organizationsProjectsPartialUpdateBodyWorkflowsConfigMarketingFrequencyCapMaxMessagesMax)
+ .nullish()
+ .describe(
+ 'Most marketing messages one person can get in the window, across all workflows. Set this together with marketing_frequency_cap_window_days. Set both to null to turn the cap off.'
+ ),
+ marketing_frequency_cap_window_days: zod
+ .number()
+ .min(1)
+ .max(organizationsProjectsPartialUpdateBodyWorkflowsConfigMarketingFrequencyCapWindowDaysMax)
+ .nullish()
+ .describe(
+ 'Length of the rolling frequency cap window in days. Set this together with marketing_frequency_cap_max_messages. Set both to null to turn the cap off.'
+ ),
})
.optional(),
feature_flag_policy_config: zod
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
index 7d3f60d8cb4d..6a645f72c6ba 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
@@ -4300,6 +4300,32 @@
"enum": ["off", "opt_out", "opt_in"],
"type": "string"
},
+ "marketing_frequency_cap_max_messages": {
+ "anyOf": [
+ {
+ "maximum": 1000,
+ "minimum": 1,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Most marketing messages one person can get in the window, across all workflows. Set this together with marketing_frequency_cap_window_days. Set both to null to turn the cap off."
+ },
+ "marketing_frequency_cap_window_days": {
+ "anyOf": [
+ {
+ "maximum": 30,
+ "minimum": 1,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Length of the rolling frequency cap window in days. Set this together with marketing_frequency_cap_max_messages. Set both to null to turn the cap off."
+ },
"workflow_task_rate_limit_per_day": {
"anyOf": [
{