skip to content

In an Android FirebaseMessagingService, why do some 'courier nearby' alerts never appear when onMessageReceived fetches courier details before posting the notification?

level: seniorimportance: should knowfreq 44%

answer

  1. a short window, then nothing guaranteed
  2. worker thread is not the problem
  3. post first, enrich later
  4. WorkManager: expedited for high priority
  5. onDeletedMessages means resync

basics

~20 s

onMessageReceived gets a short window, several seconds, before the process may lose its valid lifecycle; a network fetch first can be paused or killed by background limits. Post from the payload at once and hand slower work to WorkManager.

solid answer

~50 s

`onMessageReceived` runs on a worker thread, so the fetch does not block the main thread; the problem is **time**. FCM gives the handler a short execution window, several seconds per the guidance with slightly more for high-priority messages; the SDK's javadoc says it should complete within 20 seconds, and OS delays, app start-up or earlier slow handlers shrink it. On a slow network the fetch outlives the window, background execution limits pause or kill the process, and the alert never posts. Starting my own thread does not help, because nothing keeps the process alive after the callback returns. The fix is to put what the alert needs in the payload and post it immediately, then move slower work to `WorkManager`: an expedited job for a high-priority message, which gets a brief quota exemption right after one, and a regular `WorkRequest` for normal priority.

code

kotlin · 31 lines
kotlin
class ParcelMessagingService : FirebaseMessagingService() {

    // Worker thread, short window: post first, defer anything slow.
    override fun onMessageReceived(message: RemoteMessage) {
        val parcelId = message.data["parcelId"] ?: return
        val eta = message.data["eta"].orEmpty()

        // 1. Post at once from the payload: no network call before the user sees it.
        showCourierNearby(parcelId, eta)

        // 2. Enrichment leaves the callback's window through WorkManager.
        val refresh = OneTimeWorkRequestBuilder<RefreshParcelWorker>()
            .setInputData(workDataOf("parcelId" to parcelId))
            .build()
        WorkManager.getInstance(applicationContext).enqueue(refresh)
    }

    private fun showCourierNearby(parcelId: String, eta: String) {
        // Build and post the notification with NotificationManagerCompat here.
    }
}

class RefreshParcelWorker(context: Context, params: WorkerParameters) :
    CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        val parcelId = inputData.getString("parcelId") ?: return Result.failure()
        // Fetch courier details for parcelId and update local storage.
        return Result.success()
    }
}

go deeper

for a junior

Remember that onMessageReceived must finish quickly and that it runs off the main thread; long work goes to WorkManager.

for a middle

Explain the window: several seconds, a bit more for high priority, 20 seconds as the javadoc's ceiling, and why a fire-and-forget thread is not protected.

for a senior

Diagnose missing alerts from field data: high-latency users, the fetch-then-post pattern, and the fix of payload content plus expedited or regular work by priority.

for a principal

Set the rule for the team: every alert renders from its payload alone, enrichment is optional, and the server owns putting the needed fields in the message.

## The execution window When an FCM message reaches an Android app's `FirebaseMessagingService`, the SDK calls `onMessageReceived(message)` on a **worker thread**, not the main thread. That rules out one false diagnosis: a network call there does not throw because of the main thread. The real constraint is **how long** the app is allowed to run. Android gives the app a short window to process the message: - Firebase's guidance gives **several seconds** for both priorities, with **slightly more for high-priority messages**, meant to be long enough to render a notification immediately. - The javadoc on `onMessageReceived` says it **should complete within 20 seconds**, and that taking longer may interfere with your work and with pending messages. - The window shrinks with OS delays, app start-up time, a main thread blocked by other work, and earlier `onMessageReceived` calls that took too long. Once the handler outlives that window, the process may no longer be in a valid lifecycle, and **background execution limits** can pause or terminate it before the work completes. The user sees a delayed alert or none at all. ## Why "fetch, then post" loses alerts Take a parcel-tracking app that receives a data message with a `parcelId` and, before posting "Courier nearby", calls its server for the courier's name, photo and ETA. On a fast network this works in testing. In the field: 1. A small share of users are on high-latency networks; the call takes longer than the window. 2. The process is paused or killed mid-request; the notification line is never reached. 3. Nothing reports a failure: FCM delivered the message and the app simply did not finish. Moving the call to a thread or coroutine the handler starts and forgets makes it worse, not better. `onMessageReceived` returns at once, and **nothing keeps the process alive** for the background work, so it is the first thing cut when the app leaves a valid lifecycle. ## Doing it right 1. **Put the alert's content in the message.** The server already knows the ETA; send it in `data`, or as a notification part the SDK displays itself when the app is in the background. 2. **Post the notification immediately** from the payload inside `onMessageReceived`. 3. **Hand anything slower to WorkManager**: - for a **high-priority** message, enqueue an **expedited** job; FCM's guidance notes a brief exemption from expedited-job quotas for jobs scheduled right after a high-priority message is dispatched; - for a **normal-priority** message, enqueue a regular `WorkRequest`, which runs eventually without spending prioritized time. 4. A foreground service is the other documented way to extend the lifecycle when the work is user-visible and long. `RemoteMessage.priority` tells the handler which priority the message was delivered with, and `RemoteMessage.originalPriority` the priority it was sent with. When the two differ, FCM has lowered a high-priority message to normal; why FCM does that is covered with push delivery design. ## When the SDK displays the notification itself For a **notification message** in the background, the SDK builds the notification. If the payload names an image, the SDK downloads it on a separate thread and waits at most **5 seconds**; on timeout it posts the notification without the image. That is the same idea applied by the SDK: never let enrichment stop the alert. ## Related callbacks in the same service | Callback | When it fires | What the app should do | |---|---|---| | `onMessageReceived` | A data message, or any message in the foreground | Post at once, defer slow work | | `onDeletedMessages` | FCM discarded pending messages: more than 100 were waiting, or the device had not connected for over a month | Run a full sync with the server | | `onRegistered` | Registration by Installation ID succeeded or was refreshed | Upload the identifier | FCM will not call `onDeletedMessages` if you have not sent a message to that device in the last four weeks. While the process lives, the SDK also drops a message whose ID matches one of the last ten it received, which filters an immediate redelivery; it is not a durable de-duplication store, so handlers that change data should still tolerate seeing a message twice. ## What interviewers look for - The window is about lifecycle, not threads. - Content belongs in the payload; enrichment is optional and deferred. - Expedited versus regular work follows the message's priority.

  • When should the deferred work be an expedited job rather than a regular WorkRequest?
    Follow the message's priority. For a high-priority message, FCM's guidance is an expedited WorkManager job, and jobs scheduled right after a high-priority message get a brief exemption from expedited quotas. For normal priority, a regular `WorkRequest` runs eventually without spending prioritized processing time.
  • What does onDeletedMessages tell the app, and what should it do?
    FCM discarded messages that were pending for this device, because more than 100 piled up or the device had not connected for over a month. The app cannot recover them individually, so it runs a full sync with its server. FCM skips the callback if nothing was sent to that device in the last four weeks.

  • onMessageReceived runs on the main thread, so moving the fetch to a thread fixes it
  • onMessageReceived may take as long as it needs once the message arrives
  • High priority gives the handler unlimited time to fetch extra content
  • Starting a coroutine from onMessageReceived keeps the process alive until it finishes
  • onDeletedMessages means the registration was deleted and must be re-uploaded