wrkm.app
Search
Mobile Development

Data-Layer Rethinking, Part 2: Offline-First Under Pressure

Data-Layer Rethinking, Part 2: Offline-First Under Pressure

Editor
Nov 22, 2026 · 22 min read
Data-Layer Rethinking, Part 2: Offline-First Under Pressure

What a self-driving car in a tunnel can teach us about offline-first Android appsPhoto by KS KYUNG on UnsplashOverviewThis article is the continuation of the Data-layer rethinking article where I walked through synchronization strategies for mobile software development. While that work mainly focuses on multiple external sources and synchronizing the data obtained from them, in this paper I describe the best approaches to storing data internally and using memory efficiently within highly limited boundaries. These articles are helpful for all mobile software engineers; however, I use Kotlin and all the examples mainly focus on Android, which should not prevent other mobile software engineers from understanding the ideas.The data may not only be tables in SQL-related DB but also huge files such as videos which are directly connected with that data, and that rich structure has to be synchronized with the Network. Furthermore, sometimes conflicts between clients may take place, especially if they are reaching the same context — this issue is also considered, and it is clearly explained how to handle it. But what happens if the data is being expanded rapidly and dramatically so memory is low? Obviously, we can upload them to the network and clean local storage, which will free on-device memory. But if you don’t have a stable connection for a while — how to handle such a situation at that point? Another question comes to my mind: how exactly to synchronize one resource if several clients update it simultaneously?All of these questions are explored in this article by considering a practical task which is very real for mobile software development.The challengeLet’s imagine a car that is controlled by our application and is self-driving. Since there is no driver, our north star is ensuring safety for our passengers. The controlling application should track everything — from commonplace opening of electric windows and route coordinates to emergency situations, such as accidents or unexpected and sharp stops. Furthermore, usually such vehicles involve video recordings, storing and uploading them if/when a network is available. Just imagine how many types of data we have to structure, synchronize, and store efficiently. On the other hand, the vehicle is not static and always in motion. It goes through a forest, sometimes it’s inside a tunnel — or anywhere else without a stable connection, which requires us to resolve a variety of tasks. And imagine it puts all the events into the local DB with complex relations between its tables, bound with video files, which complicates the situation because the data is sensitive. The situation becomes even harder when the network is unstable and we are just collecting data.Photo by Leo_Visions on UnsplashBefore delving into the most interesting (and challenging) part of this article let’s clearly explore the decomposed and split tasks of the main headache:Complex data trackingNowadays, a vehicle is a highly technological device, with its main “computer” running a special Operating System, which controls a variety of technical things. Let’s consider a very practical case here when we need to track the locations the car goes through, the passengers it picks up, and potential dangerous situations. Obviously, the car records various types of videos which also must be uploaded, however this point will be emphasized a bit later. Just imagine what a rich structure and how many entities we have now: a Car (1) which has Rides (2) which have at least one Passenger (3) and a list of Videos (4), Locations (5), possible Dangerous Situations (6). Every mentioned entity has a dozen other additional ones that are closely related as well.Tracking everything in one shot is an unbearable headache. See what a rich SQL construction we will have, what complexity it will take to construct such a structure, and what a heavy query it will be to upload those things to the network.Intensive data handlingMost of us — mobile software engineers — deal with a Location Provider / GPS API which fires up to 10 updates per second even though we’re standing still and the position is static. While this issue can be debounced by speed checking, the amount of coordinates still increases dramatically. Imagine the vehicle goes through a very long tunnel without a stable connection while the GPS keeps emitting coordinates to store and handle. In that raw case the memory will run out rapidly and the application will fail at its core value. Which approach allows us to save and synchronize them efficiently, both locally and remotely? I will demonstrate the most beautiful pattern to handle it below.Video records uploadWhile a vehicle is in motion we need to record everything — from objects outside the car on a street (from different perspectives and in 3D) to internal recordings for passengers’ safety. Police may request those records to investigate accidents, or the support team can analyze passengers’ behaviours. In the meantime, we work in the same environment — limited memory, unstable network connection, and the requirement of Back-end synchronization.The first huge challenge is to come up with a mechanism to smoothly upload when the connection is back after a long break. Secondly, we need to build the most efficient approach to store that massive set of videos, binding them to the DB.The Backseat Playlist ConflictNot all synchronization goes through the Back-end — devices inside the car sync with each other too. Let’s consider another example where there are two passengers in the car sharing one playlist [A, B, C]. One passenger moves track C to the top through the car-internal tablet — [C, A, B], while another passenger simultaneously excludes track B using their personal phone — [A, C]. At the same time, the car went into a tunnel and the phone, synced through the cloud, lost its connection. What happens next when the connection is back? Depending on the approach, the final playlist may turn out to be [C, A, B], [A, C] or even [C, B], while both passengers expect [C, A]. The question here is to find the most optimal solution which will allow us to resolve the conflict.The approachLet’s consider this DB structure and a naive approach to the synchronization of the data. We have already seen it above; this illustration depicts the entities’ relationships.DB schema of a self-driving carLet’s write a naive solution which covers synchronizing all the local data structure (including video-files) with the Back-end side when the Network is on. The most appropriate component to do it is a Worker in the Android ecosystem, which allows us to do its work under a condition (e.g. when the connection is available) and in the doWork() method we can deliver all the necessary data — see the Worker snippet. Another pillar of the mechanism is constructing the entire object from all the tables of the DB (see the SQL query snippet).Snippet 1. The naive worker: sync everything in one gooverride suspend fun doWork(): Result = try { // ❌ P1 — no delta. Every sync reads and sends everything since the last successful one. // Offline for hours = every retry re-sends the whole growing backlog → quadratic traffic. val payload: List = dao.getAllCars().map { car -> // ❌ P2 + P3 — a million flat rows in memory for a single ride… val rows = dao.getEverythingForCar(car.id) // …only to collapse them back with distinctBy, another pass over all of them. CarDto(car.id, car.vin, rows.groupIntoRides()) } // ❌ P3 — the whole object graph AND its JSON string live in the heap at the same time. val json = Json.encodeToString(payload) // ❌ P5 — one giant request. The car enters a tunnel at 80% → exception → retry from 0%. // The server may have already persisted part of it → duplicates (no idempotency keys). api.uploadEverything(json.toRequestBody("application/json".toMediaType())) // ❌ P7 — videos go in the same pass, one by one, read fully into memory. // A 500 MB cabin recording = OutOfMemoryError. And a 10-minute upload of a street video // blocks the next sync, including fresh dangerous situations. payload.flatMap { it.rides }.flatMap { it.videos }.forEach { video -> val bytes = File(video.localPath).readBytes() api.uploadVideo(video.id, bytes.toRequestBody("video/mp4".toMediaType())) } // ❌ P4 + P6 — see NaiveSyncDao.wipeEverything(): rows written in the meantime are lost. // ❌ P7 — rows are deleted, but the .mp4 files stay on disk forever → storage still runs out. dao.wipeEverything() Result.success()} catch (e: Exception) { // ❌ P5 — no checkpoint, no partial progress: the next attempt starts from scratch. Result.retry()}Snippet 2. One query to fetch the entire car// ❌ 2 passengers × 36 000 locations × 5 videos × 3 situations = 1 080 000 rows for ONE ride@Query(""" SELECT r., p., l., v., s.* FROM rides r LEFT JOIN ride_passengers rp ON rp.ride_id = r.id LEFT JOIN passengers p ON p.id = rp.passenger_id LEFT JOIN locations l ON l.ride_id = r.id LEFT JOIN videos v ON v.ride_id = r.id LEFT JOIN dangerous_situations s ON s.ride_id = r.id WHERE r.car_id = :carId""")suspend fun getEverythingForCar(carId: String): ListSnippet 3. Cleanup after upload// ❌ "Uploaded? Then delete everything."// Rows written between the SELECT and this DELETE were never sent — and now they're gone.// The active ride is deleted too, so every next GPS insert fails with an FK violation.@Transactionopen suspend fun wipeEverything() { deleteVideos() deleteSituations() deleteLocations() deleteRidePassengers() deleteRides()}And this is how the data gets into the database in the first place:Snippet 4. Where the data comes from: GPS collection// ❌ "More data is better": 10 Hz, no minimum distanceval request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 100L) .setMinUpdateDistanceMeters(0f) .build()override fun onLocationResult(result: LocationResult) { result.locations.forEach { location -> // ❌ One point = one transaction = one fsync, 10 times per second. // A car parked for an hour still writes 36 000 rows. scope.launch(Dispatchers.IO) { dao.insertLocation(location.toEntity(rideId)) } }}What goes wrongTable 1. Weaknesses of the naive approach and their consequencesThe naive approach fails on every front that matters for an offline-first car. It sends too much, holds too much in memory, loses data written during sync, and has no way to resume after a dropped connection. Notably, none of these problems come from bad code — each snippet looks reasonable on its own. They come from the model itself: treating synchronization as “take a snapshot of the database and ship it”.All these weaknesses hint at a different model. Instead of asking “what is in the database now?”, we can record “what has changed?” — an append-only journal of events, each self-contained and uniquely identified. Such a journal gives us delta sync, ordering, idempotent retries and visible deletions almost for free. Locations, the heaviest stream by far, get their own treatment on top of it: filtering and batching on write, then progressive compaction when storage runs low. Let’s start with the journal itself — the tracking table.Tracking tableThe tracking table saves all the events we save locally — besides saving them into their own tables in the DB, there is an additional one which duplicates them and denormalizes the structure. Instead of creating complex JOIN-related queries looking for and constructing complex objects, we just access them from the one table in one shot. Table 2 represents the necessary data: id identifies an entry, event_id allows us to keep the events idempotent, entity_type and entity_id bind the entry to its real table in the DB; op is a type of intent (see Table 3 with other examples of operation types); payload is a self-contained JSON snapshot of the data (shortened in the table) — we can send it without any JOINs; priority points out the order of handling the operations (e.g. dangerous situations DANGEROUS_SITUATION must be handled first of all); and created_at is the time of the event registration.Table 2. Proposed tracking tableTable 3. Other operation types and when to use themEntity and DAOenum class EntityType(val priority: Int) { DANGEROUS_SITUATION(0), // safety first RIDE(1), RIDE_PASSENGER(1), PASSENGER(1), VIDEO_META(1), LOCATION(2), // the noisiest stream: one event per GPS point (for now)}enum class Op { UPSERT, DELETE }@Entity( tableName = "sync_events", indices = [ Index(value = ["priority", "id"]), // drives the "next page" query Index(value = ["event_id"], unique = true), // ack lookups ],)data class SyncEventEntity( // Local order of events: ties within the same priority are sent oldest first. @PrimaryKey(autoGenerate = true) val id: Long = 0, // Global idempotency key: the server ignores an event it has already applied. @ColumnInfo(name = "event_id") val eventId: String = UUID.randomUUID().toString(), @ColumnInfo(name = "entity_type") val entityType: EntityType, @ColumnInfo(name = "entity_id") val entityId: String, val op: Op, // Self-contained JSON snapshot: no JOINs needed to send it. Null for DELETE (tombstone). val payload: String?, val priority: Int = entityType.priority, @ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis(),)@Daointerface SyncJournalDao { // O(page · log N) thanks to the (priority, id) index — no full scans, no JOINs. @Query("SELECT * FROM sync_events ORDER BY priority, id LIMIT :limit") suspend fun nextPage(limit: Int): List // Only what the server confirmed — events appended during the upload stay untouched. @Query("DELETE FROM sync_events WHERE event_id IN (:eventIds)") suspend fun deleteAcknowledged(eventIds: List)}The main rule of the journal: events are written in the same transaction as domain data. If a journal record is not saved, other data is not saved either and vice versa. Here is a sample for a dangerous situation and the deletion of a passenger:DAO@Daoabstract class RideRecorderDao { @Insert abstract suspend fun insertSituation(situation: DangerousSituationEntity) @Query("DELETE FROM passengers WHERE id = :id") abstract suspend fun deletePassenger(id: String) @Insert abstract suspend fun appendEvent(event: SyncEventEntity) @Transaction open suspend fun recordDangerousSituation(situation: DangerousSituationEntity, lat: Double, lng: Double) { insertSituation(situation) appendEvent( SyncEventEntity( entityType = EntityType.DANGEROUS_SITUATION, entityId = situation.id, op = Op.UPSERT, payload = Json.encodeToString(situation.toDto(lat = lat, lng = lng)), // denormalized ) ) } @Transaction open suspend fun erasePassenger(id: String) { deletePassenger(id) appendEvent(SyncEventEntity(entityType = EntityType.PASSENGER, entityId = id, op = Op.DELETE, payload = null)) }}Workerinterface SyncApi { // The server applies events idempotently by eventId and returns every eventId it now has, // including ones it had already seen in a previous, interrupted attempt. @POST("sync/events") suspend fun push(@Body request: SyncRequestDto): SyncAckDto}@Serializable data class SyncRequestDto(val events: List)@Serializable data class SyncEventDto( val eventId: String, val entityType: String, val entityId: String, val op: String, val payload: JsonElement?, val createdAt: Long,)@Serializable data class SyncAckDto(val acknowledged: List)class JournalSyncWorker( context: Context, params: WorkerParameters, private val journal: SyncJournalDao, private val api: SyncApi,) : CoroutineWorker(context, params) { override suspend fun doWork(): Result { while (!isStopped) { // Only one small page lives in memory at a time. val page = journal.nextPage(limit = PAGE_SIZE) if (page.isEmpty()) return Result.success() val ack = try { api.push(SyncRequestDto(page.map { it.toDto() })) } catch (e: IOException) { // Tunnel: everything acknowledged so far is already gone from the journal, // the retry continues from this page, not from 0%. return Result.retry() } journal.deleteAcknowledged(ack.acknowledged) } return Result.retry() } companion object { private const val PAGE_SIZE = 500 // events per request; a single location event is ~150 bytes fun enqueue(context: Context) { val request = OneTimeWorkRequestBuilder() .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) // don't even start in a tunnel .build() ) .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS) .build() // KEEP: called after every journal write; a running sync will pick new events up anyway. WorkManager.getInstance(context) .enqueueUniqueWork("journal-sync", ExistingWorkPolicy.KEEP, request) } }}In this worker, we’ve implemented page-based uploads. The worker takes 500 events from the journal, sends them in one request and then removes the accepted ones. At the same time, the data remains the same: every point remains a separate intent. This is a transport mechanism.Batching the data itself is a different story, and we’ll get to it in the next section.Fewer rows, smaller rows: batching and averaging locationsAnother issue here we are going to resolve is saving memory space and using it efficiently in the limited environment. We’ve already considered a situation when the vehicle is stuck with the network off. We still have to record all the events, but the memory space is not infinite. However, what if we did not record everything and skipped those events which make sense to skip? A good example of such events are locations — they are monotonic, measurable, and predictable. There is no sense to record locations with poor accuracy, or to record them at all if we don’t move while waiting for something — such points can be filtered out right away. The rest can be grouped: instead of writing 10 separate records per second, we can collect the points for a while and write them as one record. That process is named batching.An additional optimization may be averaging the values of the locations. If the system “understands” that memory space is going to run out soon, it can start the process of multi-staged averaging of the data. The process involves running several steps and calculating the average coordinates of the locations within particular time windows of a batch. It will allow us to compress the data while keeping the route consistent.Let’s consider the following sample which illustrates the pattern.Record Batching. This is the improved version of the naive onLocationResult:class BatchingLocationCollector( private val recorder: RideRecorderDao, private val compactor: LocationCompactor, private val scope: CoroutineScope, private val rideId: String,) { private val incoming = Channel(Channel.UNLIMITED) val callback = object : LocationCallback() { override fun onLocationResult(result: LocationResult) { // ✅ No DB work in the callback: just hand points over to a single consumer. result.locations.forEach { incoming.trySend(it) } } } fun start() = scope.launch(Dispatchers.IO) { val buffer = mutableListOf() var lastKept: Location? = null for (location in incoming) { // ✅ Filter on write: drop inaccurate fixes and parked-car jitter. if (!location.isUseful(lastKept)) continue lastKept = location buffer += GeoPoint(location.latitude, location.longitude, location.speed, location.time) // ✅ One transaction and one journal event per 30 seconds, not per point. if (buffer.last().t - buffer.first().t >= BATCH_WINDOW_MS) { recorder.recordLocationBatch(rideId, buffer.toList()) buffer.clear() compactor.compactIfNeeded() } } if (buffer.isNotEmpty()) recorder.recordLocationBatch(rideId, buffer.toList()) // flush on stop } fun stop() = incoming.close() private fun Location.isUseful(previous: Location?): Boolean = accuracy <= MAX_ACCURACY_M && (previous == null || distanceTo(previous) >= MIN_DISTANCE_M) private companion object { const val BATCH_WINDOW_MS = 30_000L const val MAX_ACCURACY_M = 20f const val MIN_DISTANCE_M = 1f // at 45 km/h the car moves 1.25 m per 100 ms, so motion is kept }}The frequency of GPS remains 10 Hz. Raw resolution is needed for protected windows around dangerous situations, so compression happens later and only if additional memory space is required.2. Averagingfun List.averaged(windowMs: Long): List = groupBy { it.t / windowMs }.values.map { window -> GeoPoint( lat = window.map { it.lat }.average(), lng = window.map { it.lng }.average(), speed = window.map { it.speed }.average().toFloat(), t = window.first().t, ) }3. Staged compressionenum class CompactionLevel(val number: Int, val windowMs: Long) { ONE_SECOND(1, 1_000), FIVE_SECONDS(2, 5_000), THIRTY_SECONDS(3, 30_000),}class LocationCompactor( private val journal: SyncJournalDao, private val situations: SituationDao, private val pressure: StoragePressure,) { suspend fun compactIfNeeded() { // ✅ Gentle first: go to the next level only if the previous one wasn't enough. for (level in CompactionLevel.entries) { if (!pressure.isHigh()) return compactTo(level) } } private suspend fun compactTo(level: CompactionLevel) { var afterId = 0L while (pressure.isHigh()) { // Oldest unsent batches first: the freshest data keeps its full resolution longest. val page = journal.locationBatchesBelow(level.number, afterId, limit = 100) if (page.isEmpty()) return afterId = page.last().id journal.update(page.mapNotNull { it.compactedTo(level) }) } } private suspend fun SyncEventEntity.compactedTo(level: CompactionLevel): SyncEventEntity? { val batch = Json.decodeFromString(payload ?: return null) if (isProtected(batch)) return null // ✅ Same eventId: it's still "the same 30 seconds", just at a lower resolution. // If the raw version was already applied by the server, it simply deduplicates this one. return copy( payload = Json.encodeToString(batch.copy(points = batch.points.averaged(level.windowMs))), compactionLevel = level.number, ) } // ✅ Never compact the track around a dangerous situation — that's evidence. private suspend fun isProtected(batch: LocationBatchPayload): Boolean = situations.occurredAt(batch.rideId).any { t -> t + PROTECTED_WINDOW_MS >= batch.from && t - PROTECTED_WINDOW_MS <= batch.to } private companion object { const val PROTECTED_WINDOW_MS = 10_000L // e.g. ±10 s; tune together with the safety team }}The storage check — SUM(LENGTH(payload)) over the journal — is a full pass, but after batching it has hundreds of records instead of tens of thousands, which makes the query cheap.Table 4, Batched dataThe contrast with the previous table: the same 42-minute trip finishes on id 91 instead of 25 104.What does every step give us on a one-hour trip? These are estimated values with ~40 bytes per point inside a batch and ~150 bytes per separate event:Table 5. What each compaction level saves per hour of drivingBatching itself reduces the size approximately 4 times: JSON keys, UUIDs, and service fields on every point disappear. At the same time, the amount of rows reduces by 300 times. Every next step of compression saves another order of magnitude.One copy of locations. recordLocationBatch records only into the journal, but not into the locations table. Otherwise, the heaviest stream would be saved twice. The locations table remains a sliding window of a few minutes for the vehicle’s needs, while the history is saved in the journal until it’s gone to the server.A batch window — maximum loss when the process dies. 30 seconds may be lost from the memory upon a crash. It makes sense to reduce the window down to 5–10 seconds for a self-driving car: the row count increases, but there are still orders of magnitude fewer rows than 36 000.Averaging cuts corners. On a turn, the midpoint lies within the arc. For short windows, it’s a matter of metres, for 30-second ones it’s noticeable. If the shape is important, instead of rough averaging on the third stage it’s better off to apply a simplification algorithm like Douglas–Peucker: it keeps turns and throws out points on straight segments.SQLite itself doesn’t return space to the system. After compression, freed pages are recycled for new data, therefore the file stops growing. In order to return the space, auto_vacuum = INCREMENTAL has to be applied and PRAGMA incremental_vacuum run periodically.Moving gigabytes through a tunnel: resumable video uploadsAnother issue is to upload videos — in fact heavy files whose uploading process takes time. Just imagine how long uploading a 500MB file takes and how many resources it requires. Obviously, we can start the work in the background, but how to handle situations involving disconnections from the network? How to resume uploading when the Network is back? And finally, how to access videos efficiently if the DB is as complex as we considered earlier?Let’s apply the same pattern which we’ve already explored above — a separate log table + a Worker which handles that. The journal has VIDEO_META, so the server knows about the video right away, while the file itself lives by the following principles:Own worker with its own state table. Video upload doesn’t block the journal, and the journal doesn’t block the video.Uploading by chunks with resuming. The file goes in 8MB chunks. In a tunnel, when the Network is broken, the uploading process continues from the latest chunk accepted by the server, not from scratch. This process looks like tus or S3 multipart upload, so any Backend with the same semantics is appropriate.Reading from a disk as a stream. The maximum buffer is 64KB, not 500MB as it is with readBytes().Two types of priorities. Videos bound to dangerous situations are uploaded right away through LTE — others are waiting for Wi-Fi.Table 6. The video_uploads table: one finished, one interrupted, two waiting for Wi-Fiv-5c is uploaded, the local file has already been removed, storage space is freed.v-5d uploading process was broken in a tunnel at 312 MB and it will proceed from that point. The upload session (upload_url) is stored in the DB and survives a restart of the app.v-61 and v-62 — normal records from cameras without incidents, they are waiting for an unmetered network.DAO@Daointerface VideoUploadDao { @Query( """ SELECT * FROM video_uploads WHERE priority = :priority AND state != 'UPLOADED' ORDER BY created_at LIMIT 1 """ ) suspend fun next(priority: Int): VideoUploadEntity? @Query("UPDATE video_uploads SET upload_url = :url, state = 'UPLOADING' WHERE video_id = :videoId") suspend fun startSession(videoId: String, url: String) @Query("UPDATE video_uploads SET uploaded_bytes = :bytes WHERE video_id = :videoId") suspend fun saveProgress(videoId: String, bytes: Long) @Query("UPDATE video_uploads SET state = 'UPLOADED' WHERE video_id = :videoId") suspend fun markUploaded(videoId: String)}APIinterface VideoUploadApi { // Creates an upload session and returns its URL. @POST("videos/{id}/uploads") suspend fun createSession(@Path("id") videoId: String, @Body request: CreateUploadDto): UploadSessionDto // How many bytes the server actually has — returned in the Upload-Offset header. @HEAD suspend fun offset(@Url uploadUrl: String): Response // Appends a chunk at the given offset; the response carries the new Upload-Offset. @PATCH suspend fun appendChunk( @Url uploadUrl: String, @Header("Upload-Offset") offset: Long, @Body chunk: RequestBody, ): Response // The server verifies the sha256 of the assembled file and finalizes the video. @POST suspend fun complete(@Url completeUrl: String): Response}complete expects a separate completeUrl from the response on session creation. That way a client doesn’t build the URL manually, while the server itself decides how its links work.Workerclass VideoUploadWorker( context: Context, params: WorkerParameters, private val uploads: VideoUploadDao, private val api: VideoUploadApi,) : CoroutineWorker(context, params) { private val priority = inputData.getInt(KEY_PRIORITY, UploadPriority.REGULAR) override suspend fun doWork(): Result { // A 500 MB upload easily outlives the 10-minute limit of a regular worker. setForeground(createForegroundInfo()) while (!isStopped) { val video = uploads.next(priority) ?: return Result.success() try { upload(video) } catch (e: IOException) { // Tunnel: every confirmed chunk is already on the server, // the retry continues from there instead of starting from 0%. return Result.retry() } } return Result.retry() } private suspend fun upload(video: VideoUploadEntity) { val file = File(video.localPath) val session = if (video.uploadUrl == null) { api.createSession(video.videoId, CreateUploadDto(video.sizeBytes, video.checksum)) .also { uploads.startSession(video.videoId, it.uploadUrl) } } else { null } val uploadUrl = session?.uploadUrl ?: video.uploadUrl!! // Ask the server, not the local DB: the last chunk may have arrived // even if the response was lost in the tunnel. var offset = api.offset(uploadUrl).headers()["Upload-Offset"]?.toLong() ?: 0L while (offset < video.sizeBytes) { if (isStopped) return val length = minOf(CHUNK_SIZE, video.sizeBytes - offset) val response = api.appendChunk(uploadUrl, offset, FileChunkBody(file, offset, length)) if (!response.isSuccessful) throw IOException("Chunk rejected: HTTP ${response.code()}") offset = response.headers()["Upload-Offset"]!!.toLong() uploads.saveProgress(video.videoId, offset) } val completeUrl = session?.completeUrl ?: "$uploadUrl/complete" api.complete(completeUrl) uploads.markUploaded(video.videoId) file.delete() // ✅ storage is actually freed only after the server confirmed the whole file } companion object { private const val KEY_PRIORITY = "priority" private const val CHUNK_SIZE = 8L * 1024 * 1024 // a dropped chunk costs at most 8 MB of re-upload fun enqueue(context: Context) { val workManager = WorkManager.getInstance(context) // Incident footage: any connection, right now. workManager.enqueueUniqueWork( "video-upload-incident", ExistingWorkPolicy.KEEP, request(UploadPriority.INCIDENT, NetworkType.CONNECTED), ) // Routine footage: only on unmetered Wi-Fi, e.g. overnight at the depot. workManager.enqueueUniqueWork( "video-upload-regular", ExistingWorkPolicy.KEEP, request(UploadPriority.REGULAR, NetworkType.UNMETERED), ) } private fun request(priority: Int, network: NetworkType) = OneTimeWorkRequestBuilder() .setInputData(workDataOf(KEY_PRIORITY to priority)) .setConstraints(Constraints.Builder().setRequiredNetworkType(network).build()) .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) .build() }}Foreground and Android limits. The long-running uploading process requires setForeground() with FOREGROUND_SERVICE_TYPE_DATA_SYNC and the necessary permission in the Manifest. On Android 15 dataSync has a limit of around 6 hours per day. The rules may differ on vehicles with Android Automotive — depending on a vendor.Chunk size — a tradeoff. A small chunk reduces repeated uploading after a break but increases overhead. 4–8 MB is a balanced tradeoff, while S3 multipart’s minimal part is 5 MB (the last part is the exception).Sessions expiring. If a car was offline for days, the server may return 404 to an old upload_url. In this case, the session must be cleared and restarted.Low storage: the dashcam principle. If the disk is running out while Wi-Fi is unavailable, usual videos (REGULAR) may be removed starting from the oldest ones — the same way it works on dashcams. Videos with INCIDENT are never removed.Orphaned files. If a process dies between markUploaded() and file.delete(), the file remains on a disk. This is closed by a periodic cleaning process: deleting the files of all the rows with status UPLOADED.Two passengers, one playlist: conflict-free merging with CRDTsLet’s consider the task we’ve described above. A common playlist in a car is [A, B, C]. The connection between a smartphone and a tablet was broken and passengers act simultaneously:Passenger 1 (tablet) moves C to the top: [C, A, B].Passenger 2 (smartphone) removes B: [A, C].The expected result where both intents are saved: [C, A].What the naive approaches lead to:Table 7. Why naive merging breaks the playlist (expected: [C, A])The second row is the classic reason why OT and CRDT exist: operations bound to positions break when the positions move.Solution: CRDTOT (Operational Transformation, like in Google Docs) has a drawback: it requires a central server to order operations. There might not be one in a car, and a tablet and a phone may have no connection. CRDT requires no coordination: each device edits its own replica, and when they meet, the replicas merge deterministically, yielding the exact same result across all devices.For a playlist, a simple schema is enough:each entry has a unique ID rather than an index;position is a fractional number instead of a list index, so reordering only updates the position of a single entry;deletion is a flag (tombstone) rather than a physical removal;each field merges using a last-writer-wins rule with logical clocks.CRDT mechanism/** A register that merges by "the latest write wins", deterministic on every device. */@Serializabledata class Lww(val value: T, val clock: Long, val replica: String) { fun merge(other: Lww): Lww = if (clock > other.clock || (clock == other.clock && replica > other.replica)) this else other}@Serializabledata class PlaylistEntry( val entryId: String, // unique per insertion: the same song can be added twice val trackId: String, val position: Lww, // fractional index: moving C before A = 0.5 between nothing and 1.0 val removed: Lww, // tombstone instead of deletion)typealias Playlist = Map<String, PlaylistEntry>// Commutative, associative, idempotent: order and duplicates of syncs don't matter.fun Playlist.merge(other: Playlist): Playlist = (keys + other.keys).associateWith { id -> val mine = this[id] val theirs = other[id] when { mine == null -> theirs!! theirs == null -> mine else -> mine.copy( position = mine.position.merge(theirs.position), removed = mine.removed.merge(theirs.removed), ) } }fun Playlist.visibleTracks(): List = values.filterNot { it.removed.value } .sortedWith(compareBy({ it.position.value }, { it.entryId })) .map { it.trackId }How this resolves the conflictTable 8. How the CRDT merge resolves the conflictMoving C to the front only needs a position smaller than A’s: 0.5. A and B keep their positions untouched — that’s what makes concurrent edits independent. The result of visibleTracks() is [C, A] on both devices, regardless of the order in which they sync. The changes do not conflict because they touch different fields of different entries.If passengers edit the same field (both move C to different positions), the write with the higher clock wins. The losing change is dropped, but the result is identical across all devices and the playlist never breaks. If the clock values are equal, replica acts as a tie-breaker, so a draw is impossible.A few things to keep in mind before shipping it:Use logical clocks, not wall time. The tablet’s and the phone’s clocks can drift by minutes. A Lamport or hybrid logical clock solves it: every device takes max(own, seen) + 1.Sending the whole state is fine here. It doesn’t contradict the naive-sync section: a playlist is tiny and the merge is idempotent, so retries and duplicates are harmless. For 36,000 GPS points it wouldn’t work; for 20 tracks it does.Use string positions in production. Moving a track to either end is unlimited: just subtract or add 1. But inserting repeatedly into the same gap halves the distance each time, and a Double runs out of precision after ~50 such insertions. String-based fractional indexing grows the key instead and has no such limit.Tombstones accumulate. For a playlist that lives for one ride, they can simply be dropped when the ride ends.Internal sync doesn’t need the internet. If the devices talk through the car’s head unit over local Wi-Fi or Bluetooth, the tunnel doesn’t affect them. Concurrent edits still happen whenever the devices lose sight of each other for a while — and that’s exactly the case CRDTs are built for.With a few dozen lines of code, two passengers can edit the same playlist offline and always end up with the same result — no server, no locks, no lost changes.ConclusionWe’ve just explored 4 main cases relevant for self-driving cars and capturing the most common offline-first tasks for systems with limited resources — such as mobile software, using Android as an example.We walked through not only how to use SQL-related data efficiently, but also how to synchronize the heavy files related to it. CRDT mechanics were demonstrated and compared with OT, showing how they can be used and which specific tasks the patterns allow us to resolve. Also, we’ve clearly answered how to batch data efficiently if it keeps growing while working with limited resources. Additionally, we’ve managed to handle the synchronization process while facing network connection issues.Let’s go back to the questions we started with. What happens when data grows rapidly and memory runs low, while the connection is gone for a while? The answer turned out to be not a single trick but a combination of them: an append-only journal that remembers what has changed instead of re-sending what is there, batching on write, and progressive compaction that trades resolution for space only when it really has to. How do we upload huge files bound to that data? Separately from it — chunk by chunk, resuming from the last byte the server confirmed, so that a tunnel costs us seconds of re-upload rather than the whole file. And how do we synchronize one resource that several clients update simultaneously? By changing the shape of the data itself, so that merging becomes deterministic and no change gets lost.Throughout all of these solutions, our north star stayed the same — the safety of passengers. That’s why the track around a dangerous situation is never compacted, incident footage goes first over any available network, and local data is deleted only after the server has confirmed it. In a system where data may become evidence, “eventually consistent” must never mean “eventually lost”.Perhaps the most important takeaway is a shift in mindset: being offline is not an edge case to handle in a catch block, but the normal state of a mobile device. Although every example here is written in Kotlin for Android, none of these ideas are tied to a platform or to cars — the same patterns apply to delivery and courier apps, field-service tools, health trackers, or any IoT device that collects data faster than it can send it. Together with the previous article, Data-layer rethinking, which focused on synchronizing data from multiple external sources, this one completes the picture from the inside: how to store, compress and deliver your own data when resources are limited and the network can’t be trusted.I’d love to hear how you approach offline-first in your projects — share your experience in the comments.ReferencesData-layer rethinking — the previous article of this seriesRamer–Douglas–Peucker algorithm — WikipediaDouglas–Peucker algorithm — interactive playgroundtus — Resumable Upload Protocol (specification)Amazon S3 — Uploading objects using multipart uploadDaniel Spiewak — Understanding and Applying Operational TransformationOperational transformation — WikipediaSun et al. — Real Differences between OT and CRDT (arXiv)Data-Layer Rethinking, Part 2: Offline-First Under Pressure was originally published in ProAndroidDev on Medium, where people are continuing the conversation by highlighting and responding to this story.

Kaynak: Siarhei Krupenich

#Android#Kotlin
Share

From other categories