Push Notification Interview: Can You Collapse a Score Update Without Losing a Chat Message?
Quick Overview
An offline-device trace separates replaceable sports scores from immutable chat events. Run a small notification model and a reopened SQLite journal to show what expiry, replacement and duplicate delivery can safely change.
Yes, a score update can replace an older score without losing a chat message, provided replacement is scoped to superseded state and the chat history lives outside the push queue. A collapse key describes what may replace what. It is not a conversation archive, a delivery receipt or a retry identifier.
This interview exercise puts two sports matches and two private messages on one offline-device timeline. Use PracHub’s extensible notification-system question to explain the contract before drawing provider adapters. The important decision is which missing notification can be reconstructed and which application fact must remain stored.

State the provider boundary before choosing keys
Official Firebase documentation describes a collapsible message as replaceable while still pending. Its Android collapse guidance uses sports scores as an example and names chat as a typical non-collapsible use. It also says delivery order is not guaranteed.
That is provider behavior. Our separate design decision is to store immutable chat events in an application journal and use notifications to prompt synchronization. The locally executed Python example models a pending queue and opens a real temporary SQLite file. It makes no Firebase request, runs no mobile device and measures no delivery latency. There are no candidate reports or employer-process claims here.
Ask whether the score payload is a complete current snapshot or an incremental event. Replacing “current score is 2–1” with “current score is 3–1” can make sense. Replacing “add one goal” with another “add one goal” discards an operation. Similar-looking payloads can require different transport contracts.
For chat, distinguish a display alert from the message itself. A single “conversation changed” hint can represent several stored messages if the client fetches all unseen events. If push bodies are the only copy, collapsing them destroys content. The architecture must make that difference visible.
Interleave the offline events
Our synthetic clock starts with the device unavailable. Match m1 receives score version 10 at time zero, then version 11 at time two. Conversation c7 receives events c41 and c42 between those score updates. Another match, m2, receives its own score snapshot at time four.
| Arrival time | Application fact | Pending representation | Model expiry |
|---|---|---|---|
| 0 | m1 score version 10 | Replaceable under score:m1 | 30 |
| 1 | c7 event c41, sequence 41 | Separate event notification | 121 |
| 2 | m1 score version 11 | Replaces m1 version 10 | 32 |
| 3 | c7 event c42, sequence 42 | Separate event notification | 123 |
| 4 | m2 score version 1 | Replaceable under score:m2 | 34 |
At reconnect time 10, the original model exposes c41, c42, s11 and s20. Score s10 is absent because the newer m1 snapshot replaced it. The second match remains independent, and neither chat event occupied a score slot.
These absolute expiry values are chosen application test inputs. They are not Firebase request fields or recommended production durations. A real sender maps remaining relevance into the provider’s supported lifespan representation. A retry must not accidentally extend a stale score’s useful life by resetting its business deadline.
Now try the deliberately bad policy: put s10, c41 and s11 under one key named all-updates. Only s11 remains. Nothing about a successfully accepted push request would reveal that the application chose an unsafe replacement scope. The loss follows directly from the key contract.
Separate identity, replacement and ordering
An event ID answers whether two attempts refer to the same immutable fact. A collapse key groups pending notifications whose older contents may be superseded. A score version orders snapshots within one match. These identifiers need not have the same value or cardinality.
The example keeps a unique ID for each chat event and a per-match score key. It then uses a version guard when applying score snapshots. Receiving version 11, then 10, then 11 leaves version 11 visible. Neither arrival order nor a duplicate retry should regress the score.
That guard assumes the producer provides a trustworthy monotonic version within a stable match identity. A random timestamp from two unsynchronized writers would need a stronger conflict rule. Our model does not solve distributed sequencing; it makes the prerequisite explicit so a candidate cannot hide it inside a string key.
Also scope state to the authenticated account and destination. An application should not display a previous user’s pending conversation after an account switch. The local fixture uses one synthetic user and no registration tokens; token ownership, logout and authorization checks remain necessary integration work.
Test the queue and the stored history separately
This complete Python program creates the temporary journal, commits both chat events, interleaves pending notifications, expires them and reconnects to the same file. Its queue is an original model rather than an emulator of provider capacity or scheduling.
import sqlite3
import tempfile
from pathlib import Path
class Pending:
# Original offline queue model, not an FCM implementation.
def __init__(self):
self.items = {}
def put(self, event_id, kind, scope, version, expiry, key=None):
slot = ("collapse", key) if key is not None else ("event", event_id)
self.items[slot] = dict(id=event_id, kind=kind, scope=scope,
version=version, expiry=expiry)
def at(self, now):
return [x for x in self.items.values() if now < x["expiry"]]
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "chat.db"
db = sqlite3.connect(path)
db.execute("CREATE TABLE chat(conversation TEXT, seq INTEGER, "
"event_id TEXT UNIQUE, body TEXT, "
"PRIMARY KEY(conversation, seq))")
for seq, event_id, body in [(41, "c41", "Meet at gate B"),
(42, "c42", "Bring the tickets")]:
db.execute("INSERT INTO chat VALUES(?,?,?,?)", ("c7", seq, event_id, body))
db.commit()
pending = Pending()
pending.put("s10", "score", "m1", 10, 30, "score:m1")
pending.put("c41", "chat", "c7", 41, 121)
pending.put("s11", "score", "m1", 11, 32, "score:m1")
pending.put("c42", "chat", "c7", 42, 123)
pending.put("s20", "score", "m2", 1, 34, "score:m2")
assert sorted(x["id"] for x in pending.at(10)) == ["c41", "c42", "s11", "s20"]
assert pending.at(130) == []
db.close()
db = sqlite3.connect(path) # New connection, same committed file.
recovered = db.execute("SELECT seq,event_id,body FROM chat "
"WHERE conversation=? AND seq>? ORDER BY seq",
("c7", 40)).fetchall()
assert [row[1] for row in recovered] == ["c41", "c42"]
applied = {}
for row in recovered + recovered: # Repeated fetch must not duplicate display.
applied[row[1]] = row
assert len(applied) == 2
db.close()
bad = Pending()
for event_id, kind in [("s10", "score"), ("c41", "chat"), ("s11", "score")]:
bad.put(event_id, kind, "mixed", 0, 30, "all-updates")
assert [x["id"] for x in bad.at(10)] == ["s11"]
score_version = -1
for incoming in [11, 10, 11]:
if incoming > score_version:
score_version = incoming
assert score_version == 11
print({"pending_at_10": ["c41", "c42", "s11", "s20"],
"pending_at_130": [], "recovered_chat": ["c41", "c42"],
"bad_shared_key": ["s11"], "score_version": score_version})
The printed receipt reports four pending IDs at time 10 and none at time 130. After the database connection is closed and reopened, a query after conversation sequence 40 still returns c41 and c42. Applying that recovered result twice leaves two displayed event IDs.
The test proves those particular local journal, expiry and deduplication properties. It does not simulate power loss, replicated storage, filesystem failure, mobile background restrictions or provider retries. Calling the file “durable application history” describes its responsibility; the run only verifies committed data surviving a connection reopen.
The queue’s expiry comparison treats now equal to expiry as expired. That is an explicit mock contract. Relevance checks should also happen when consuming a delayed message: a payload can become obsolete between provider acceptance, arrival and display.
Recover even when no notification survives
At time 130 every modeled notification has expired. If the device treats an empty pending list as proof that no chat happened, it stays wrong forever. It needs an independent synchronization trigger, such as reconnect or opening the conversation, using its last confirmed application cursor.
The cursor belongs to the journal, not the notification queue. Fetch conversation c7 after sequence 40, apply events 41 and 42, and advance only after the intended local state is stored. Repeating the fetch is acceptable when event application is idempotent. A production cursor must also define retention and gap recovery when old events are no longer available.
Persisting chat and publishing its hint creates another boundary. If the database commit succeeds but the process stops before enqueueing, the message should still be discoverable through synchronization. A transactional outbox is one possible extension for reliable notification intent, but this small example does not implement or test one.
Conversely, a hint published before the journal transaction commits can wake a client before the event is readable. State which store is authoritative and how the client retries a version it has been told exists. The push request alone is not evidence that the application record is committed or readable.

