skip to content

A parcel-tracking backend sending through the FCM Admin SDK sees send failures pile up; which stored registrations should it delete, and on which errors must it keep them?

level: seniorimportance: should knowfreq 38%

answer

  1. only the target's own fault counts
  2. 404 is final, 400 only maybe
  3. the FID variant has its own code
  4. retry transient, fix configuration
  5. timestamps catch what errors miss

basics

~20 s

Delete a registration on UNREGISTERED (404), and on INVALID_ARGUMENT (400) only when the payload is known valid. Keep it on rate-limit, unavailable, internal or credential errors: retry or fix configuration. Also prune by upload timestamp.

solid answer

~40 s

I delete a registration only when FCM says the target itself is dead: `UNREGISTERED` (HTTP 404), which FCM returns after an app unregisters or after an Android registration expires at 270 days of inactivity, and `INVALID_ARGUMENT` (HTTP 400) only if I am sure the payload is valid, since a malformed message returns it too. In the Node.js Admin SDK 14.5.0 a 404 maps to `messaging/registration-token-not-registered` for a `token` target but to `messaging/installation-id-not-registered` for an `fid` target, so a pruning check written for tokens misses every FID. Errors such as `messaging/server-unavailable`, `messaging/internal-error` and `messaging/message-rate-exceeded` are retried with backoff; `messaging/mismatched-credential` points at the wrong project or credential. Errors only catch the dead, so I also store a timestamp per registration and drop, and unsubscribe from topics, any older than my window, a month by FCM's default.

code

typescript · 25 lines
typescript
import { getMessaging, FidMulticastMessage } from 'firebase-admin/messaging';

// Codes that mean the target itself is gone (Admin SDK for Node.js 14.5.0).
const DEAD_TARGET_CODES = new Set([
  'messaging/installation-id-not-registered',
  'messaging/registration-token-not-registered',
]);

export async function sendAndPrune(
  fids: string[],
  data: Record<string, string>,
  deleteRegistration: (fid: string) => Promise<void>,
): Promise<void> {
  const message: FidMulticastMessage = { fids, data };
  const batch = await getMessaging().sendEachForMulticast(message);

  await Promise.all(
    batch.responses.map(async (res, i) => {
      // responses[i] belongs to fids[i]; other errors are retried elsewhere, never deleted.
      if (!res.success && res.error && DEAD_TARGET_CODES.has(res.error.code)) {
        await deleteRegistration(fids[i]);
      }
    }),
  );
}

go deeper

for a junior

Know that FCM tells a server when a registration is gone, with UNREGISTERED (404), and that the server should then forget it.

for a middle

Explain why INVALID_ARGUMENT is only a conditional delete, the 270-day Android expiry, and how BatchResponse order maps failures to FIDs.

for a senior

Separate dead-target errors from transient and configuration errors, catch the new FID error code, and add timestamp pruning and topic unsubscription.

for a principal

Own the staleness window and the deletion policy: what counts as dead, who may delete during an incident, and which delivery signals the team watches.

