iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔔

Designing Push Notifications with Expo, Firebase, and SST

に公開

Introduction

In the diary app Storyie, we have implemented "diary reminder notifications" to help users build a habit of writing daily. In addition, we send alert notifications when users approach their free plan content limit.

In this article, I will introduce the design for push notifications using Firebase Cloud Messaging (FCM) in an Expo (React Native) app, as well as the mechanism for scheduled delivery using SST Cron jobs, along with insights gained through implementation.

Overall Architecture

[Expo App]
  ├─ Fetch token via @react-native-firebase/messaging
  ├─ Upsert to Supabase user_devices table
  └─ Foreground/background handling in NotificationContext

[SST (AWS Lambda)]
  ├─ DiaryReminderNotifier: Runs every 15 minutes
  ├─ Filter target users → Send via Firebase Admin SDK
  └─ Deduplication via notification_logs

The key point is that token management is client-driven, while delivery logic is handled entirely server-side. The client is responsible only for registering tokens and displaying notifications, while the server determines "who to send to, when, and what to send."

Device Token Management

Table Design

// packages/database/src/schemas/devices.ts
export const userDevices = pgTable("user_devices", {
  id: uuid("id").primaryKey().default(sql`uuid_generate_v4()`),
  userId: uuid("user_id").notNull(),
  fcmToken: text("fcm_token").notNull(),
  platform: text("platform").notNull(),  // "ios" | "android"
  isActive: boolean("is_active").notNull().default(true),
  lastSeen: timestamp("last_seen", { withTimezone: true }),
  createdAt: timestamp("created_at", { withTimezone: true }).defaultNow(),
  updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow(),
}, (table) => ({
  userFcmUniqueIdx: uniqueIndex().on(table.userId, table.fcmToken),
}));

Design considerations:

  • Unique constraint on (user_id, fcm_token): Prevents duplicates even if a user registers the same token from the same device multiple times.
  • is_active flag: Set to false when a token is invalidated. By using soft deletes instead of physical deletes, upserts function naturally when the same token is re-registered.
  • platform column: Recorded because notification payload structures differ slightly between iOS and Android.
  • Supabase RLS: Restricts operations to a user's own devices using user_id = auth.uid().

Client-Side Registration

// apps/expo/services/registerDevice.ts
export async function registerDevice() {
  const messagingInstance = getMessaging(getApp());
  const authStatus = await requestPermission(messagingInstance);

  const enabled =
    authStatus === AuthorizationStatus.AUTHORIZED ||
    authStatus === AuthorizationStatus.PROVISIONAL;
  if (!enabled) return;

  const fcmToken = await getToken(messagingInstance);
  if (!fcmToken) return;

  await supabase.from("user_devices").upsert(
    {
      user_id: user.id,
      fcm_token: fcmToken,
      platform: Platform.OS,
      is_active: true,
      last_seen: new Date().toISOString(),
    },
    { onConflict: "user_id,fcm_token" }
  );
}

Using upsert + onConflict makes it safe to call every time the app launches. Since last_seen is updated, it can also be used to detect devices that haven't been used for a long time.

Handling Notification Reception

On the Expo app side, we handle three states using NotificationContext:

App State Processing
Foreground messaging().onMessage → Display via Alert
Background messaging().onNotificationOpenedApp → Screen navigation
Cold start (Killed) messaging().getInitialNotification → Screen navigation after 1-second delay

The delay during a cold start is implemented to wait for the app's initialization to complete. Without this, navigation calls would fail.

Another subtly important detail is clearing the badge count. We call setBadgeCountAsync(0) both when the app enters the foreground and when a notification is opened. It is a minor point, but having the badge persist while the user is actively using the app can be a source of frustration.

Server-Side Delivery Design

Why Cron — In a World Without Queue Servers

In typical notification systems, processes like "send a reminder at 20:00" are often implemented using job queues (such as SQS + Worker, BullMQ, or Celery). The flow is usually: when a user sets a reminder time, a scheduled job is placed into a queue, and the worker processes it at the designated time.

However, in the SST (Serverless Stack) ecosystem, there is no direct equivalent to a constantly running Queue Worker. Lambda functions only execute when invoked. While SQS + Lambda combinations exist, handling "delay until a specific time" cleanly is difficult due to the constraints on DelaySeconds (max 15 minutes). Furthermore, using EventBridge Scheduler to manage individual schedules for every single user becomes overly complex.

At Storyie, we run all background processes via Cron, including not only notifications but also page view aggregation, like counting, email queue processing, and weekly summaries:

