: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cdp): keep a young apns token instead of refreshing it after a rejection (#117338)
Daniel Marchukd3a7d82ce7bf
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.tsindex 8b1332ccda99..4cf129ba38e9 100644--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts@@ -667,7 +667,9 @@ describe('PushNotificationService', () => {// The JWT is written to Valkey once and read back on the second send. Minting a new token per// send is what makes Apple return 429 TooManyProviderTokenUpdates.- expect(mockValkeySet).toHaveBeenCalledTimes(1)+ expect(+ mockValkeySet.mock.calls.filter(([key]: [string]) => key.startsWith('@posthog/apns-provider-jwt/'))+ ).toHaveLength(1)// Apple accepts a provider token for up to an hour, so the TTL has to stay under that.expect(mockValkeySet).toHaveBeenCalledWith(expect.stringContaining('@posthog/apns-provider-jwt/'),@@ -1017,9 +1019,32 @@ describe('PushNotificationService', () => {const sentTokens = (): string[] =>mockTrackedFetch.mock.calls.map((call: any) => call[0].fetchParams.headers.Authorization)const jwtCacheKey = `@posthog/apns-provider-jwt/${createHash('sha256').update(`TEAM456:KEY123:${testEcKey}`).digest('hex')}`+ const forgetSharedAcceptance = (): void => {+ for (const key of [...valkeyStore.keys()]) {+ if (key.startsWith('@posthog/apns-key-accepted/')) {+ valkeyStore.delete(key)+ }+ }+ }+ const tokenIssuedMinutesAgo = (minutes: number): string =>+ `e30.${Buffer.from(JSON.stringify({ iat: Math.floor(Date.now() / 1000) - minutes * 60 })).toString('base64url')}.sig`beforeEach(() => {mockTrackedFetch.mockReset()+ valkeyStore.set(jwtCacheKey, tokenIssuedMinutesAgo(30))+ })++ it('keeps a rejected token that is younger than the refresh window', async () => {+ const youngToken = tokenIssuedMinutesAgo(1)+ valkeyStore.set(jwtCacheKey, youngToken)+ mockTrackedFetch.mockResolvedValue(apnsResponse(403, 'InvalidProviderToken'))++ const result = await send()++ expect(result.error).toContain('InvalidProviderToken')+ expect(sentTokens()).toHaveLength(1)+ expect(valkeyStore.get(jwtCacheKey)).toBe(youngToken)+ expect([...valkeyStore.keys()].some((key) => key.includes('jwt-refresh'))).toBe(false)})it.each(['InvalidProviderToken', 'ExpiredProviderToken'])(@@ -1066,7 +1091,8 @@ describe('PushNotificationService', () => {mockTrackedFetch.mockResolvedValue(apnsResponse(403, 'InvalidProviderToken'))const rescheduled = await send()- // The retry can run on a pod that has not delivered with this key yet.+ // The retry can run on a pod that has not delivered with this key yet. Only the carried evidence counts.+ forgetSharedAcceptance()const otherPod = new PushNotificationService(integrationManager,encryptedFields,@@ -1096,6 +1122,43 @@ describe('PushNotificationService', () => {expect(failed.metrics).toContainEqual(expect.objectContaining({ metric_name: 'push_failed' }))})+ it('reschedules a young token rejection on a pod that has not delivered with a key another pod delivered with', async () => {+ mockTrackedFetch.mockResolvedValueOnce(apnsResponse(200))+ await send()+ valkeyStore.set(jwtCacheKey, tokenIssuedMinutesAgo(1))+ mockTrackedFetch.mockResolvedValue(apnsResponse(403, 'InvalidProviderToken'))++ const result = await new PushNotificationService(+ integrationManager,+ encryptedFields,+ fetchUtils,+ mockValkey+ ).executeSendPushNotification(+ createSendPushNotificationInvocation({+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),+ })+ )++ expect(result.finished).toBe(false)+ expect(result.metrics).not.toContainEqual(expect.objectContaining({ metric_name: 'push_failed' }))+ })++ it('does not read shared acceptance for a failure a working key cannot explain', async () => {+ mockTrackedFetch.mockResolvedValue(apnsResponse(429, 'TooManyRequests'))++ await service.executeSendPushNotification(+ createSendPushNotificationInvocation({+ [deviceSubscriptionKey('com.example.app', 'token-a')]: encryptedFields.encrypt('token-a'),+ [deviceSubscriptionKey('com.example.app', 'token-b')]: encryptedFields.encrypt('token-b'),+ })+ )++ expect(mockValkey.useClient).not.toHaveBeenCalledWith(+ expect.objectContaining({ name: 'apns-key-accepted-read' }),+ expect.anything()+ )+ })+it('carries the working key when another device asks for a longer Retry-After', async () => {mockTrackedFetch.mockResolvedValueOnce(apnsResponse(200))await send()@@ -1116,6 +1179,7 @@ describe('PushNotificationService', () => {expect(rescheduled.finished).toBe(false)// On a fresh pod the throttled device is gone, so only the carried evidence keeps the rejection retriable.+ forgetSharedAcceptance()mockTrackedFetch.mockImplementation(({ url }: { url: string }) =>Promise.resolve(url.endsWith('/token-a')diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.tsindex 6427bfe5906d..bc810e3461d3 100644--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts@@ -61,7 +61,7 @@ const pushNotificationSendDurationMs = new Histogram({const apnsProviderTokenRefreshCounter = new Counter({name: 'push_notification_apns_token_refresh_total',- help: 'APNs provider tokens replaced after Apple rejected one. outcome: minted = a new token was signed; adopted = another pod had already replaced it; skipped = a refresh for this key happened inside the refresh window.',+ help: 'APNs provider tokens replaced after Apple rejected one. outcome: minted = a new token was signed; adopted = another pod had already replaced it; skipped = a refresh for this key, or the rejected token itself, is inside the refresh window.',labelNames: ['outcome'],})@@ -80,6 +80,9 @@ const APNS_JWT_TTL_SECONDS = 45 * 60// Apple can reject a token it accepted minutes earlier. One new token per key per window keeps a key that// keeps getting rejected under Apple's refresh limit.const APNS_JWT_REFRESH_PREFIX = '@posthog/apns-provider-jwt-refresh/'+// A delivery on any pod proves the key works, so a pod that has not sent with it yet can still retry a rejection.+const APNS_KEY_ACCEPTED_PREFIX = '@posthog/apns-key-accepted/'+const APNS_KEY_ACCEPTED_SHARE_INTERVAL_MS = 60 * 1000const APNS_JWT_REFRESH_WINDOW_SECONDS = 20 * 60const APNS_REJECTED_TOKEN_CODES = new Set(['InvalidProviderToken', 'ExpiredProviderToken'])const APNS_JWT_REPLACEMENT_POLLS = 5@@ -263,7 +266,7 @@ export class PushNotificationService {private apnsJwtLocalCache = new Map<string, { jwt: string; expiresAtMs: number }>()private apnsJwtInFlight = new Map<string, Promise<string>>()// Last time APNs accepted a send signed with each key, so a token rejection for a key that works can be retried.- private apnsKeyAcceptedAtMs = new Map<string, number>()+ private apnsKeyAcceptedAtMs = new Map<string, { acceptedAtMs: number; sharedAtMs: number }>()@instrumented('push-notification.executeSendPushNotification')async executeSendPushNotification(@@ -666,7 +669,11 @@ export class PushNotificationService {this.pruneDeviceToken(result, invocation, params.distinctId, subscription.propertyKeys, 'apns')addLog('warn', `APNs: ${outcome.message}`)} else if (outcome.error) {- const keyAccepted = apnsAcceptedKeys.has(keyRef) || this.apnsKeyAcceptedRecently(keyFingerprint)+ // Only a provider-token rejection depends on whether the key works, so skip the shared read otherwise.+ const keyAccepted =+ !!outcome.error.code &&+ APNS_REJECTED_TOKEN_CODES.has(outcome.error.code) &&+ (apnsAcceptedKeys.has(keyRef) || (await this.apnsKeyAcceptedRecently(keyFingerprint)))const error = keyAccepted ? retriableTokenRejection(outcome.error) : outcome.errorif (error instanceof ApnsTokenRejectionError) {apnsAcceptedKeys.add(keyRef)@@ -810,6 +817,14 @@ export class PushNotificationService {return replacement}+ // Apple answers a second token inside its refresh window with TooManyProviderTokenUpdates for the rest of+ // that window, so a new token cannot help while the rejected one is still young.+ const rejectedIssuedAtMs = apnsJwtIssuedAtMs(rejectedJwt)+ if (rejectedIssuedAtMs !== null && Date.now() - rejectedIssuedAtMs < APNS_JWT_REFRESH_WINDOW_SECONDS * 1000) {+ apnsProviderTokenRefreshCounter.labels({ outcome: 'skipped' }).inc()+ return null+ }+// Fails closed: without Valkey a pod cannot tell whether the fleet already refreshed this key.const refreshKey = `${APNS_JWT_REFRESH_PREFIX}${fingerprint}`const claimed = await this.valkey.useClient({ name: 'apns-jwt-refresh', failOpen: true }, (client) =>@@ -907,8 +922,16 @@ export class PushNotificationService {}private rememberApnsKeyAccepted(fingerprint: string): void {+ const nowMs = Date.now()+ let sharedAtMs = this.apnsKeyAcceptedAtMs.get(fingerprint)?.sharedAtMs ?? 0+ if (nowMs - sharedAtMs >= APNS_KEY_ACCEPTED_SHARE_INTERVAL_MS) {+ sharedAtMs = nowMs+ void this.valkey.useClient({ name: 'apns-key-accepted-write', failOpen: true }, (client) =>+ client.set(`${APNS_KEY_ACCEPTED_PREFIX}${fingerprint}`, '1', 'EX', APNS_JWT_REFRESH_WINDOW_SECONDS)+ )+ }this.apnsKeyAcceptedAtMs.delete(fingerprint)- this.apnsKeyAcceptedAtMs.set(fingerprint, Date.now())+ this.apnsKeyAcceptedAtMs.set(fingerprint, { acceptedAtMs: nowMs, sharedAtMs })if (this.apnsKeyAcceptedAtMs.size > APNS_JWT_LOCAL_CACHE_MAX) {const oldest = this.apnsKeyAcceptedAtMs.keys().next().valueif (oldest !== undefined) {@@ -917,9 +940,15 @@ export class PushNotificationService {}}- private apnsKeyAcceptedRecently(fingerprint: string): boolean {- const acceptedAtMs = this.apnsKeyAcceptedAtMs.get(fingerprint)- return acceptedAtMs !== undefined && Date.now() - acceptedAtMs < APNS_JWT_REFRESH_WINDOW_SECONDS * 1000+ private async apnsKeyAcceptedRecently(fingerprint: string): Promise<boolean> {+ const acceptedAtMs = this.apnsKeyAcceptedAtMs.get(fingerprint)?.acceptedAtMs+ if (acceptedAtMs !== undefined && Date.now() - acceptedAtMs < APNS_JWT_REFRESH_WINDOW_SECONDS * 1000) {+ return true+ }+ const shared = await this.valkey.useClient({ name: 'apns-key-accepted-read', failOpen: true }, (client) =>+ client.get(`${APNS_KEY_ACCEPTED_PREFIX}${fingerprint}`)+ )+ return shared !== null && shared !== undefined}private rememberApnsJwtLocally(cacheKey: string, jwt: string): void {diff --git a/nodejs/src/cdp/utils/push-subscription-utils.ts b/nodejs/src/cdp/utils/push-subscription-utils.tsindex 1d398ef964ef..ede9048ae4c6 100644--- a/nodejs/src/cdp/utils/push-subscription-utils.ts+++ b/nodejs/src/cdp/utils/push-subscription-utils.ts@@ -15,8 +15,7 @@ export interface DeviceSubscription {token: string}-/** Person property key holding one device's push token. Mirrors `device_subscription_key` in- * `push_subscriptions.py`; the two must agree or a registration lands on a key sends never read. */+/** Person property key holding one device's push token. */export function deviceSubscriptionKey(appIdentifier: string, token: string): string {return `${DEVICE_SUBSCRIPTION_PREFIX}${appIdentifier}:${createHash('sha256').update(token)