Respect provider limits without treating them as storage
Firebase’s Android guidance limits concurrently retained collapse keys per registration token to four and makes retention unspecified beyond that set. It also documents a bounded non-collapsible backlog that can be discarded on overflow. Notification messages are always collapsible and ignore the supplied collapse key. These constraints make “one key for every conversation forever” an unsafe design shortcut.
Our model does not reproduce those limits. It uses two score keys and explicitly chosen event slots to demonstrate application semantics. For a real high-cardinality account, a broader sync hint can replace many hints only when an authoritative fetch recovers all affected state. Changing that grouping is a product and recovery decision, not just a queue optimization.
The lifespan documentation separately explains that provider acceptance is not device delivery and that zero TTL discards work unavailable for immediate delivery. The fixture covers expiry of stored mock notifications; it does not test zero-TTL online delivery.
Keep platform adapters explicit. Android, Apple and Web Push expose different fields and behavior. The contract in this article is Android-focused; copying its field names into another provider request would not establish equivalent semantics. Verify the destination platform’s current documentation before implementing that adapter.
Diagnose missing chat at the correct layer
Start with the application event ID. Was c41 committed, and is it still visible to an authorized journal query? If yes, inspect notification intent, replacement scope, provider acceptance, expiry and the client’s sync cursor as separate evidence. If no, changing collapse keys cannot restore a record the application never stored.
For the score, compare the displayed version with the authoritative match version. A collapsed old snapshot is expected; a newer snapshot overwritten by a late old delivery is a consumer ordering bug. Logging only a count of “notifications sent” cannot distinguish those two outcomes.
Record identifiers and versions without putting private message contents in routine transport logs. The synthetic fixture prints event IDs and stores toy text solely to make assertions readable. Real operational traces should allow correlation while respecting account boundaries and data minimization.
The broader notification-system design guide covers fan-out, preferences and channel retries. Bring this narrower replacement contract into that architecture: the provider may discard a hint, while the product must still explain how a reader obtains the underlying message.
The recovery cursor also needs a failure boundary on the client. Suppose c41 is displayed but the client crashes before saving its cursor. On reconnect, fetching after 40 can return c41 again along with c42. The fixture's immutable-ID application handles that repeated result, but a production client must persist display state and cursor progress under its chosen local storage contract. A notification acknowledgment cannot substitute for that application checkpoint.
Now reverse the order: advancing the cursor to 42 before saving the two events can make a later fetch skip data the client never retained. The example does not execute a mobile crash or local transaction, so this is a proposed integration test, not another passed result. It follows directly from the journal-versus-hint distinction and gives the interviewer a concrete next boundary to defend.
For the score, store the match identity together with its accepted version. A version number from m2 should never suppress a valid update from m1. The two separate pending slots illustrate the identity boundary; equivalent per-match scoping is needed when applying snapshots in a real client, even if transport delivery and storage mechanisms change.
Rehearse the replacement and recovery decisions
These five prompts connect replacement semantics to extensibility, per-recipient fan-out, duplicate delivery and channel adapters. Some overlap the broader notification guides because the integration boundary is shared; the worked score-and-chat trace adds the specific failure those general architectures must survive.
| PracHub question | What to practise |
|---|---|
| Design an extensible notification system for email, SMS, iOS and Android push | Separate replaceable score state from durable message history. |
| Design a follower push-notification system | Scope replacement to the recipient and meaning of an update. |
| Design at-least-once notification delivery | Handle missing and duplicate transport notifications. |
| Unify Notification Services Without Duplicate Delivery | Keep application IDs stable across channel retries. |
| Design a Multi-Channel Notification System | Declare platform-specific collapse and expiry adapters. |
Return to the extensible notification-system exercise and remove every pending push from the diagram. Show how both chat events still reach the conversation view, then show why m1 needs only its newest valid score. That demonstration makes the meaning of “safe to collapse” concrete.
Comments (0)