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): per-workflow email sending rate limit (#87647)

Meikel Ratz7a7f9f8a4f5a
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 294f562ea83a..1105cb2a763c 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -558,6 +558,8 @@ export const FEATURE_FLAGS = {
WEB_ANALYTICS_TOOLTIP_COMPARISON_LABELS: 'web-analytics-tooltip-comparison-labels', // owner: @lricoy #team-web-analytics
WORKFLOW_AI_TASK_ACTION: 'workflow-ai-task-action', // owner: @mayteio #team-workflows
WORKFLOWS_DELAY_UNTIL_DATE: 'workflows-delay-until-date', // owner: @dmarchuk #team-workflows
+ WORKFLOWS_EMAIL_RATE_LIMIT: 'workflows-email-rate-limit', // owner: #team-workflows
+ WORKFLOWS_EMAIL_REPUTATION: 'workflows-email-reputation', // owner: #team-workflows
WORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflows
WORKFLOWS_INCIDENT_REPLAY: 'workflows-incident-replay', // owner: #team-workflows
WORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflows
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index a06ea4a7250b..2600505e0eb5 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -42,6 +42,7 @@ import { HogFunctionMonitoringService } from './services/monitoring/hog-function
import { HogInvocationResultsService } from './services/monitoring/hog-invocation-results.service'
import { HogWatcherService } from './services/monitoring/hog-watcher.service'
import { NativeDestinationExecutorService } from './services/native-destination-executor.service'
+import { RateLimiterService } from './services/rate-limiter/rate-limiter.service'
import { SegmentDestinationExecutorService } from './services/segment-destination-executor.service'
import { WarehouseWebhooksService } from './services/warehouse/warehouse-webhooks.service'
import { MAX_FETCH_TIMEOUT_MS, cdpTrackedFetch } from './utils/cdp-fetch'
@@ -403,6 +404,11 @@ export function createCdpCoreServices(
transientBounceThreshold: config.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD,
})
const recipientsManager = new RecipientsManagerService(deps.postgres)
+ // Per-workflow send pacing rides the SES Valkey pool, which is only populated on pods that
+ // execute email actions — exactly where the limit is enforced. Null elsewhere disables it.
+ const workflowEmailRateLimiter = deps.emailValidationValkey
+ ? new RateLimiterService(deps.emailValidationValkey, { name: 'workflow-email' })
+ : null
const emailService = new EmailService(
{
sesAccessKeyId: config.SES_ACCESS_KEY_ID,
@@ -420,7 +426,8 @@ export function createCdpCoreServices(
trackingCodeSigner,
emailSuppressionService,
recipientsManager,
- messageAssetsService
+ messageAssetsService,
+ workflowEmailRateLimiter
)
const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)
const hogInputsService = new HogInputsService(deps.integrationManager, recipientTokensService, deps.encryptedFields)
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 210fd78530e6..d7cfd45431ac 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -251,8 +251,10 @@ export function getDefaultCdpConfig(): CdpConfig {
CDP_VALKEY_TLS: false,
CDP_VALKEY_READ_FEATURES: '',
- SES_RATE_LIMITER_VALKEY_HOST: '',
- SES_RATE_LIMITER_VALKEY_PORT: 6379,
+ // Dev points at the compose stack's Valkey (same instance as CDP_VALKEY) so the SES gate,
+ // per-workflow email rate limits, and the MX-validation cache are exercisable locally.
+ SES_RATE_LIMITER_VALKEY_HOST: isDevEnv() ? '127.0.0.1' : '',
+ SES_RATE_LIMITER_VALKEY_PORT: isDevEnv() ? 6390 : 6379,
SES_RATE_LIMITER_VALKEY_PASSWORD: '',
SES_RATE_LIMITER_VALKEY_TLS: false,
diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.ts
index f09af3f9ab00..ea85d81d84fb 100644
--- a/nodejs/src/cdp/schema/hogflow.ts
+++ b/nodejs/src/cdp/schema/hogflow.ts
@@ -2,6 +2,13 @@ import { z } from 'zod'
import { CyclotronInputMappingSchema, CyclotronInputSchema, CyclotronJobInputSchemaTypeSchema } from './cyclotron'
+export const HogFlowEmailSendingRateLimitSchema = z.object({
+ count: z.number().int().positive(),
+ period: z.enum(['minute', 'hour']),
+})
+
+export type HogFlowEmailSendingRateLimit = z.infer<typeof HogFlowEmailSendingRateLimitSchema>
+
const HogFlowOutputVariableSchema = z.object({
key: z.string(),
result_path: z.string().optional().nullable(), // The path within the action result to store, e.g. 'response.user.id'
@@ -324,6 +331,9 @@ export const HogFlowSchema = z.object({
'exit_on_trigger_not_matched_or_conversion',
'exit_only_at_end',
]),
+ // User-configured email pacing for deliverability. The email worker holds this flow's sends
+ // under the limit by rescheduling over-limit sends, never dropping them.
+ email_sending_rate_limit: HogFlowEmailSendingRateLimitSchema.optional().nullable(),
actions: z.array(HogFlowActionSchema),
// Secret function inputs, split out of `actions` and stored Fernet-encrypted at rest, keyed by
// action id then input key. Decrypted by the manager and merged back into `action.config.inputs`
diff --git a/nodejs/src/cdp/services/hogflows/__snapshots__/hogflow-manager.service.test.ts.snap b/nodejs/src/cdp/services/hogflows/__snapshots__/hogflow-manager.service.test.ts.snap
index b28063029836..b16c031ac3ba 100644
--- a/nodejs/src/cdp/services/hogflows/__snapshots__/hogflow-manager.service.test.ts.snap
+++ b/nodejs/src/cdp/services/hogflows/__snapshots__/hogflow-manager.service.test.ts.snap
@@ -48,6 +48,7 @@ exports[`HogFlowManager returns the hog flow 1`] = `
"type": "continue",
},
],
+ "email_sending_rate_limit": null,
"exit_condition": "exit_on_conversion",
"id": "<REPLACED-UUID-0>",
"name": "Test Hog Flow team 1",
@@ -115,6 +116,7 @@ exports[`HogFlowManager returns the hog flow 1`] = `
"type": "continue",
},
],
+ "email_sending_rate_limit": null,
"exit_condition": "exit_on_conversion",
"id": "<REPLACED-UUID-1>",
"name": "Test Hog Flow team 1 - other",
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts
index 3cb022b1e020..b74cfc750494 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts
@@ -45,7 +45,9 @@ export class HogFlowFunctionsService {
mappings,
created_at: '',
updated_at: '',
- metadata: config,
+ // The action's config, plus flow-level send settings the email service needs at the
+ // send choke point, where only the synthetic hog function is in scope.
+ metadata: { ...config, email_sending_rate_limit: hogFlow.email_sending_rate_limit ?? null },
}
return hogFunction
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts
index 3d0a698a065d..fe25902786af 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts
@@ -33,6 +33,7 @@ const HOG_FLOW_FIELDS = [
'trigger_masking',
'conversion',
'exit_condition',
+ 'email_sending_rate_limit',
'edges',
'actions',
'encrypted_inputs',
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.ts
index 1eff15b0426b..be2c22c436ef 100644
--- a/nodejs/src/cdp/services/messaging/email.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts
@@ -13,6 +13,7 @@ import { getFirstTeam, resetTestDatabase } 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 { RateLimiterService } from '../rate-limiter/rate-limiter.service'
import { EmailSuppressionService, emailSuppressionConfigFromEnv } from './email-suppression.service'
import { EmailService, parseAddressList, sanitizeEmailSubject } from './email.service'
import { MailDevAPI } from './helpers/maildev'
@@ -453,6 +454,104 @@ describe('EmailService', () => {
)
})
})
+
+ describe('workflow sending rate limit', () => {
+ let claimUpTo: jest.Mock
+ let limitedService: EmailService
+ let limitedSendSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ claimUpTo = jest.fn().mockResolvedValue(1)
+ limitedService = new EmailService(
+ {
+ sesAccessKeyId: hub.SES_ACCESS_KEY_ID,
+ sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,
+ sesRegion: hub.SES_REGION,
+ sesEndpoint: hub.SES_ENDPOINT,
+ sesTrackedConfigurationSet: hub.SES_TRACKED_CONFIGURATION_SET,
+ sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,
+ sesTenantAttributionEnabled: hub.EMAIL_SES_TENANT_ATTRIBUTION_ENABLED,
+ },
+ hub.integrationManager,
+ new TeamWorkflowsConfigService(hub.postgres),
+ hub.ENCRYPTION_SALT_KEYS,
+ hub.SITE_URL,
+ new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),
+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()),
+ new RecipientsManagerService(hub.postgres),
+ undefined,
+ { claimUpTo } as unknown as RateLimiterService
+ )
+ limitedSendSpy = jest.spyOn(limitedService.sesV2Client!, 'send') as any
+ limitedSendSpy.mockResolvedValue({ MessageId: 'test-message-id' })
+ invocation.hogFunction.metadata = {
+ email_sending_rate_limit: { count: 120, period: 'minute' },
+ }
+ })
+
+ it('reschedules without sending when the bucket denies a token', async () => {
+ claimUpTo.mockResolvedValue(0)
+
+ const before = Date.now()
+ const result = await limitedService.executeSendEmail(invocation)
+
+ expect(limitedSendSpy).not.toHaveBeenCalled()
+ expect(result.error).toBeUndefined()
+ expect(result.finished).toBe(false)
+ expect(result.invocation.queueScheduledAt).toBeDefined()
+ // The reschedule must carry the email payload forward: without queueParameters the
+ // retry has nothing to send and the throttled email is dropped rather than delayed.
+ expect(result.invocation.queueParameters).toEqual(invocation.queueParameters)
+ // 120/minute refills a token every 500ms, so the clamped jittered wake lands in [1s, 2s].
+ const scheduledMs = result.invocation.queueScheduledAt!.toMillis()
+ expect(scheduledMs).toBeGreaterThanOrEqual(before + 1000)
+ expect(scheduledMs).toBeLessThan(before + 3000)
+ // No business metric on a pacing delay — the eventual send produces email_sent.
+ expect(result.metrics ?? []).toEqual([])
+ })
+
+ it('claims one token scoped to the workflow and sends when granted', async () => {
+ const result = await limitedService.executeSendEmail(invocation)
+
+ expect(claimUpTo).toHaveBeenCalledWith({
+ key: `@posthog/workflow-email-rate/${team.id}/function-1`,
+ requested: 1,
+ // Burst capacity is ~1s of budget (not the count), so the first period can't
+ // send ~2x the limit and an idle-expired bucket can't re-burst.
+ capacity: 2,
+ refillPerSecond: 2,
+ })
+ expect(result.finished).toBe(true)
+ expect(limitedSendSpy).toHaveBeenCalled()
+ })
+
+ it.each([
+ ['no rate limit is configured', (): void => void (invocation.hogFunction.metadata = {})],
+ [
+ 'the configured value is malformed',
+ (): void =>
+ void (invocation.hogFunction.metadata = { email_sending_rate_limit: { count: 'lots' } }),
+ ],
+ ])('does not consult the bucket when %s', async (_name, setup) => {
+ setup()
+
+ const result = await limitedService.executeSendEmail(invocation)
+
+ expect(claimUpTo).not.toHaveBeenCalled()
+ expect(result.finished).toBe(true)
+ expect(limitedSendSpy).toHaveBeenCalled()
+ })
+
+ it('skips the limit for test sends', async () => {
+ claimUpTo.mockResolvedValue(0)
+
+ const result = await limitedService.executeSendEmail(invocation, true)
+
+ expect(claimUpTo).not.toHaveBeenCalled()
+ expect(result.finished).toBe(true)
+ expect(limitedSendSpy).toHaveBeenCalled()
+ })
+ })
})
describe('native email sending with maildev', () => {
let invocation: CyclotronJobInvocationHogFunction
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index 2354d494e59a..5a100b865b2e 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -4,10 +4,12 @@ import { SendMailOptions } from 'nodemailer'
import { Counter } from 'prom-client'
import { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'
+import { HogFlowEmailSendingRateLimit, HogFlowEmailSendingRateLimitSchema } from '~/cdp/schema/hogflow'
import {
CyclotronJobInvocationHogFlow,
CyclotronJobInvocationHogFunction,
CyclotronJobInvocationResult,
+ HogFunctionType,
IntegrationType,
MessageAssetRow,
} from '~/cdp/types'
@@ -18,6 +20,7 @@ import { logger } from '~/common/utils/logger'
import { IntegrationManagerService } from '../managers/integration-manager.service'
import { RecipientManagerRecipient, RecipientsManagerService } from '../managers/recipients-manager.service'
import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'
+import { RateLimiterService } from '../rate-limiter/rate-limiter.service'
import { selectEmailSenderIntegrationId } from './email-sender-selection'
import { EmailSuppressionService } from './email-suppression.service'
import { addTrackingToEmail, resolveEmailEngagementDistinctId } from './email-tracking.service'
@@ -78,6 +81,32 @@ function pickThrottleRetryDelayMs(): number {
return 500 + Math.floor(Math.random() * 500)
}
+const workflowEmailRateLimitedTotal = new Counter({
+ name: 'cdp_workflow_email_rate_limited_total',
+ help: 'Email sends delayed by a user-configured per-workflow sending rate limit.',
+})
+
+// The metadata blob is the flow action's config plus flow-level keys stamped in by
+// HogFlowFunctionsService.buildHogFunction; parse defensively since it is untyped.
+function parseWorkflowEmailRateLimit(metadata: HogFunctionType['metadata']): HogFlowEmailSendingRateLimit | null {
+ const raw = metadata?.email_sending_rate_limit
+ if (!raw) {
+ return null
+ }
+ const parsed = HogFlowEmailSendingRateLimitSchema.safeParse(raw)
+ return parsed.success ? parsed.data : null
+}
+
+function pickWorkflowRateLimitRetryDelayMs(refillPerSecond: number): number {
+ // Wake around when the next token accrues. The 1x-2x jitter spreads a queued backlog's
+ // retries so they don't all re-dequeue (and re-claim against one token) at the same instant.
+ // Clamped so second-scale limits don't churn the queue and hour-scale limits still wake
+ // often enough to drain promptly once capacity frees up.
+ const tokenIntervalMs = 1000 / refillPerSecond
+ const baseMs = Math.min(Math.max(tokenIntervalMs, 1_000), 5 * 60 * 1_000)
+ return Math.floor(baseMs * (1 + Math.random()))
+}
+
export interface EmailServiceConfig {
sesAccessKeyId: string
sesSecretAccessKey: string
@@ -158,7 +187,8 @@ export class EmailService {
private trackingCodeSigner: EmailTrackingCodeSigner,
private emailSuppressionService: EmailSuppressionService,
private recipientsManager: RecipientsManagerService,
- private messageAssetsService?: MessageAssetsService
+ private messageAssetsService?: MessageAssetsService,
+ private workflowEmailRateLimiter: RateLimiterService | null = null
) {
this.sesV2Client = this.sesConfig.sesRegion
? new SESv2Client({
@@ -261,6 +291,45 @@ export class EmailService {
// (workflow action or email destination hog function) resolves it the same way.
trackingEnabled = await this.resolveTrackingEnabled(result.invocation, params)
+ // User-configured per-workflow pacing. Claimed last, after every skip gate, so a
+ // suspended or suppressed send never spends a token. Test sends bypass it. When the
+ // limiter's Valkey is down claimUpTo returns 0, so sends wait (never drop) until it
+ // recovers — same fail-closed stance as the global SES gate.
+ const workflowRateLimit = parseWorkflowEmailRateLimit(invocation.hogFunction.metadata)
+ if (workflowRateLimit && this.workflowEmailRateLimiter && !isTest) {
+ const periodSeconds = workflowRateLimit.period === 'minute' ? 60 : 3600
+ const refillPerSecond = workflowRateLimit.count / periodSeconds
+ // Burst capacity is about one second of budget, not the full count: a bucket that
+ // could hold `count` starts full and refills within the same period, so a fresh (or
+ // idle-expired) bucket would send ~2x the configured limit in its first period.
+ // A near-empty bucket keeps every window at ~count and spreads sends evenly, which
+ // is what the pacing is for.
+ const capacity = Math.max(1, Math.ceil(refillPerSecond))
+ const granted = await this.workflowEmailRateLimiter.claimUpTo({
+ key: `@posthog/workflow-email-rate/${invocation.teamId}/${invocation.functionId}`,
+ requested: 1,
+ capacity,
+ refillPerSecond,
+ })
+ if (granted === 0) {
+ workflowEmailRateLimitedTotal.inc()
+ result.finished = false
+ // Re-attach the email payload before rescheduling. createInvocationResult cleared
+ // queueParameters, so without this the rescheduled dequeue has no 'email' params to
+ // re-enter the send path — the retry would resume the Hog VM instead and drop the
+ // send. Mirrors the fetch-retry (`result.invocation.queueParameters = params`) and
+ // queue-routing paths, which re-attach the same way.
+ result.invocation.queueParameters = params
+ const retryDelayMs = pickWorkflowRateLimitRetryDelayMs(refillPerSecond)
+ result.invocation.queueScheduledAt = DateTime.utc().plus({ milliseconds: retryDelayMs })
+ addLog(
+ 'info',
+ `Sending rate limit reached (${workflowRateLimit.count} emails per ${workflowRateLimit.period}); retrying this email in ${Math.round(retryDelayMs / 1000)}s`
+ )
+ return result
+ }
+ }
+
switch (integration.config.provider ?? 'ses') {
case 'maildev':
await this.sendEmailWithMaildev(result, params, from, trackingEnabled, isTest)
diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts
index 650fc0f8dac9..2c24d4d5992e 100644
--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts
+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts
@@ -133,7 +133,7 @@ describe('RateLimiterService', () => {
}
it('increments granted_full when the grant equals the request', async () => {
- const labels = { limiter: 'ses-rate-limiter', key: KEY, result: 'granted_full' }
+ const labels = { limiter: 'ses-rate-limiter', result: 'granted_full' }
const before = await readCounter(labels)
const granted = await limiter.claimUpTo({ key: KEY, requested: 5, capacity: 10, refillPerSecond: 0 })
@@ -147,7 +147,7 @@ describe('RateLimiterService', () => {
// Drain to 2 tokens, then ask for 5.
await limiter.claimUpTo({ key: KEY, requested: 8, capacity: 10, refillPerSecond: 0 })
- const labels = { limiter: 'ses-rate-limiter', key: KEY, result: 'granted_partial' }
+ const labels = { limiter: 'ses-rate-limiter', result: 'granted_partial' }
const before = await readCounter(labels)
const granted = await limiter.claimUpTo({ key: KEY, requested: 5, capacity: 10, refillPerSecond: 0 })
@@ -161,7 +161,7 @@ describe('RateLimiterService', () => {
// Drain the bucket fully.
await limiter.claimUpTo({ key: KEY, requested: 10, capacity: 10, refillPerSecond: 0 })
- const labels = { limiter: 'ses-rate-limiter', key: KEY, result: 'denied' }
+ const labels = { limiter: 'ses-rate-limiter', result: 'denied' }
const before = await readCounter(labels)
const granted = await limiter.claimUpTo({ key: KEY, requested: 5, capacity: 10, refillPerSecond: 0 })
@@ -179,7 +179,7 @@ describe('RateLimiterService', () => {
} as unknown as RedisV2
const brokenLimiter = new RateLimiterService(brokenValkey, { name: 'broken-limiter' })
- const labels = { limiter: 'broken-limiter', key: KEY, result: 'valkey_error' }
+ const labels = { limiter: 'broken-limiter', result: 'valkey_error' }
const before = await readCounter(labels)
const granted = await brokenLimiter.claimUpTo({
diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts
index 8aa5712d3c55..f1566e993c46 100644
--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts
+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts
@@ -20,7 +20,10 @@ import { logger } from '~/common/utils/logger'
const claimCounter = new Counter({
name: 'cdp_rate_limiter_claim_total',
help: 'Token-bucket claim outcomes from the SES rate limiter Valkey.',
- labelNames: ['limiter', 'key', 'result'],
+ // No per-bucket `key` label: the workflow-email limiter's key embeds team and flow id, which
+ // would grow the series count without bound. `limiter` already separates the callers; per-key
+ // diagnosis stays available through the structured warn logs below.
+ labelNames: ['limiter', 'result'],
})
const claimLatency = new Histogram({
@@ -164,19 +167,19 @@ export class RateLimiterService {
key: req.key,
raw: result,
})
- claimCounter.inc({ limiter: this.config.name, key: req.key, result: 'valkey_error' })
+ claimCounter.inc({ limiter: this.config.name, result: 'valkey_error' })
return 0
}
const outcome = granted === 0 ? 'denied' : granted < req.requested ? 'granted_partial' : 'granted_full'
- claimCounter.inc({ limiter: this.config.name, key: req.key, result: outcome })
+ claimCounter.inc({ limiter: this.config.name, result: outcome })
return granted
} catch (err) {
logger.warn('🪙', `RateLimiterService(${this.config.name}) claim threw`, {
key: req.key,
error: String(err),
})
- claimCounter.inc({ limiter: this.config.name, key: req.key, result: 'valkey_error' })
+ claimCounter.inc({ limiter: this.config.name, result: 'valkey_error' })
return 0
} finally {
endTimer()
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index fcb5f64a8cd8..501448fac6ad 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -3493,10 +3493,7 @@ describe('Workflows E2E (email queue)', () => {
}
const data = await metric.get()
return data.values
- .filter(
- (v: any) =>
- v.labels.result === 'denied' && v.labels.limiter === limiterName && v.labels.key === bucketKey
- )
+ .filter((v: any) => v.labels.result === 'denied' && v.labels.limiter === limiterName)
.reduce((sum: number, v: any) => sum + v.value, 0)
}
const deniedBefore = await readDeniedCount()
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 1926ee1f2d1f..042fa3393748 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -180,10 +180,15 @@ DRAFT_CONTENT_FIELDS = (
"trigger_masking",
"conversion",
"exit_condition",
+ "email_sending_rate_limit",
"abort_action",
"variables",
)
+# Server-side rollout gate for email sending rate limits. Key shared with FEATURE_FLAGS in
+# frontend/src/lib/constants.tsx, where the same flag hides the editor control.
+EMAIL_SENDING_RATE_LIMIT_FLAG = "workflows-email-rate-limit"
+
# Compiled from the author's filters rather than written by them, and only present once a condition has
# been through validation. Comparing them would make an unchanged condition look edited.
@@ -1726,6 +1731,32 @@ class HogFlowConversionSerializer(serializers.Serializer):
return value
+class HogFlowEmailSendingRateLimitSerializer(serializers.Serializer):
+ count = serializers.IntegerField(
+ min_value=1,
+ max_value=1_000_000,
+ help_text="Maximum number of emails this workflow sends per period.",
+ )
+ period = serializers.ChoiceField(
+ choices=["minute", "hour"],
+ help_text="Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.",
+ )
+
+ def validate(self, data):
+ # A PATCH propagates partial=True into nested serializers, which would let a lone
+ # {"period": ...} skip the required count and store a shape the worker can't enforce.
+ # The value is atomic: replace it whole or clear it with null.
+ missing = [field for field in ("count", "period") if field not in data]
+ if missing:
+ raise serializers.ValidationError(f"Both count and period are required, missing: {', '.join(missing)}.")
+ return data
+
+ def to_representation(self, value):
+ # Pass stored JSON through untouched so a legacy or hand-written row that doesn't match
+ # the declared fields can still render (and be fixed) instead of crashing the read.
+ return value
+
+
class HogFlowScheduleSerializer(serializers.ModelSerializer):
class Meta:
model = HogFlowSchedule
@@ -2020,6 +2051,7 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Mod
"trigger_masking",
"conversion",
"exit_condition",
+ "email_sending_rate_limit",
"edges",
"actions",
"abort_action",
@@ -2124,6 +2156,15 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
"exit_on_trigger_not_matched_or_conversion: both (needs 'conversion')."
),
)
+ email_sending_rate_limit = HogFlowEmailSendingRateLimitSerializer(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker "
+ "spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead "
+ "of failing. Null disables pacing."
+ ),
+ )
edges = serializers.ListField(
child=HogFlowEdgeSerializer(),
required=False,
@@ -2271,6 +2312,7 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
"trigger_masking",
"conversion",
"exit_condition",
+ "email_sending_rate_limit",
"edges",
"actions",
"abort_action",
@@ -2302,6 +2344,29 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
instance = cast(Optional[HogFlow], self.instance)
is_draft = self.context.get("is_draft")
+ # New adoption of the email sending rate limit is flag-gated server-side: the UI hides the
+ # control behind the same flag, but API and MCP callers write workflows directly. Only new
+ # adoption is policed — resubmitting the stored or draft-staged value and clearing to null
+ # always pass, so a flag dial-down can't brick saves or publishes of workflows that already
+ # carry a limit. Uses the same fail-closed flag evaluation as gated templates.
+ if "email_sending_rate_limit" in data:
+ # Nested use (the `configuration` override on test invocations) never binds
+ # self.instance — the flow arrives via context, same as in to_internal_value — so
+ # resolve it here too or a test run echoing a stored limit would fail the gate.
+ gate_instance = instance or cast(Optional[HogFlow], self.context.get("instance"))
+ new_value = data["email_sending_rate_limit"]
+ existing_values = [gate_instance.email_sending_rate_limit if gate_instance else None]
+ if gate_instance is not None and isinstance(gate_instance.draft, dict):
+ existing_values.append(gate_instance.draft.get("email_sending_rate_limit"))
+ if new_value is not None and new_value not in existing_values:
+ # Outside a request (internal re-saves, direct construction) there is no team
+ # to evaluate the flag against.
+ get_team = self.context.get("get_team")
+ if get_team is not None and not gated_template_enabled(EMAIL_SENDING_RATE_LIMIT_FLAG, get_team()):
+ raise serializers.ValidationError(
+ {"email_sending_rate_limit": "Email sending rate limits are not enabled for this project."}
+ )
+
# Reject duplicate action ids on any client-submitted actions array (create/update/graph), on
# every path - not just the surgical /graph endpoint where validate_graph enforces it. Secret
# recovery is keyed by action id, so a forged duplicate id could otherwise pull another action's
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index bdfe698a10bc..1e2185f5eb4e 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -178,6 +178,65 @@ class TestHogFlowAPI(APIBaseTest):
assert response.status_code == 201, response.json()
return response.json()["id"]
+ def test_email_sending_rate_limit_round_trip(self):
+ flow_id = self._create_simple_flow()
+
+ with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=True):
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {"email_sending_rate_limit": {"count": 250, "period": "hour"}},
+ )
+ assert response.status_code == 200, response.json()
+ assert response.json()["email_sending_rate_limit"] == {"count": 250, "period": "hour"}
+ assert HogFlow.objects.get(id=flow_id).email_sending_rate_limit == {"count": 250, "period": "hour"}
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {"email_sending_rate_limit": None},
+ )
+ assert response.status_code == 200, response.json()
+ assert response.json()["email_sending_rate_limit"] is None
+
+ @parameterized.expand(
+ [
+ ("zero_count", {"count": 0, "period": "minute"}),
+ ("missing_count", {"period": "minute"}),
+ ("unknown_period", {"count": 10, "period": "day"}),
+ ]
+ )
+ def test_email_sending_rate_limit_rejects_invalid_values(self, _name, value):
+ flow_id = self._create_simple_flow()
+
+ with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=True):
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {"email_sending_rate_limit": value},
+ )
+ assert response.status_code == 400, response.json()
+
+ def test_email_sending_rate_limit_gated_on_feature_flag(self):
+ # The UI hides the control behind the flag, but API callers hit the serializer directly —
+ # without the server-side gate any team could adopt the feature before its rollout.
+ flow_id = self._create_simple_flow()
+ url = f"/api/projects/{self.team.id}/hog_flows/{flow_id}"
+ value = {"email_sending_rate_limit": {"count": 100, "period": "minute"}}
+
+ with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=False) as mock_gate:
+ response = self.client.patch(url, value)
+ assert response.status_code == 400, response.json()
+ assert mock_gate.call_args.args[0] == "workflows-email-rate-limit"
+
+ with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=True):
+ response = self.client.patch(url, value)
+ assert response.status_code == 200, response.json()
+
+ # A flag dial-down must not brick saves that resubmit the stored value, nor block clearing.
+ with patch("products.workflows.backend.api.hog_flow.gated_template_enabled", return_value=False):
+ response = self.client.patch(url, value)
+ assert response.status_code == 200, response.json()
+ response = self.client.patch(url, {"email_sending_rate_limit": None})
+ assert response.status_code == 200, response.json()
+
@parameterized.expand(
[
("name_match", "welcome", {"Welcome email"}),
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index e32f4994923b..57c0f811d5c2 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -870,6 +870,13 @@ export interface hogFlowEditorLogicActions {
to: string
type: 'branch' | 'continue'
}[]
+ email_sending_rate_limit?:
+ | {
+ count: number
+ period: 'hour' | 'minute'
+ }
+ | null
+ | undefined
exit_condition:
| 'exit_on_conversion'
| 'exit_on_trigger_not_matched'
@@ -1710,6 +1717,13 @@ export interface hogFlowEditorLogicActions {
to: string
type: 'branch' | 'continue'
}[]
+ email_sending_rate_limit?:
+ | {
+ count: number
+ period: 'hour' | 'minute'
+ }
+ | null
+ | undefined
exit_condition:
| 'exit_on_conversion'
| 'exit_on_trigger_not_matched'
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
index b70d8caa16fb..dc9957b63cd5 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
@@ -1,6 +1,6 @@
import { Node } from '@xyflow/react'
import { useActions, useValues } from 'kea'
-import { useMemo, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import {
IconBolt,
@@ -380,6 +380,7 @@ export function StepTriggerConfiguration({ node }: { node: Node<TriggerAction> }
) : node.data.config.type === 'tracking_pixel' ? (
<StepTriggerConfigurationTrackingPixel action={node.data} config={node.data.config} />
) : null}
+ <SendingRateLimitSection />
</div>
)
}
@@ -979,6 +980,104 @@ function ConversionGoalSection(): JSX.Element {
)
}
+function SendingRateLimitSection(): JSX.Element | null {
+ const { setWorkflowValue } = useActions(workflowLogic)
+ const { workflow } = useValues(workflowLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+
+ const rateLimit = workflow.email_sending_rate_limit ?? null
+ // Mirror the count locally so clearing the field doesn't snap back to the committed value
+ // mid-edit; reconcile when the stored value changes externally (toggle, another editor).
+ const [displayCount, setDisplayCount] = useState<number | undefined>(rateLimit?.count)
+ useEffect(() => {
+ setDisplayCount(rateLimit?.count)
+ }, [rateLimit?.count])
+
+ // Flag-gated rollout, but a workflow that already carries a limit keeps the section after a
+ // flag dial-down so the limit stays visible and removable.
+ if (!featureFlags[FEATURE_FLAGS.WORKFLOWS_EMAIL_RATE_LIMIT] && !rateLimit) {
+ return null
+ }
+
+ const hasEmailAction = workflow.actions.some((action) => action.type === 'function_email')
+ // Stay visible while a limit is set even without an email step, so it can still be removed.
+ if (!hasEmailAction && !rateLimit) {
+ return null
+ }
+
+ return (
+ <>
+ <LemonDivider />
+ <div className="flex flex-col w-full py-2 gap-2">
+ <span className="flex gap-1 items-center">
+ <IconClock className="text-lg" />
+ <span className="text-md font-semibold">Email sending rate limit (optional)</span>
+ <Tooltip title="Sending a large volume too quickly can hurt deliverability. Emails over the limit are delayed until capacity frees up, not dropped.">
+ <IconInfo className="text-secondary" />
+ </Tooltip>
+ </span>
+ <p className="mb-0">Spread this workflow's emails out over time instead of sending all at once.</p>
+ <LemonCheckbox
+ checked={!!rateLimit}
+ onChange={(checked) =>
+ setWorkflowValue('email_sending_rate_limit', checked ? { count: 100, period: 'minute' } : null)
+ }
+ label="Limit sending rate"
+ data-attr="workflow-email-rate-limit-toggle"
+ />
+ {rateLimit ? (
+ <div className="flex items-center gap-2">
+ <span>Send at most</span>
+ <LemonInput
+ type="number"
+ size="small"
+ className="w-24"
+ min={1}
+ // Mirror the API's accepted range (min_value=1, max_value=1_000_000) so an
+ // out-of-range entry is clamped here instead of failing the workflow save.
+ max={1_000_000}
+ aria-label="Maximum emails per period"
+ value={displayCount ?? NaN}
+ onChange={(count) => {
+ if (count == null || !Number.isFinite(count)) {
+ setDisplayCount(undefined)
+ return
+ }
+ const next = Math.min(1_000_000, Math.max(1, Math.floor(count)))
+ setDisplayCount(next)
+ setWorkflowValue('email_sending_rate_limit', { ...rateLimit, count: next })
+ }}
+ onBlur={() =>
+ displayCount === undefined
+ ? setDisplayCount(rateLimit.count)
+ : setWorkflowValue('email_sending_rate_limit', {
+ ...rateLimit,
+ count: displayCount,
+ })
+ }
+ data-attr="workflow-email-rate-limit-count"
+ />
+ <span>emails per</span>
+ <LemonSelect
+ size="small"
+ aria-label="Rate limit period"
+ value={rateLimit.period}
+ options={[
+ { value: 'minute' as const, label: 'minute' },
+ { value: 'hour' as const, label: 'hour' },
+ ]}
+ onChange={(period) =>
+ setWorkflowValue('email_sending_rate_limit', { ...rateLimit, period })
+ }
+ data-attr="workflow-email-rate-limit-period"
+ />
+ </div>
+ ) : null}
+ </div>
+ </>
+ )
+}
+
function ExitConditionSection(): JSX.Element {
const { setWorkflowValue } = useActions(workflowLogic)
const { workflow } = useValues(workflowLogic)
diff --git a/products/workflows/frontend/Workflows/hogflows/types.ts b/products/workflows/frontend/Workflows/hogflows/types.ts
index ee91cf5f5e56..0160ca7eeff6 100644
--- a/products/workflows/frontend/Workflows/hogflows/types.ts
+++ b/products/workflows/frontend/Workflows/hogflows/types.ts
@@ -54,6 +54,14 @@ export const HogFlowSchema = z.object({
'exit_on_trigger_not_matched_or_conversion',
'exit_only_at_end',
]),
+ // Optional email pacing: the email worker delays sends over the limit instead of dropping them
+ email_sending_rate_limit: z
+ .object({
+ count: z.number(),
+ period: z.enum(['minute', 'hour']),
+ })
+ .optional()
+ .nullable(),
actions: z.array(HogFlowActionSchema),
abort_action: z.string().optional(),
edges: z.array(HogFlowEdgeSchema),
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index c751713713b1..cc1cadc85f52 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -170,6 +170,7 @@ const WORKFLOW_CONTENT_FIELDS = [
'trigger_masking',
'conversion',
'exit_condition',
+ 'email_sending_rate_limit',
'abort_action',
'variables',
] as const
@@ -991,6 +992,13 @@ export interface workflowLogicActions {
to: string
type: 'branch' | 'continue'
}[]
+ email_sending_rate_limit?:
+ | {
+ count: number
+ period: 'hour' | 'minute'
+ }
+ | null
+ | undefined
exit_condition:
| 'exit_on_conversion'
| 'exit_on_trigger_not_matched'
@@ -1831,6 +1839,13 @@ export interface workflowLogicActions {
to: string
type: 'branch' | 'continue'
}[]
+ email_sending_rate_limit?:
+ | {
+ count: number
+ period: 'hour' | 'minute'
+ }
+ | null
+ | undefined
exit_condition:
| 'exit_on_conversion'
| 'exit_on_trigger_not_matched'
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 742250f2052a..b3ad15e5465a 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -308,6 +308,7 @@ export interface HogFlowMinimalApi {
readonly trigger_masking: unknown
readonly conversion: unknown
readonly exit_condition: ExitConditionEnumApi
+ readonly email_sending_rate_limit: unknown
readonly edges: unknown
readonly actions: unknown
/** @nullable */
@@ -362,6 +363,31 @@ export interface HogFlowConversionApi {
bytecode?: unknown
}
+/**
+ * * `minute` - minute
+ * * `hour` - hour
+ */
+export type PeriodEnumApi = (typeof PeriodEnumApi)[keyof typeof PeriodEnumApi]
+
+export const PeriodEnumApi = {
+ Minute: 'minute',
+ Hour: 'hour',
+} as const
+
+export interface HogFlowEmailSendingRateLimitApi {
+ /**
+ * Maximum number of emails this workflow sends per period.
+ * @minimum 1
+ * @maximum 1000000
+ */
+ count: number
+ /** Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.
+ *
+ * * `minute` - minute
+ * * `hour` - hour */
+ period: PeriodEnumApi
+}
+
/**
* * `continue` - continue
* * `branch` - branch
@@ -561,6 +587,8 @@ export interface HogFlowApi {
* * `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion
* * `exit_only_at_end` - Only At End */
exit_condition?: ExitConditionEnumApi
+ /** Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing. */
+ email_sending_rate_limit?: HogFlowEmailSendingRateLimitApi | null
/** Graph edges: [{from, to, type: 'continue'|'branch', index?}]. 'continue' = fall-through (sequential, or no-match path of conditional_branch). 'branch' requires 'index': matches config.conditions[index] on conditional_branch / wait_until_condition. Every non-exit action needs a reachable next action ('No next action found' otherwise). */
edges?: HogFlowEdgeApi[]
/** Ordered action nodes. Exactly one type='trigger' required. Typically one type='exit' too. */
@@ -637,6 +665,8 @@ export interface PatchedHogFlowApi {
* * `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion
* * `exit_only_at_end` - Only At End */
exit_condition?: ExitConditionEnumApi
+ /** Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing. */
+ email_sending_rate_limit?: HogFlowEmailSendingRateLimitApi | null
/** Graph edges: [{from, to, type: 'continue'|'branch', index?}]. 'continue' = fall-through (sequential, or no-match path of conditional_branch). 'branch' requires 'index': matches config.conditions[index] on conditional_branch / wait_until_condition. Every non-exit action needs a reachable next action ('No next action found' otherwise). */
edges?: HogFlowEdgeApi[]
/** Ordered action nodes. Exactly one type='trigger' required. Typically one type='exit' too. */
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 4dfc6fa17d3b..1faec0fc67ba 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -394,6 +394,8 @@ export const hogFlowsCreateBodyTriggerMaskingOneTtlMin = 60
export const hogFlowsCreateBodyTriggerMaskingOneTtlMax = 94608000
export const hogFlowsCreateBodyConversionOneEventsItemFiltersOneSourceDefault = `events`
+export const hogFlowsCreateBodyEmailSendingRateLimitOneCountMax = 1000000
+
export const hogFlowsCreateBodyActionsItemIdMax = 200
export const hogFlowsCreateBodyActionsItemNameMax = 400
@@ -516,6 +518,27 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod
.describe(
"exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"
),
+ email_sending_rate_limit: zod
+ .union([
+ zod.object({
+ count: zod
+ .number()
+ .min(1)
+ .max(hogFlowsCreateBodyEmailSendingRateLimitOneCountMax)
+ .describe('Maximum number of emails this workflow sends per period.'),
+ period: zod
+ .enum(['minute', 'hour'])
+ .describe('\* `minute` - minute\n\* `hour` - hour')
+ .describe(
+ 'Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.\n\n\* `minute` - minute\n\* `hour` - hour'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."
+ ),
edges: zod
.array(
zod.object({
@@ -749,6 +772,8 @@ export const hogFlowsUpdateBodyTriggerMaskingOneTtlMin = 60
export const hogFlowsUpdateBodyTriggerMaskingOneTtlMax = 94608000
export const hogFlowsUpdateBodyConversionOneEventsItemFiltersOneSourceDefault = `events`
+export const hogFlowsUpdateBodyEmailSendingRateLimitOneCountMax = 1000000
+
export const hogFlowsUpdateBodyActionsItemIdMax = 200
export const hogFlowsUpdateBodyActionsItemNameMax = 400
@@ -871,6 +896,27 @@ export const HogFlowsUpdateBody = /* @__PURE__ */ zod
.describe(
"exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"
),
+ email_sending_rate_limit: zod
+ .union([
+ zod.object({
+ count: zod
+ .number()
+ .min(1)
+ .max(hogFlowsUpdateBodyEmailSendingRateLimitOneCountMax)
+ .describe('Maximum number of emails this workflow sends per period.'),
+ period: zod
+ .enum(['minute', 'hour'])
+ .describe('\* `minute` - minute\n\* `hour` - hour')
+ .describe(
+ 'Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.\n\n\* `minute` - minute\n\* `hour` - hour'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."
+ ),
edges: zod
.array(
zod.object({
@@ -1104,6 +1150,8 @@ export const hogFlowsPartialUpdateBodyTriggerMaskingOneTtlMin = 60
export const hogFlowsPartialUpdateBodyTriggerMaskingOneTtlMax = 94608000
export const hogFlowsPartialUpdateBodyConversionOneEventsItemFiltersOneSourceDefault = `events`
+export const hogFlowsPartialUpdateBodyEmailSendingRateLimitOneCountMax = 1000000
+
export const hogFlowsPartialUpdateBodyActionsItemIdMax = 200
export const hogFlowsPartialUpdateBodyActionsItemNameMax = 400
@@ -1231,6 +1279,27 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
"exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"
),
+ email_sending_rate_limit: zod
+ .union([
+ zod.object({
+ count: zod
+ .number()
+ .min(1)
+ .max(hogFlowsPartialUpdateBodyEmailSendingRateLimitOneCountMax)
+ .describe('Maximum number of emails this workflow sends per period.'),
+ period: zod
+ .enum(['minute', 'hour'])
+ .describe('\* `minute` - minute\n\* `hour` - hour')
+ .describe(
+ 'Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.\n\n\* `minute` - minute\n\* `hour` - hour'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."
+ ),
edges: zod
.array(
zod.object({
@@ -1652,6 +1721,8 @@ export const hogFlowsInvocationsCreateBodyConfigurationOneTriggerMaskingOneTtlMi
export const hogFlowsInvocationsCreateBodyConfigurationOneTriggerMaskingOneTtlMax = 94608000
export const hogFlowsInvocationsCreateBodyConfigurationOneConversionOneEventsItemFiltersOneSourceDefault = `events`
+export const hogFlowsInvocationsCreateBodyConfigurationOneEmailSendingRateLimitOneCountMax = 1000000
+
export const hogFlowsInvocationsCreateBodyConfigurationOneActionsItemIdMax = 200
export const hogFlowsInvocationsCreateBodyConfigurationOneActionsItemNameMax = 400
@@ -1835,6 +1906,27 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({
.describe(
"exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"
),
+ email_sending_rate_limit: zod
+ .union([
+ zod.object({
+ count: zod
+ .number()
+ .min(1)
+ .max(hogFlowsInvocationsCreateBodyConfigurationOneEmailSendingRateLimitOneCountMax)
+ .describe('Maximum number of emails this workflow sends per period.'),
+ period: zod
+ .enum(['minute', 'hour'])
+ .describe('\* `minute` - minute\n\* `hour` - hour')
+ .describe(
+ 'Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.\n\n\* `minute` - minute\n\* `hour` - hour'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."
+ ),
edges: zod
.array(
zod.object({
@@ -2347,6 +2439,8 @@ export const hogFlowsBulkDeleteCreateBodyTriggerMaskingOneTtlMin = 60
export const hogFlowsBulkDeleteCreateBodyTriggerMaskingOneTtlMax = 94608000
export const hogFlowsBulkDeleteCreateBodyConversionOneEventsItemFiltersOneSourceDefault = `events`
+export const hogFlowsBulkDeleteCreateBodyEmailSendingRateLimitOneCountMax = 1000000
+
export const hogFlowsBulkDeleteCreateBodyActionsItemIdMax = 200
export const hogFlowsBulkDeleteCreateBodyActionsItemNameMax = 400
@@ -2474,6 +2568,27 @@ export const HogFlowsBulkDeleteCreateBody = /* @__PURE__ */ zod
.describe(
"exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"
),
+ email_sending_rate_limit: zod
+ .union([
+ zod.object({
+ count: zod
+ .number()
+ .min(1)
+ .max(hogFlowsBulkDeleteCreateBodyEmailSendingRateLimitOneCountMax)
+ .describe('Maximum number of emails this workflow sends per period.'),
+ period: zod
+ .enum(['minute', 'hour'])
+ .describe('\* `minute` - minute\n\* `hour` - hour')
+ .describe(
+ 'Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.\n\n\* `minute` - minute\n\* `hour` - hour'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."
+ ),
edges: zod
.array(
zod.object({
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 26a39524ccc1..0ea0e6e6da33 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -40481,6 +40481,32 @@ export namespace Schemas {
bytecode?: unknown;
}
+ /**
+ * * `minute` - minute
+ * * `hour` - hour
+ */
+ export type PeriodEnum = typeof PeriodEnum[keyof typeof PeriodEnum];
+
+
+ export const PeriodEnum = {
+ Minute: 'minute',
+ Hour: 'hour',
+ } as const;
+
+ export interface HogFlowEmailSendingRateLimit {
+ /**
+ * Maximum number of emails this workflow sends per period.
+ * @minimum 1
+ * @maximum 1000000
+ */
+ count: number;
+ /** Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.
+ *
+ * * `minute` - minute
+ * * `hour` - hour */
+ period: PeriodEnum;
+ }
+
/**
* * `continue` - continue
* * `branch` - branch
@@ -40692,6 +40718,8 @@ export namespace Schemas {
* * `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion
* * `exit_only_at_end` - Only At End */
exit_condition?: ExitConditionEnum;
+ /** Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing. */
+ email_sending_rate_limit?: HogFlowEmailSendingRateLimit | null;
/** Graph edges: [{from, to, type: 'continue'|'branch', index?}]. 'continue' = fall-through (sequential, or no-match path of conditional_branch). 'branch' requires 'index': matches config.conditions[index] on conditional_branch / wait_until_condition. Every non-exit action needs a reachable next action ('No next action found' otherwise). */
edges?: HogFlowEdge[];
/** Ordered action nodes. Exactly one type='trigger' required. Typically one type='exit' too. */
@@ -40864,6 +40892,7 @@ export namespace Schemas {
readonly trigger_masking: unknown;
readonly conversion: unknown;
readonly exit_condition: ExitConditionEnum;
+ readonly email_sending_rate_limit: unknown;
readonly edges: unknown;
readonly actions: unknown;
/** @nullable */
@@ -60392,6 +60421,8 @@ export namespace Schemas {
* * `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion
* * `exit_only_at_end` - Only At End */
exit_condition?: ExitConditionEnum;
+ /** Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing. */
+ email_sending_rate_limit?: HogFlowEmailSendingRateLimit | null;
/** Graph edges: [{from, to, type: 'continue'|'branch', index?}]. 'continue' = fall-through (sequential, or no-match path of conditional_branch). 'branch' requires 'index': matches config.conditions[index] on conditional_branch / wait_until_condition. Every non-exit action needs a reachable next action ('No next action found' otherwise). */
edges?: HogFlowEdge[];
/** Ordered action nodes. Exactly one type='trigger' required. Typically one type='exit' too. */
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index 0e08ab659fa1..6600f79774cf 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -45,6 +45,8 @@ export const hogFlowsCreateBodyTriggerMaskingOneTtlMin = 60
export const hogFlowsCreateBodyTriggerMaskingOneTtlMax = 94608000
export const hogFlowsCreateBodyConversionOneEventsItemFiltersOneSourceDefault = `events`
+export const hogFlowsCreateBodyEmailSendingRateLimitOneCountMax = 1000000
+
export const hogFlowsCreateBodyActionsItemIdMax = 200
export const hogFlowsCreateBodyActionsItemNameMax = 400
@@ -167,6 +169,27 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod
.describe(
"exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"
),
+ email_sending_rate_limit: zod
+ .union([
+ zod.object({
+ count: zod
+ .number()
+ .min(1)
+ .max(hogFlowsCreateBodyEmailSendingRateLimitOneCountMax)
+ .describe('Maximum number of emails this workflow sends per period.'),
+ period: zod
+ .enum(['minute', 'hour'])
+ .describe('\* `minute` - minute\n\* `hour` - hour')
+ .describe(
+ 'Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.\n\n\* `minute` - minute\n\* `hour` - hour'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."
+ ),
edges: zod
.array(
zod.object({
@@ -417,6 +440,7 @@ export const hogFlowsPartialUpdateBodyTriggerMaskingOneTtlMin = 60
export const hogFlowsPartialUpdateBodyTriggerMaskingOneTtlMax = 94608000
export const hogFlowsPartialUpdateBodyConversionOneEventsItemFiltersOneSourceDefault = `events`
+export const hogFlowsPartialUpdateBodyEmailSendingRateLimitOneCountMax = 1000000
export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod
.object({
@@ -526,6 +550,27 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
"exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End"
),
+ email_sending_rate_limit: zod
+ .union([
+ zod.object({
+ count: zod
+ .number()
+ .min(1)
+ .max(hogFlowsPartialUpdateBodyEmailSendingRateLimitOneCountMax)
+ .describe('Maximum number of emails this workflow sends per period.'),
+ period: zod
+ .enum(['minute', 'hour'])
+ .describe('\* `minute` - minute\n\* `hour` - hour')
+ .describe(
+ 'Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.\n\n\* `minute` - minute\n\* `hour` - hour'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."
+ ),
variables: zod
.array(
zod
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index 53a50cbca55c..510de15a24f1 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -62,6 +62,9 @@ const workflowsCreate = (): ToolBase<typeof WorkflowsCreateSchema, WithPostHogUr
if (params.exit_condition !== undefined) {
body['exit_condition'] = params.exit_condition
}
+ if (params.email_sending_rate_limit !== undefined) {
+ body['email_sending_rate_limit'] = params.email_sending_rate_limit
+ }
if (params.edges !== undefined) {
body['edges'] = params.edges
}
@@ -457,6 +460,9 @@ const workflowsUpdate = (): ToolBase<typeof WorkflowsUpdateSchema, WithPostHogUr
if (params.exit_condition !== undefined) {
body['exit_condition'] = params.exit_condition
}
+ if (params.email_sending_rate_limit !== undefined) {
+ body['email_sending_rate_limit'] = params.email_sending_rate_limit
+ }
if (params.variables !== undefined) {
body['variables'] = params.variables
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json
index bc1f11bfc5f0..9e71351bbc46 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json
@@ -476,6 +476,31 @@
},
"type": "array"
},
+ "email_sending_rate_limit": {
+ "anyOf": [
+ {
+ "properties": {
+ "count": {
+ "description": "Maximum number of emails this workflow sends per period.",
+ "maximum": 1000000,
+ "minimum": 1,
+ "type": "number"
+ },
+ "period": {
+ "description": "Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.\n\n* `minute` - minute\n* `hour` - hour",
+ "enum": ["minute", "hour"],
+ "type": "string"
+ }
+ },
+ "required": ["count", "period"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."
+ },
"exit_condition": {
"description": "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n* `exit_on_conversion` - Conversion\n* `exit_on_trigger_not_matched` - Trigger Not Matched\n* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n* `exit_only_at_end` - Only At End",
"enum": [
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.json
index b74918a6a5c2..e5fd8dca28bb 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.json
@@ -118,6 +118,31 @@
"description": "Optional description.",
"type": "string"
},
+ "email_sending_rate_limit": {
+ "anyOf": [
+ {
+ "properties": {
+ "count": {
+ "description": "Maximum number of emails this workflow sends per period.",
+ "maximum": 1000000,
+ "minimum": 1,
+ "type": "number"
+ },
+ "period": {
+ "description": "Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.\n\n* `minute` - minute\n* `hour` - hour",
+ "enum": ["minute", "hour"],
+ "type": "string"
+ }
+ },
+ "required": ["count", "period"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."
+ },
"exit_condition": {
"description": "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n* `exit_on_conversion` - Conversion\n* `exit_on_trigger_not_matched` - Trigger Not Matched\n* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n* `exit_only_at_end` - Only At End",
"enum": [