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): retry push sends on transient provider errors (#70831)

Daniel Marchuk80c5d84e8c8c
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index 222d586083cb..ac6ce5ccf843 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -414,6 +414,9 @@ export function createCdpCoreServices(
{
trackedFetch: cdpTrackedFetch,
maxFetchTimeoutMs: MAX_FETCH_TIMEOUT_MS,
+ maxRetries: config.CDP_FETCH_RETRIES,
+ backoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
+ backoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
},
redis
)
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index b1152e7d9821..e9064cf8616d 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -528,6 +528,9 @@ export function createHogTransformerService(
{
trackedFetch: cdpTrackedFetch,
maxFetchTimeoutMs: MAX_FETCH_TIMEOUT_MS,
+ maxRetries: config.CDP_FETCH_RETRIES,
+ backoffBaseMs: config.CDP_FETCH_BACKOFF_BASE_MS,
+ backoffMaxMs: config.CDP_FETCH_BACKOFF_MAX_MS,
},
redis
)
diff --git a/nodejs/src/cdp/services/messaging/push-notification-errors.ts b/nodejs/src/cdp/services/messaging/push-notification-errors.ts
index 43d90acab337..175bc09dc99f 100644
--- a/nodejs/src/cdp/services/messaging/push-notification-errors.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification-errors.ts
@@ -21,22 +21,26 @@ export type NormalizedPushError = {
code?: string
// Whether this means the device token should be removed from the person (a permanent, dead token).
unregistered: boolean
+ // Whether the send is worth retrying: transient provider/network problems are, config/content ones aren't.
+ retriable: boolean
// Log severity: config problems the user must fix are errors; transient/expected ones are warnings.
level: LogEntryLevel
// A plain-language explanation for the workflow logs.
message: string
}
-// Thrown by a channel send on a terminal failure. Carries the normalized reason, severity, and raw
-// provider code so the caller can log once at the right level and label the failure metric, without
-// re-deriving any of it or double-logging.
+// Thrown by a channel send when it fails. Carries the normalized reason, severity, retriability, and the
+// provider's Retry-After (when given) so the caller can log once at the right level, label metrics, and
+// decide whether to reschedule the whole invocation, without re-deriving any of it or double-logging.
export class PushSendError extends Error {
constructor(
message: string,
public readonly platform: PushPlatform,
public readonly reason: PushFailureReason,
public readonly level: LogEntryLevel,
- public readonly code?: string
+ public readonly retriable: boolean,
+ public readonly code?: string,
+ public readonly retryAfterMs?: number
) {
super(message)
this.name = 'PushSendError'
@@ -57,6 +61,20 @@ const REASON_LEVEL: Record<PushFailureReason, LogEntryLevel> = {
unknown: 'error',
}
+// Only transient provider/network problems are worth retrying. Config and content problems (bad
+// credentials, invalid token, rejected payload) will fail the same way on every attempt, and an
+// unregistered token is handled by pruning rather than retrying.
+const REASON_RETRIABLE: Record<PushFailureReason, boolean> = {
+ unregistered: false,
+ invalid_token: false,
+ auth_error: false,
+ rate_limited: true,
+ invalid_payload: false,
+ provider_error: true,
+ network_error: true,
+ unknown: false,
+}
+
// The user-facing sentence for each reason. Written to guide the next action, not just state the fault.
function reasonMessage(platform: PushPlatform, reason: PushFailureReason): string {
const provider = PLATFORM_LABEL[platform]
@@ -85,6 +103,7 @@ function build(platform: PushPlatform, reason: PushFailureReason, code: string |
reason,
code,
unregistered: reason === 'unregistered',
+ retriable: REASON_RETRIABLE[reason],
level: REASON_LEVEL[reason],
message: reasonMessage(platform, reason),
}
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
index 6dd85565cb02..0fc85a36a877 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
@@ -85,6 +85,9 @@ describe('PushNotificationService', () => {
fetchUtils = {
trackedFetch: mockTrackedFetch,
maxFetchTimeoutMs: 10000,
+ maxRetries: 3,
+ backoffBaseMs: 1000,
+ backoffMaxMs: 30000,
}
redisStore = new Map<string, string>()
@@ -194,14 +197,86 @@ describe('PushNotificationService', () => {
expect(mockTrackedFetch).not.toHaveBeenCalled()
})
- it('sets error when push fails', async () => {
+ it('fails terminally (no retry) on a non-retriable 4xx', async () => {
const invocation = createSendPushNotificationInvocation({
'$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
})
+ // A 400 is a client error that won't change on retry (bad payload), unlike a 429/5xx.
mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 400,
+ headers: {},
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.error).toBeTruthy()
+ expect(result.finished).toBe(true)
+ expect(result.invocation.queueScheduledAt).toBeUndefined()
+ expect(result.metrics).toContainEqual(expect.objectContaining({ metric_name: 'push_failed' }))
+ })
+
+ it('reschedules a transient failure and re-runs the send on the retry (round trip)', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
+ })
+ // First attempt: FCM 500 is transient, so the invocation is rescheduled rather than dropped.
+ mockTrackedFetch.mockResolvedValueOnce({
fetchError: null,
fetchResponse: {
status: 500,
+ headers: {},
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ const first = await service.executeSendPushNotification(invocation)
+
+ expect(first.finished).toBe(false)
+ expect(first.invocation.queueScheduledAt).toBeDefined()
+ expect(first.error).toBeUndefined()
+ // The P1 guard: queueParameters must be restored, or the retry dequeue resumes the hog VM
+ // instead of re-entering this service, pops an empty stack, and drops the notification.
+ expect(first.invocation.queueParameters?.type).toBe('sendPushNotification')
+ expect(first.invocation.queueMetadata).toEqual(expect.objectContaining({ tries: 1 }))
+ // A rescheduled attempt reports no terminal outcome yet.
+ expect(first.metrics).not.toContainEqual(expect.objectContaining({ metric_name: 'push_failed' }))
+
+ // Feed the rescheduled invocation back through the executor: the send must actually re-run.
+ mockTrackedFetch.mockResolvedValueOnce({
+ fetchError: null,
+ fetchResponse: {
+ status: 200,
+ headers: {},
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ const second = await service.executeSendPushNotification(first.invocation)
+
+ expect(second.finished).toBe(true)
+ expect(second.metrics).toContainEqual(expect.objectContaining({ metric_name: 'push_sent', count: 1 }))
+ })
+
+ it('stops rescheduling once the retry budget is exhausted', async () => {
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
+ })
+ invocation.queueMetadata = { tries: 3 } // == maxRetries
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 429,
+ headers: {},
text: () => Promise.resolve('{}'),
dump: () => Promise.resolve(),
},
@@ -210,7 +285,10 @@ describe('PushNotificationService', () => {
const result = await service.executeSendPushNotification(invocation)
+ expect(result.finished).toBe(true)
expect(result.error).toBeTruthy()
+ expect(result.invocation.queueScheduledAt).toBeUndefined()
+ expect(result.metrics).toContainEqual(expect.objectContaining({ metric_name: 'push_failed' }))
})
it('prunes an unregistered FCM token and skips the channel without erroring', async () => {
@@ -631,30 +709,74 @@ describe('PushNotificationService', () => {
expect(result.error).toBeUndefined()
})
- it('retries when one channel is skipped and another genuinely fails', async () => {
+ it('reschedules without re-counting the skipped channel on the retry attempt', async () => {
;(integrationManager.get as jest.Mock).mockImplementation((id: number) =>
Promise.resolve(id === 1 ? firebaseIntegration : apnsIntegration)
)
- // Only the APNS token is registered: FCM is skipped (not a delivery), APNS is attempted.
+ // FCM has no token (skipped), APNS fails transiently. Nothing delivered, so this reschedules,
+ // and the skip must not be counted on the rescheduled attempt — it's emitted only at the
+ // terminal outcome, so per-notification counts don't inflate on every retry.
const invocation = createSendPushNotificationInvocation({
'$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-token'),
})
invocation.queueParameters = { ...invocation.queueParameters, integrationIds: [1, 2] } as any
- // APNS fails - nothing was delivered, so this must retry rather than silently drop the push.
mockTrackedFetch.mockResolvedValue({
fetchError: null,
- fetchResponse: { status: 500, text: () => Promise.resolve('{}'), dump: () => Promise.resolve() },
+ fetchResponse: {
+ status: 500,
+ headers: {},
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
fetchDuration: 10,
})
const result = await service.executeSendPushNotification(invocation)
- expect(result.error).toBeTruthy()
- // The error is also surfaced to the hog template, so its failure message is not blank.
- expect(result.invocation.state.vmState!.stack.at(-1)).toEqual({
- success: false,
- error: expect.any(String),
+ expect(result.finished).toBe(false)
+ expect(result.invocation.queueParameters?.type).toBe('sendPushNotification')
+ expect(result.metrics).not.toContainEqual(expect.objectContaining({ metric_name: 'push_skipped' }))
+ expect(result.metrics).not.toContainEqual(expect.objectContaining({ metric_name: 'push_failed' }))
+ })
+
+ it('reschedules using the longest Retry-After across failed channels', async () => {
+ ;(integrationManager.get as jest.Mock).mockImplementation((id: number) =>
+ Promise.resolve(id === 1 ? firebaseIntegration : apnsIntegration)
+ )
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('fcm-token'),
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-token'),
})
+ invocation.queueParameters = { ...invocation.queueParameters, integrationIds: [1, 2] } as any
+ // FCM 500 (short backoff) then APNs 429 with Retry-After: 30. Retrying re-attempts both, so the
+ // delay must clear the longer 30s window, not FCM's sub-2s backoff.
+ mockTrackedFetch.mockResolvedValueOnce({
+ fetchError: null,
+ fetchResponse: {
+ status: 500,
+ headers: {},
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+ mockTrackedFetch.mockResolvedValueOnce({
+ fetchError: null,
+ fetchResponse: {
+ status: 429,
+ headers: { 'retry-after': '30' },
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ expect(result.finished).toBe(false)
+ const delayMs = result.invocation.queueScheduledAt!.toMillis() - Date.now()
+ expect(delayMs).toBeGreaterThan(20_000)
+ expect(delayMs).toBeLessThanOrEqual(30_000)
})
})
})
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.ts
index dea4ba36ca24..2158610d4b48 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts
@@ -1,4 +1,5 @@
import { createHash, createSign } from 'crypto'
+import { DateTime } from 'luxon'
import { Counter, Histogram } from 'prom-client'
import {
@@ -55,6 +56,12 @@ const pushNotificationSendDurationMs = new Histogram({
buckets: [10, 25, 50, 100, 200, 500, 1000, 2000, 5000, 10000],
})
+const pushNotificationRescheduledCounter = new Counter({
+ name: 'push_notification_rescheduled_total',
+ help: 'Push sends rescheduled after a transient provider failure (throttle / 5xx / network) instead of being dropped. A sustained rate for one platform means that provider is rate-limiting the sending project.',
+ labelNames: ['platform'],
+})
+
// Apple rate-limits new APNs provider tokens (returns 429 TooManyProviderTokenUpdates if refreshed more
// than once every ~20 min per key) and accepts a token for up to 1 hour. Cache the signed JWT in Redis
// keyed by the auth key id so the whole fleet reuses one token per key rather than minting one per send.
@@ -66,15 +73,40 @@ const APNS_JWT_TTL_SECONDS = 45 * 60
// push targets a handful of provider integrations, not thousands.
const MAX_PUSH_CHANNELS = 10
+// Cap a provider-supplied Retry-After. FCM returns one on QUOTA_EXCEEDED and honoring it is the point,
+// but a hostile or misconfigured value must not park an invocation for hours.
+const MAX_RETRY_AFTER_MS = 5 * 60 * 1000
+
function stringifyBody(body: unknown): string {
return typeof body === 'string' ? body : JSON.stringify(body)
}
-function pushSendError(platform: PushPlatform, err: NormalizedPushError): PushSendError {
+// Retry-After is delta-seconds or an HTTP-date. Return a bounded millisecond delay, or undefined if the
+// header is absent or unparseable so the caller falls back to exponential backoff.
+function parseRetryAfterMs(response: FetchResponse | null): number | undefined {
+ const header = response?.headers?.['retry-after']
+ if (!header) {
+ return undefined
+ }
+ const seconds = Number(header)
+ const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header) - Date.now()
+ if (!Number.isFinite(ms) || ms <= 0) {
+ return undefined
+ }
+ return Math.min(ms, MAX_RETRY_AFTER_MS)
+}
+
+// Exponential-ish backoff with jitter for a retry when the provider didn't give a Retry-After.
+function backoffAt(baseMs: number, maxMs: number, tries: number): DateTime {
+ const delay = Math.min(baseMs * tries + Math.floor(Math.random() * baseMs), maxMs)
+ return DateTime.utc().plus({ milliseconds: delay })
+}
+
+function pushSendError(platform: PushPlatform, err: NormalizedPushError, retryAfterMs?: number): PushSendError {
// Append the raw provider code so the failure surfaced to the hog template stays debuggable, while
// the human-readable sentence leads.
const message = err.code ? `${err.message} [${err.code}]` : err.message
- return new PushSendError(message, platform, err.reason, err.level, err.code)
+ return new PushSendError(message, platform, err.reason, err.level, err.retriable, err.code, retryAfterMs)
}
export type PushNotificationFetchUtils = {
@@ -84,6 +116,11 @@ export type PushNotificationFetchUtils = {
fetchDuration: number
}>
maxFetchTimeoutMs: number
+ // Retry budget + backoff for transient provider failures, wired from CDP_FETCH_* so push shares the
+ // same policy as the generic fetch destinations.
+ maxRetries: number
+ backoffBaseMs: number
+ backoffMaxMs: number
}
export class PushNotificationService {
@@ -106,14 +143,24 @@ export class PushNotificationService {
const result = createInvocationResult<CyclotronJobInvocationHogFunction>(invocation, {}, { finished: true })
const addLog = createAddLogFunction(result.logs)
- const pushMetric = (metricName: 'push_sent' | 'push_skipped' | 'push_failed'): void => {
+ // How many times this send has already been rescheduled after a transient failure, carried on the
+ // invocation's queue metadata across reschedules.
+ const metadata = (invocation.queueMetadata as { tries?: number }) || {}
+ const tries = metadata.tries ?? 0
+
+ // Business metrics are emitted once, at the terminal outcome below, rather than per channel — a
+ // rescheduled attempt must not re-count the same notification's skips or failures on every retry.
+ const pushMetric = (metricName: 'push_sent' | 'push_skipped' | 'push_failed', count: number): void => {
+ if (count <= 0) {
+ return
+ }
result.metrics.push({
team_id: invocation.teamId,
app_source_id: invocation.parentRunId ?? invocation.functionId,
instance_id: invocation.state.actionId || invocation.id,
metric_kind: 'push',
metric_name: metricName,
- count: 1,
+ count,
})
}
@@ -132,8 +179,10 @@ export class PushNotificationService {
)
}
- let errorCount = 0
let successCount = 0
+ let skippedCount = 0
+ let otherErrorCount = 0
+ const errors: PushSendError[] = []
let firstError: string | undefined
for (const integrationId of integrationIds) {
try {
@@ -153,31 +202,75 @@ export class PushNotificationService {
if (sent) {
successCount++
- pushMetric('push_sent')
} else {
// A channel with no registered device token for this recipient is skipped, not failed.
- pushMetric('push_skipped')
+ skippedCount++
}
} catch (error) {
- errorCount++
firstError = firstError ?? error.message
if (error instanceof PushSendError) {
- // The channel already normalized the provider error; log it once here at the reason's
- // severity and label the failure metric by platform + reason.
+ // Normalized provider failure: log once at the reason's severity. The failure metric is
+ // emitted at the terminal outcome below, so a rescheduled retry doesn't over-count it.
+ errors.push(error)
addLog(error.level, error.message)
- pushNotificationFailedCounter.labels({ platform: error.platform, reason: error.reason }).inc()
} else {
+ otherErrorCount++
addLog('error', error.message)
- pushNotificationFailedCounter.labels({ platform: 'unknown', reason: 'unknown' }).inc()
}
- pushMetric('push_failed')
}
}
- // Retry (by surfacing an error) only when a channel was attempted and failed and nothing was
- // delivered. A skip (no device token) is not a delivery, so retrying is safe; but once any
- // channel has delivered we must not retry, or it would re-deliver to that channel.
+ const errorCount = errors.length + otherErrorCount
const success = successCount > 0 || errorCount === 0
+ const retriableErrors = errors.filter((e) => e.retriable)
+
+ // Nothing delivered and a channel failed transiently: reschedule the whole invocation instead of
+ // dropping the notification. Only safe when nothing was delivered — once a channel has sent,
+ // retrying would re-deliver to it. A terminally-failed channel (e.g. a 400) sitting alongside a
+ // transient one is re-attempted on each retry; that's acceptable, it just re-fails, bounded by the
+ // budget. `tries` starts at 0, so this allows CDP_FETCH_RETRIES reschedules after the first attempt
+ // (the notification is tried maxRetries + 1 times in total).
+ if (!success && retriableErrors.length > 0 && tries < this.fetchUtils.maxRetries) {
+ const nextTries = tries + 1
+ // Restore queueParameters — createInvocationResult cleared them. Without this the retry dequeue
+ // routes on an undefined queue type and resumes the hog VM instead of re-running this send,
+ // which pops an empty stack and throws a bytecode error, dropping the notification.
+ result.invocation.queueParameters = invocation.queueParameters
+ result.invocation.queueMetadata = { ...metadata, tries: nextTries }
+ result.invocation.queuePriority = nextTries
+ // Retrying re-attempts every failed channel, so wait out the LONGEST Retry-After any channel
+ // asked for; fall back to exponential backoff when none provided one.
+ const retryAfterValues = retriableErrors
+ .map((e) => e.retryAfterMs)
+ .filter((ms): ms is number => ms !== undefined)
+ result.invocation.queueScheduledAt =
+ retryAfterValues.length > 0
+ ? DateTime.utc().plus({ milliseconds: Math.max(...retryAfterValues) })
+ : backoffAt(this.fetchUtils.backoffBaseMs, this.fetchUtils.backoffMaxMs, nextTries)
+ result.finished = false
+ // Count each distinct throttled platform so the metric shows which provider is rate-limiting.
+ for (const platform of new Set(retriableErrors.map((e) => e.platform))) {
+ pushNotificationRescheduledCounter.labels({ platform }).inc()
+ }
+ addLog(
+ 'warn',
+ `Push notification throttled or temporarily unavailable; retrying (attempt ${nextTries}/${this.fetchUtils.maxRetries}).`
+ )
+ // No business metric or VM-state push here — the eventual terminal attempt reports the outcome.
+ return result
+ }
+
+ // Terminal outcome: emit the per-notification business metrics once, and label the ops failure
+ // metric by platform + reason for every channel that failed for good.
+ pushMetric('push_sent', successCount)
+ pushMetric('push_skipped', skippedCount)
+ pushMetric('push_failed', errorCount)
+ for (const error of errors) {
+ pushNotificationFailedCounter.labels({ platform: error.platform, reason: error.reason }).inc()
+ }
+ if (otherErrorCount > 0) {
+ pushNotificationFailedCounter.labels({ platform: 'unknown', reason: 'unknown' }).inc(otherErrorCount)
+ }
if (!success) {
result.error = firstError
}
@@ -268,7 +361,7 @@ export class PushNotificationService {
addLog('warn', `FCM: ${err.message}`)
return false
}
- throw pushSendError('fcm', err)
+ throw pushSendError('fcm', err, parseRetryAfterMs(fetchResponse))
}
pushNotificationSentCounter.labels({ platform: 'fcm' }).inc()
@@ -377,7 +470,7 @@ export class PushNotificationService {
addLog('warn', `APNs: ${err.message}`)
return false
}
- throw pushSendError('apns', err)
+ throw pushSendError('apns', err, parseRetryAfterMs(fetchResponse))
}
pushNotificationSentCounter.labels({ platform: 'apns' }).inc()