Skip to content

Expo / EAS Push Notifications ​

PPP sends push notifications to the PPP mobile app through the Expo push service using the expo-server-sdk package. Every push originates from the tRPC backend and fans out to all registered device tokens for a given user. There is no Firebase Cloud Messaging or APNs code in PPP — Expo abstracts both APIs behind a single sendPushNotificationsAsync call.

1. Purpose ​

The PPP mobile app (#5112, PR #5125) uses push notifications for:

  • CPD reminders — plan submission prompts, approval notifications, milestone celebrations
  • Wellness reminders — questionnaire prompts, retrospective reminders
  • Timesheet reminders — geo-fence exit nudges, Monday-morning submission reminders
  • 360 peer review — invitation and reviewed notifications
  • System and platform notifications — generic updates not tied to a clinical workflow

Most notifications come from the notification service (see Notifications feature spec), which decides whether to send and what to say, and then delegates how to send to sendPushNotification from api/backend-ppp/src/utils/send-push-notification.ts.

2. Where it's wired ​

FilePurpose
api/backend-ppp/src/utils/send-push-notification.tsSingleton Expo client, token validation, send + cleanup
api/backend-ppp/src/services/notificationService/index.tsCreates notification rows and triggers pushes
api/backend-ppp/src/services/workQueueService/dailyDigestService.tsBatches daily digest notifications
packages-shared/ppp/schema — userNotifications tableStores registered device tokens per user

Token lifecycle ​

  1. On app startup the mobile client requests permission and asks Expo for a push token (ExponentPushToken[…]).
  2. The client POSTs the token to the tRPC userNotificationToken.save procedure (input: { userId, token, platform: 'ios' | 'android' }), which upserts a row in userNotifications keyed by (userId, token) via userNotificationTokenService.
  3. When the backend needs to send a push, sendPushNotification({ userId, message }, ctx) looks up every token registered for that user and sends a batch.
  4. If Expo reports a token as DeviceNotRegistered or InvalidCredentials, the sender removes it from the database in the same request. Stale tokens never accumulate.

tRPC procedures ​

ProcedurePurpose
userNotificationToken.save (mutation)Upserts an Expo push token + platform for the authenticated user
notifications.list (query)Returns in-app notifications; does not itself push
notifications.update (mutation)Updates a notification (e.g. marks it read); usually called from the app
notifications.getActionItemCountReturns unread + action item counts for the bell badge

Pushes are never triggered by a direct tRPC call. They are always a side effect of another operation — CPD plan reviewed, timesheet submitted, wellness questionnaire due — and fire from inside the relevant service.

3. Configuration ​

Expo's push API is authenticated by the token itself, not by an API key. A client with a valid ExponentPushToken[…] can send a push to that token — but Expo imposes rate limits and abuse protection.

Environment variables ​

PPP does not require any Expo-specific environment variables for the push path. The Expo client from expo-server-sdk is constructed with default config:

ts
expoClient = new Expo({});

The SDK reads no environment variables by default. If you need to provide an access token (for example, to use the "enhanced push security" feature or to lift rate limits), set:

VariablePurposeRequired
EXPO_ACCESS_TOKENPersonal/organisation access token from expo.dev (optional for now)No

EAS Build and OTA updates ​

The mobile app itself is built and published through EAS Build and EAS Update in a separate mobile repo. Those are developer-facing concerns for the mobile team and do not touch PPP backend env vars. Push delivery and mobile releases are decoupled: you can roll out a new push notification type without cutting a new mobile build, and you can cut a new mobile build without touching the push code.

4. Resilience ​

Because the notification service fires pushes from the request path (e.g. "CPD plan approved" triggers a push and returns the tRPC response), the sender must fail fast and degrade gracefully. It uses the shared resilience helpers:

  • Circuit breaker — expoCircuitBreaker trips after 10 consecutive failures and stays open for 60 seconds. When the breaker is open, sendPushNotification returns an empty success response (so the calling procedure does not error out) and logs that pushes are temporarily unavailable.
  • Retry with backoff — up to 2 retries on transient errors (isTransientError), starting at 500ms base delay.
  • Timeout — 10 seconds via withTimeout. Beyond that, the batch is aborted.
ts
const tickets = await expoCircuitBreaker.execute(() =>
  withRetry(
    () =>
      withTimeout(
        _signal => expo.sendPushNotificationsAsync(validMessages),
        10_000,
        'expo-push-notification',
      ),
    { maxRetries: 2, baseDelayMs: 500, shouldRetry: isTransientError },
  ),
);

If the circuit breaker is open, the user will not get a push for that notification, but the in-app notification row is still created — next time they open the app they will see it in the notification centre. Push is a best-effort delivery channel; the in-app list is the canonical record.

5. Failure modes ​

FailureUser impactOperator action
Expo push service is downPushes queue inside Expo; circuit breaker opens after 10 failuresMonitor status.expo.dev
User has no registered tokensSender returns success: false with totalTokens: 0, logs, no-opNone — user hasn't opened the app on a device yet
Token is malformedInvalid token is removed from DB immediatelyNone — self-heals
DeviceNotRegisteredToken is removed from DB after the send attemptNone — self-heals
InvalidCredentialsToken is removed from DB; usually means the app was uninstalled/reinstalledNone — self-heals
Circuit breaker openPush is silently dropped; in-app notification still landsInvestigate recent failures in logs
iOS / Android rejected the pushExpo reports a ticket error; message is logged with last 8 chars of tokenReview logs for push notification error for token

Observability ​

Every push operation is logged with service: 'push-notification' and a userId field. To tail recent pushes in production:

kql
ContainerAppConsoleLogs_CL
| where Log_s contains "service=push-notification"
| project TimeGenerated, Log_s
| order by TimeGenerated desc
| take 200

Metrics worth monitoring:

  • Push success rate — successCount / totalTokens across a time window
  • Circuit breaker open events — should be zero in steady state
  • Token cleanup rate — how often tokens are being removed; spikes indicate an app regression or mass reinstall
  • Send latency — sendPushNotificationsAsync round-trip time

6. Cost and billing ​

The Expo push service itself is free of charge — there are no per-message fees. Rate limits apply (~600 notifications per second per project, burst limits on individual tokens), but PPP is nowhere near them.

EAS Build and EAS Update — used to compile and ship the mobile app — do have a cost tier based on build minutes and bandwidth. Those costs are billed to the mobile project and are not tied to push delivery volume.

7. Testing ​

Unit tests ​

bash
cd api/backend-ppp
pnpm test -- send-push-notification

The test suite mocks the Expo SDK and verifies:

  • Valid tokens produce sendPushNotificationsAsync calls with the correct message shape
  • Invalid tokens are removed from the DB in the same request
  • Circuit breaker open state returns a graceful empty response
  • Transient failures are retried
  • DeviceNotRegistered errors trigger token cleanup

Smoke testing locally ​

You cannot send a real push to a simulator — Expo requires a physical device registered to a project. To smoke-test the delivery path without a real device:

  1. Set up an Expo account and project, and install the Expo Go app on a physical iOS or Android device
  2. Run the PPP mobile app against your local backend, log in, and capture the registered push token
  3. Trigger a notification from the PPP backend (e.g. approve a CPD plan) and confirm the push arrives

For most PPP backend work, the mocked unit tests are sufficient — the push path is small and well-covered.

Internal documentation — org members only