This is the implementation material behind the travel plans app interview case. It covers:
- the local schema, the REST calls and the merge rule
- order keys, deletes, time zones and the sync cursor
- photos, roles, platform limits and the iOS version
None of it belongs in a 45-minute round (the length I assume). I draw it only if asked. The snippets use Room 3.0 (androidx.room3, current stable 3.0.3, from the Room guide and the 2.x to 3.0 migration guide). Room 3 needs KSP (no KAPT) and a SQLiteDriver on the builder. I did not compile these snippets against Room 3. The design is the same with Room 2.x (androidx.room). The model is the one on the offline-first hub.
1. Local schema (Room)
The local tables are:
tripitinerary_item, withsortKey, the time fields,serverRev, adeletedAttombstone and adirtyflagop_outbox(opId, tripId, itemId, field, value, baseRev, createdSeq), one row per waiting field change, ordered by a local countermedia, the upload queue, in the style of photo and file syncsync_state(scope, cursor)
@Entity(
tableName = "itinerary_item",
indices = [Index("tripId", "sortKey", "itemId")], // order by sortKey, break ties by itemId
)
data class ItineraryItemEntity(
@PrimaryKey val itemId: String, // client-generated UUID
val tripId: String,
val title: String,
val sortKey: String, // fractional index
val startLocal: String, // what the person meant, e.g. "2027-06-10T10:00"
val startZoneId: String, // IANA id, e.g. "Europe/Lisbon"
val startInstant: Long, // epoch millis; a cache computed from the two fields above
val serverRev: Long, // last revision the server confirmed
val deletedAt: Long? = null, // tombstone: hidden in the UI, kept until the server confirms
@ColumnInfo(defaultValue = "0") val dirty: Boolean = false,
)
I show the entity itself to keep the snippet short. In a larger app, I would map it to a UI model. itemId is made on the device. So creating an item offline needs no round trip, and a retried create does no harm. The chat case does the same with clientId.
The entity stores what the person meant (startLocal plus startZoneId). startInstant is a cache that you compute again from them, for sorting and flight length. It is not the truth. I did not compile this version.
2. REST
GET /v1/trips/{id}/changes?cursor=<opaque> → { changes[], nextCursor, hasMore } or 410 (cursor too old)
GET /v1/trips/{id} → full snapshot + cursor (bootstrap and resync)
POST /v1/trips/{id}/ops { opId, ops[] } → per-op result: applied | conflict(field, serverValue) | rejected
How to read the snippet. Each block is one call: the method and path, then the headers, then the JSON body (the data the app sends) in braces. A line that starts with → is a reply from the server. Text after // is a comment. These are sketches for this guide, not a vendor API.
| Call | What it is for | When the app makes it |
|---|---|---|
GET /v1/trips/{id}/changes | Get the edits made by other people since the saved cursor. | On open, on pull to refresh, and after a push message. The client saves nextCursor and repeats while hasMore is true. |
410 reply on changes | The cursor is too old. The server no longer has those changes. | Fetch the full snapshot, replace the local copy, and start from the new cursor. |
GET /v1/trips/{id} | The full trip plus a cursor. | The first time a trip opens, and for a resync after a 410. |
POST /v1/trips/{id}/ops | Send the edits made on the phone, each with an opId. The server answers for each edit: applied, conflict or rejected. | When there is a network and the local queue has edits. A retry with the same opId changes nothing a second time. On conflict, merge using the server value. |
Every write carries an opId. So a retry after a lost response changes nothing on the server. The server picks the revision and the cursor. They are not the seq of the chat case.
A 410 on the changes call means the cursor is too old. The client then fetches the snapshot (section 7).
3. Merging edits: the rule
Two companions are on a plane. One renames "Lunch" to "Lunch at Time Out Market". The other changes the time of the same item and adds a note. Both edits must survive.
Whole-item last write wins loses one of them. The Android guide names last write wins as the simple option. It also says that conflict resolution often needs versioning, with the network as the source of truth. So the flow is:
- A local edit writes the value into Room. It also adds one
op_outboxrow for that field. The row carries thebaseRevthe person was looking at. PushChangesWorkerposts the waiting ops for the trip, in order.- The server applies an op if the field has not changed since
baseRev. If the field changed to another value, the server keeps its value and reports a conflict for that field. - The client clears the applied ops. For a conflict, it shows the server value and keeps the rejected value in view ("Alex changed this to ... Keep mine?").
- The next pull brings every accepted change, and revisions make all devices agree.
// Sketch of the server rule: reject only a field that changed since the editor's base revision
data class Field(val value: String?, val rev: Long)
data class Edit(val name: String, val value: String?, val baseRev: Long)
data class MergeResult(val fields: Map<String, Field>, val conflicts: List<String>)
fun mergeEdits(current: Map<String, Field>, edits: List<Edit>, newRev: Long): MergeResult {
val out = current.toMutableMap()
val conflicts = mutableListOf<String>()
for (e in edits) {
val cur = current[e.name]
if (cur != null && cur.rev > e.baseRev && cur.value != e.value) conflicts += e.name
else out[e.name] = Field(e.value, newRev)
}
return MergeResult(out, conflicts)
}
This code runs on the server in the real system. It is a sketch of the rule.
One case to handle: your own earlier edit. The sketch compares each edit's baseRev with the revision stored before the batch. Suppose one person edits the same field twice offline, and the two ops travel in two requests. The second op sees the revision made by the first op. It would look like a conflict with the person's own change. Two client rules fix this:
- Before sending, merge the waiting ops for one field into one op. Keep the first
baseRevand the last value. - When the server accepts an op, set the
baseRevof later waiting ops for that field to the new revision.
fun coalesce(ops: List<Edit>): List<Edit> =
ops.groupBy { it.name }.map { (_, same) ->
Edit(same.first().name, same.last().value, same.first().baseRev)
}
I did not compile this. Write the two-request test first: two edits to one field, sent in two requests, must give no conflict.
Per-field merge treats a field as one value. So two people typing in one long note still conflict. A CRDT (a data type that merges edits by itself) can merge that. But both platforms must then follow its protocol exactly and keep its history.
My position: per-field merge for structured fields, a text merge for the note only if the product needs it, and no CRDT for the whole trip. I have not checked any mobile CRDT library, so I do not recommend one.
Do not merge two edits to the same field by joining the text. That invents text nobody wrote. "Your change was not applied, reapply?" is cheap and honest.
4. Order keys
With integer positions, an insert at the top rewrites every row after it. Two offline inserts at position 3 also collide. Give each item a sortKey, a string that sorts between its neighbours. Sort by (sortKey, itemId). A move or an insert then writes one row.
The interview page sorts a day by time first. The key decides only the items with no time, and ties.
private const val DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
fun keyBetween(a: String?, b: String?): String {
require(a == null || b == null || a < b) { "a must sort before b" }
return mid(a ?: "", b)
}
// Keys never end in '0', so there is always room between two distinct keys.
private fun mid(a: String, b: String?): String {
if (b != null) {
var n = 0
while (n < b.length && (if (n < a.length) a[n] else '0') == b[n]) n++
if (n > 0) return b.substring(0, n) + mid(a.drop(n), b.drop(n))
}
val da = if (a.isEmpty()) 0 else DIGITS.indexOf(a[0])
val db = if (b == null) DIGITS.length else DIGITS.indexOf(b[0])
return when {
db - da > 1 -> DIGITS[(da + db + 1) / 2].toString()
b != null && b.length > 1 -> b.substring(0, 1)
else -> DIGITS[da] + mid(a.drop(1), null)
}
}
- Concurrent inserts can produce the same key. The
(sortKey, itemId)tie-break is the same on every device, so the order is the same everywhere. - Keys grow when people insert again and again at one spot. For human edits this is rare. Rebalancing a day rewrites many rows and can meet a concurrent move. I leave it as an open item.
- Runs of inserts at one spot can interleave with another person's run. I accept this.
5. Deletes and tombstones
If a delete removes the row, a companion who edited that item offline uploads it again on reconnect. The item comes back. So a delete is a write. Set deletedAt and a revision, sync it, and filter tombstones out of every UI query.
If one person deletes an item while another edits it offline, my rule is that the delete wins. The edit comes back as a conflict that the editor can restore ("This item was deleted. Restore it?"). Deleting someone's work silently is the worse failure.
The server cannot know whether a phone that was offline for months has seen the tombstone. So it keeps tombstones for a retention time. It answers an older cursor with a forced resync (section 7). Tie the retention to the offline gap you promise. I give no number, because no official page gives one.
Order keys need no tombstones. Only the change feed does.
6. Time zones
A trip crosses zones, so what does "10:00" mean? Store a local date and time plus an IANA zone ID such as Europe/Lisbon. Never store a fixed offset like +01:00, and never a display name. Apple says the same: values such as America/Los_Angeles are IDs, not names (TimeZone).
The instant is derived from those two values. An instant alone loses the place the user meant. Then the UI cannot show "10:00 in Lisbon" to a companion in New York.
data class ItineraryTime(val local: LocalDateTime, val zoneId: String) {
// The stored value is local + zoneId. The instant is derived from it.
val instant: Instant get() = local.atZone(ZoneId.of(zoneId)).toInstant()
}
fun flightDuration(dep: ItineraryTime, arr: ItineraryTime): Duration =
Duration.between(dep.instant, arr.instant)
The stored value is the local date and time plus the zone ID. The instant is computed from them each time, or cached in startInstant. If a zone rule changes, you recompute the cache and the local time stays what the person typed.
- Display in the item's own zone, with a switch for the viewer's zone.
- Duration is arithmetic on instants. Lisbon 10:00 to New York 13:00 on 10 June 2027 is eight hours with today's rules. Lisbon is UTC+1 and New York is UTC-4. Subtracting wall-clock times gives three.
- Group by the item's local date. For example, a 23:30 item in Tokyo belongs to that Tokyo day for every viewer.
- An unknown zone ID.
ZoneId.ofthrows for an ID that this phone does not know, for example a new ID on an old phone. Catch it and show the stored local time with the ID. The Swift model falls back to GMT. I did not compile this handling. - Take the zone from the place, not from the device. The device zone is wrong when you plan a trip from home.
- Gaps and overlaps. A local time may not exist (clocks go forward) or may happen twice (clocks go back).
ZonedDateTimemoves a time in a gap forward by the length of the gap. In an overlap, it keeps the earlier offset unless you ask for the later one (Java SE 17). - Rules change. A government can change a zone rule after you store an instant. RFC 9557 names the case of a future local time whose instant changes, and says it is outside its scope (RFC 9557). Android updates zone rules through a system module, and phones get an update at different times (Android). That is why the local value is the truth.
7. The sync cursor
Pull sync needs an answer to "what changed since I last looked". Use a server-ordered change log and an opaque cursor, a value that the app never reads.
- A steady order per trip. Every accepted op, tombstone and permission change goes into the log. The cursor means "the last change you have seen". The server can change its encoding, because the client never reads it.
- Never use device time as the cursor. A wrong clock or a late commit breaks "changes since my last sync time".
- Apply a page and its cursor in one Room transaction. If the process dies, you have both or neither. Pulling again does no harm, because applying by
(itemId, serverRev)ignores anything that is not newer. Your own pushed writes come back in the next pull and change nothing. - Put tombstones and permission changes in the log. Otherwise a pull never learns about them.
- Expired cursor. The server answers
410. The client fetches the snapshot and replaces the local copy. It keeps its waiting ops. A stalebaseRevthen goes through the normal per-field check. - Waiting edits survive a pull. A refresh that overwrites a row with an unsent edit makes the text jump back. Show the server value with the waiting ops from
op_outboxapplied on top. - A push is a hint. "Trip X changed" starts a pull. One pull recovers any number of missed hints.
An old standard, RFC 6578, has the same shape. It has an opaque token, a full list from an empty token, and an error for a token that is too old (RFC 6578).
8. Photos, roles and sharing
A photo is a separate upload from the item edit. A media row starts as QUEUED. The item points at it at once, with a local thumbnail. A unique UploadMediaWorker for each mediaId runs a resumable session. It saves confirmedOffset in Room. The mechanics are in photo and file sync.
After the upload is complete, the client calls the attach endpoint. Only then do companions see the photo. Say "shared" after that point, not before.
Photo location is a privacy choice. On Android 10 and later, apps cannot read it unless they hold the ACCESS_MEDIA_LOCATION permission (media). I have not checked what iOS does, and I do not promise that location is removed.
Roles are enforced on the server. A viewer's op must be rejected whatever the client sends. A queued op that gets 403 is marked rejected, and the text is kept. Removal arrives as a change in the log. The app deletes the local trip after it warns about unsent edits. It cannot reach a phone that never reconnects.
For invite links, verified App Links open the app directly on Android. On Android 15 and later, the system re-checks links in the background, and a change can take up to seven days to reach all phones (App Links). The page does not cover a phone without the app. The web page fallback is my design.
9. Scenarios and handling
| Scenario | Handling |
|---|---|
| Response lost after the server applied ops | Retry with the same opId; the server returns the first results |
| Same field edited on two phones | The server keeps its value and returns a conflict; the UI offers "keep mine" as a new op |
| Delete on one phone, edit on another | Tombstone with a revision; the edit comes back as a conflict with a restore action |
| Device offline longer than tombstone retention | 410 on the cursor; fetch the snapshot, keep waiting ops, check them again |
| Pull overwrites a waiting edit | Show the server value with op_outbox applied on top; no jump |
| Companion removed while offline | Queued ops get 403; keep the text, explain, delete local data after confirmation |
No polling loop. Pull on open, on foreground, when the network returns and on a push hint.
10. Platform limits
The limits that shaped the design, side by side. Each fact comes from a page I read, or is marked as my reading.
| Limit | Android | iOS | So the design changes by |
|---|---|---|---|
| Work that must survive a restart | WorkManager work persists across app restarts and reboots | No equivalent; the app drains its own outbox | The outbox is a table, and a drain runs on edit, foreground, network return and push |
| Background upload | Persistent WorkManager work; Android 14 adds user-initiated transfer jobs, and the page speaks of downloads | A background session supports download tasks and upload tasks from a file (not data tasks or in-memory uploads), and a rate limiter delays new background download tasks (uploads assumed) | Write the photo to a file, use one session, and save the offset |
| After the app is ended | Not covered here | The system relaunches the app if it ended it. I did not confirm what happens after a force-quit, so do not count on a relaunch | On launch, set a photo row to queued and ask the server for its offset |
| Retries | Result.retry() with exponential backoff, 30 s by default and 10 s at the least | No equivalent; the outbox decides | Retry short failures; stop on a permanent rejection |
| Photo location | Hidden on Android 10 and later unless the app holds a permission | Not checked | Treat location as a product choice; make no promise |
| Zone rule updates | Come through a system module at different times | TimeZone IDs are names of places; update timing not read | Store the local value and the zone ID |
| Invite links | Verified links open the app; re-checks on Android 15 take up to seven days | Not read in full | Link to a web page for people without the app |
11. How to build an offline-first travel plans app on iOS (Swift)
Same design, different primitives. SwiftData (iOS 17 and later) or Core Data (or GRDB) replaces Room. SwiftUI watches it with @Query. A background URLSession replaces the upload worker.
What really differs:
- You drain the outbox yourself. There is no WorkManager equivalent. Start a drain on edit, on foreground, on network return (
NWPathMonitor) and on push. If the user force-quits, do not count on a relaunch. Queued edits may wait for the next launch. I did not confirm this in the pages I read. The edits are in the database and the server ignores repeatedopIds, so nothing is lost. - The system owns background transfers. Apple's background
URLSessionruns in a separate process. It supports download tasks and upload tasks from a file. It does not support data tasks or uploads from memory, so write each photo to a file and useuploadTask(with:fromFile:). If the system ended the app, it relaunches the app. Create the session again with the same identifier. Use one session. Apple documents a growing delay for new background download tasks. I assume uploads match. BGProcessingTaskis a bonus, not a plan. It runs only when the device is idle, and it can be interrupted. It needs theprocessingbackground mode, the task identifier listed inBGTaskSchedulerPermittedIdentifiersin Info.plist, and a handler registered before launch finishes. SetrequiresNetworkConnectivity, and do the cheap work on launch and foreground.BGContinuedProcessingTask(iOS 26) starts in the foreground and may continue after. The person can cancel it, and the system can end it at once. Save the offset. The page I read does not name uploads.CKSyncEngine(iOS 17) syncs local records with CloudKit. It fits only when every companion uses Apple's cloud. A trip shared with Android phones needs your own server and outbox. That is my reading.- SwiftData upsert. Apple documents
@Attribute(.unique)as keeping a value unique across instances. Test upsert-on-save on your target OS before you rely on it.
@Model
final class ItineraryItem {
@Attribute(.unique) var itemId: String // client-generated UUID
var tripId: String
var title: String
var sortKey: String // fractional index
var startLocal: String // what the person meant, e.g. "2027-06-10T10:00"
var startZoneId: String // IANA id, e.g. "Europe/Lisbon"
var startInstant: Date // cache, computed from the two fields above
var serverRev: Int64
var deletedAt: Date? // tombstone
var dirty: Bool
init(itemId: String, tripId: String, title: String, sortKey: String,
startLocal: String, startZoneId: String, startInstant: Date) {
self.itemId = itemId; self.tripId = tripId; self.title = title; self.sortKey = sortKey
self.startLocal = startLocal; self.startZoneId = startZoneId; self.startInstant = startInstant
self.serverRev = 0; self.deletedAt = nil; self.dirty = true
}
var startZone: TimeZone { TimeZone(identifier: startZoneId) ?? .gmt }
}
The fractional-key logic and the merge rule are plain value code, and they port to Swift line by line. Port the unit test with them: random inserts stay sorted, strictly between their neighbours, and never end in the lowest digit.
12. More practice prompts
- How do you test this? (A fake server that drops, reorders and repeats requests. Kill the process in the middle of a push. Property-test the key function. Write the two-request test from section 3.)
- How would you add live presence? (A socket only while the trip is open, kept short-lived. The durable path stays the op log.)
- How would you add shared expenses? (Append-only entries, and a balance computed from them.)
- How would you add offline maps? (This is a download problem, not a conflict problem. Keep it apart from the edit path.)
- How would you add calendar export? (Export the local value with its zone ID.)
Further reading (official docs)
- The interview part of this case: scope, decisions, failures, follow-ups and levels
- Build an offline-first app (Android): write strategies, pull, push and hybrid sync, last write wins, queues
- Architecture recommendations (Android)
- Task scheduling and WorkManager (Android)
- Manage work (WorkManager): unique work and
ExistingWorkPolicy - User-initiated data transfer jobs (Android)
- Time zone rules (Android)
- Access media files and photo location (Android)
- Verify Android App Links
- ZonedDateTime (Java SE 17)
- TimeZone (Apple)
- Downloading files in the background (Apple): background sessions, file-based uploads, relaunch
- BGProcessingTask (Apple)
- BGProcessingTaskRequest (Apple)
- BGContinuedProcessingTask (Apple)
- Preserving your app's model data across launches (Apple)
- RFC 9557 and RFC 6578
- Offline-first hub on this site
- Related case studies: Chat app, Photo and file sync, Booking app
Words on this page (15)
- BGProcessingTask
- A kind of iOS background task for long work. The system decides when it runs, often when the phone is idle.
- CRDT
- A data type that merges edits from many devices by itself. Every device ends with the same result.
- Cursor
- A saved place in a list. The server gives it to the app, and the app sends it back to get the next part.
- Exponential backoff
- Waiting longer after each failure. For example, wait 1 second, then 2, then 4.
- Outbox
- A saved list of changes that the server has not confirmed yet. The app sends them later, even after it restarts.
- Polling
- Asking the server again and again if there is news. It costs battery and data.
- Room
- Android's library for the database on the phone. You use a DAO to read and write the data.
- Sequence number
- A number that grows by one with each message. It shows the order, and it shows a gap when a number is missing.
- Snapshot
- A copy of the data as it was at one moment. It is not a list of changes.
- Source of truth
- The one copy of the data that the app trusts. In these cases it is the database on the phone, and the screen only reads it.
- Stale data
- Saved data that may be out of date. The app should show how old it is, or refresh it.
- SwiftData
- Apple's library for saving data on an iPhone. It has the same role as Room on Android.
- Tombstone
- A row that says an item was deleted. The app keeps it for a while, so an old copy cannot bring the item back.
- Upsert
- A database step that inserts a row, or updates it if it already exists.
- WorkManager
- Android's tool for background work that must run later. The work survives when the app closes or the phone restarts.
Verification notes (last reviewed 14 Oct 2026)
What I checked.
- The Kotlin key, merge and time code ran on the JVM. 2,000 random inserts stayed sorted and unique. The merge keeps edits to different fields and flags the same field. Lisbon 10:00 to New York 13:00 is eight hours.
- An earlier version of the Room entity compiled. The Room compiler accepted the table, the index and the default value.
- An earlier version of the Swift model type-checked for iOS 17 and later. It was not run.
- Official docs read: Android offline-first, WorkManager, user-initiated transfers, zone rules, media location, App Links, Java ZonedDateTime, Apple background URLSession, BGProcessingTask, BGContinuedProcessingTask, TimeZone, RFC 9557 and RFC 6578.
What I did not verify.
- The changed entity (
startLocal), the changed time snippet, the Swift model change and thecoalescefunction were not compiled. - The "own earlier edit" case is my reading of the sketch. It is not tested.
- What iOS does after a force-quit, and photo location on iOS.
- No iOS engineer has reviewed this page.
My own design.
- Per-field merge, order keys, tombstone handling, the 410 resync and the cursor design. The official docs do not cover collaborative editing.
- Tombstone retention is a design choice. I give no number.
Questions or corrections?
Add them to the discussion thread for this case on GitHub. To post, you need a free GitHub account. What you write there is public and follows GitHub's terms. Good answers are added to this page.
Keep reading
Get the free one-page cheat sheet
One page: the five steps, a 45-minute time plan and two checklists. Print it or keep it on your phone.
We email you the cheat sheet after you confirm your address. You can also open it now from the Start here page. You also get a short email each week with a follow-up round, and a note when a new case is published. Unsubscribe any time. Privacy.