// sst.config.ts — A portion of the currently running Cron jobs
new sst.aws.Cron("DiaryReminderNotifier", { schedule: "cron(0/15 * * * ? *)" });
new sst.aws.Cron("EmailQueueProcessor",   { schedule: "cron(*/5 * * * ? *)" });
new sst.aws.Cron("ViewAggregator",        { schedule: "cron(0 */4 * * ? *)" });
new sst.aws.Cron("WeeklySummaryEmailSender", { schedule: "cron(0 12 ? * SUN *)" });

While this design eliminates the cost of "keeping a Queue Worker running," it does sacrifice real-time performance. Reminders can shift by up to 15 minutes, and emails might be delayed by up to 5 minutes. For a solo-developed diary app, this trade-off is acceptable, but products requiring strict real-time delivery should consider SQS + Lambda or EventBridge Scheduler instead.

Implementing Diary Reminders

Diary reminders are executed via an SST Cron job every 15 minutes.

// sst.config.ts
new sst.aws.Cron("DiaryReminderNotifier", {
  schedule: "cron(0/15 * * * ? *)",
  // ...
});

The reason it runs "every 15 minutes" rather than "once a day" is because reminder times and time zones vary for each user. A user in Tokyo who sets a reminder for 20:00 UTC differs completely from a user in New York setting it for 20:00 EST in terms of the required UTC execution time.

Process flow:

  1. Fetch users where notification_settings.diaryReminderEnabled = true.
  2. Calculate current time in each user's time zone and determine if it matches the reminder time (rounded to 15-minute increments).
  3. Exclude users who have already written a diary entry today.
  4. Exclude users who have already been notified today (using the notification_logs table).
  5. Send via Firebase Admin SDK.
  6. Record to the log.

Duplicates are managed in the notification_logs table using a combination of (user_id, notification_type, period_key). The period_key is formatted as YYYY-MM-DD for diary reminders and YYYY-MM for content limits.

Multilingual Messages

Notification messages are switched between Japanese and English based on the user's preferred_language. Additionally, we implemented logic to select messages randomly while remembering the previous index to prevent the same message from appearing consecutively.

const REMINDER_MESSAGES: Record<string, ReminderMessage[]> = {
  ja: [
    { title: "今日のひとこと 📝", body: "まだ何も書いてないよ。ひとこと残してみない?" },
    { title: "日記の時間だよ ✨", body: "今日あったこと、忘れないうちに書き留めよう。" },
    // ...
  ],
  en: [
    { title: "Time to Write! 📝", body: "You haven't written today..." },
    // ...
  ],
};

Because diary app notifications are often quickly disabled if they feel "annoying," we took care to keep the tone soft.

Content Limit Notifications

When a free plan user reaches 90% or 100% of their limit, we notify them via push notification. Unlike reminders, this is triggered at the time of content creation rather than by Cron.

For deduplication, the period_key for diaries is monthly (YYYY-MM), and for notes, it is yearly (YYYY-all). Since diary limits reset monthly, notifications must also be reset on a monthly basis.

Automatic Cleanup of Invalid Tokens

If FCM returns messaging/registration-token-not-registered, we update the token's is_active to false. This mechanism prevents sending messages to users who have uninstalled the app while ensuring the system cleans up tokens automatically upon every failed attempt.

iOS / Android Payload Differences

In FCM multicast delivery, we include optimized settings for iOS (APNs) and Android respectively:

const message = {
  tokens,
  notification: { title, body },
  apns: {
    payload: {
      aps: {
        alert: { title, body },
        sound: "default",
        badge: 1,
      },
    },
  },
  android: {
    notification: {
      channelId: "high-priority",
      priority: "high",
    },
  },
};
  • iOS: Uses badge: 1 to display a badge on the icon. Sound also requires an explicit "default" to play.
  • Android: Notifications may not appear on Android 8+ without specifying a channelId. We use priority: "high" for immediate delivery even in the background.

Insights from Operations

Do Not Underestimate Time Zone Processing

We round to 15-minute increments because Lambda invocation timing can shift by a few to several dozen seconds. Comparing strictly by the minute can lead to missed notifications where a user has a 20:00 setting but the execution happens at 20:01.

The Importance of Deciding "Not to Send"

Do not send to users who have already written a diary entry. Do not send to users who have already been notified. I have realized that the most important aspect of a notification system is "knowing when not to send." Sending too many notifications leads users to turn them off, and they may never return.

A Log Table is Essential

It was the right decision to design the notification_logs table from the start. It is useful not only for deduplication but also for acquiring operational data, such as "how many notifications are actually sent?" or "what is the ratio of invalid tokens?"

Summary

Push notifications are easy to "send," but they involve surprisingly many considerations when including time zone support, deduplication, invalid token management, and message tone.

Especially for notifications aimed at "building habits" like in a diary app, maintaining the right distance from the user is delicate. I designed this system with both technical accuracy and product-level comfort in mind.


📔 Storyie — A diary app to record your daily memories

Discussion