## Why registrations go bad A backend that sends **Firebase Cloud Messaging (FCM)** messages to individual app instances keeps a table of registrations: one Firebase Installation ID (FID), or a legacy registration token, per install. Over time that table fills with entries that will never receive anything: - the phone was lost, broken or put in a drawer; - the app was uninstalled, or was reinstalled or had its data cleared, which leaves the old FID behind; - the app called `unregister()`. FCM's own rules: a registration whose device has not connected for **over a month** is **stale**, and on Android a registration inactive for **270 days** is **expired**, garbage-collected and rejected on send. Sending to stale and expired entries wastes quota, slows topic fan-outs, and makes delivery reports show a drop that is not real. ## Errors that justify deleting | FCM error (HTTP v1) | Admin SDK for Node.js code | Action | |---|---|---| | `UNREGISTERED` (404), `token` target | `messaging/registration-token-not-registered` | Delete the token | | `UNREGISTERED` (404), `fid` target | `messaging/installation-id-not-registered` | Delete the FID | | `INVALID_ARGUMENT` (400) | `messaging/invalid-argument` | Delete only if the payload is known valid | The second row is new with FID registration. In Admin SDK 14.5.0, when a 404 answers a request whose message carried an `fid`, the SDK reports `messaging/installation-id-not-registered` instead of the token code. The example in Firebase's own registration guide sends with `fid` but checks only `messaging/registration-token-not-registered`, so code copied from it and run on Admin SDK 14.5.0 **misses unregistered FIDs**. `INVALID_ARGUMENT` needs care: FCM returns it both for a bad target and for a problem in the message itself. Delete on it only when the same payload succeeds for other targets. ## Errors that must not delete These say nothing about the target: - `messaging/server-unavailable` and `messaging/internal-error`: transient; retry with exponential backoff. - `messaging/message-rate-exceeded` (FCM's `QUOTA_EXCEEDED`) and the device or topic rate variants: you are sending too fast; slow down and retry. - `messaging/mismatched-credential` (`SENDER_ID_MISMATCH`): the credential has no permission to send to that registration, because the two belong to different Firebase projects. After a deploy this usually means the backend points at the wrong project; check its configuration before touching data. - `messaging/authentication-error` or `messaging/third-party-auth-error`: a credential problem on your side or with a platform push service. Deleting on any of these turns an outage or a misconfiguration into lost users: every install whose send failed during the incident silently stops receiving alerts until the app uploads its FID again. Picture the parcel app on the evening a backend release swaps in a service account from the staging project. Every send now fails with `messaging/mismatched-credential`. A pruning rule of "delete on any error" empties the registration table within an hour, and fixing the credential the next morning brings back only the users who happen to open the app, because a fresh upload happens only when the app runs and `onRegistered` fires again. A rule that deletes on the not-registered codes alone loses nothing. ## Proactive pruning by timestamp Errors only reveal registrations that are already dead. To catch the stale ones: 1. Store a **timestamp** with each FID and refresh it on every upload. With Installation-ID registration and auto-init enabled, `onRegistered` fires on routine syncs at app start, so an active install keeps its timestamp current with no extra client job. 2. Pick a **staleness window**. FCM treats a month without connection as stale; your product may choose longer or shorter. 3. Run a daily job that removes registrations older than the window, before they are targeted. A scheduled function is one way to run it. 4. When sending a multicast, read the `BatchResponse`: its `responses` follow the order of the `fids` you passed, so index `i` maps back to `fids[i]`. ## Topics Topic subscriptions outlive the registration table. For each install pruned as stale, call the Admin SDK's `unsubscribeFromTopic` for its topics, and have the app resubscribe whenever its FID changes. Stale instances then rejoin automatically when they come back, and every fan-out reaches fewer dead targets and finishes sooner. ## Signals worth watching - For Android, the FCM Data API reports messages dropped because the device was inactive (`droppedDeviceInactive`); a rising share means pruning is behind. - A delivery rate that falls while sends grow usually means stale registrations, not an FCM problem.

  • Why is INVALID_ARGUMENT a weaker signal than UNREGISTERED?
    FCM returns `INVALID_ARGUMENT` for a malformed message as well as for a bad target. If a payload bug slips into a release, every send fails with 400, and a backend that deletes on it wipes its whole registration table. Delete on it only when the same payload succeeds for other targets.
  • Why would a backend migrated to FIDs stop pruning anything, with no errors in its logs?
    Its check compares the error code to `messaging/registration-token-not-registered`. In the Node.js Admin SDK 14.5.0, a 404 for an `fid` target is reported as `messaging/installation-id-not-registered`, so the condition is never true and dead FIDs accumulate silently.

  • Any failed send means the registration is dead and should be deleted
  • INVALID_ARGUMENT always means the registration is invalid
  • Checking registration-token-not-registered also catches unregistered FIDs
  • FCM errors find every stale registration, so timestamps are unnecessary
  • Rate-limit errors mean the device has blocked the app's messages

Assumes the Firebase Admin SDK for Node.js 14.5.0, which reports an unregistered fid target as messaging/installation-id-not-registered; fid targets exist since Installation-ID registration in firebase-messaging 25.1.0.