DEV Community

Cover image for How I Reached 90.64% Shared Code in Kotlin Multiplatform Across Android, iOS, Desktop, and LAN Sync
WolfOf420Stret
WolfOf420Stret

Posted on

How I Reached 90.64% Shared Code in Kotlin Multiplatform Across Android, iOS, Desktop, and LAN Sync

SnapLedger is a local-first receipt and expense tracker I built for the KotlinConf Student Coding Competition. It targets Android, iOS, and Desktop, with a standalone server and an embedded Desktop LAN Hub for synchronization. I measured the shared-code ratio with the repository’s own ./scripts/shared-code-ratio.sh: 7,396 shared production Kotlin lines out of 8,160 client lines, or 90.64%.

The high-level module layout is intentionally small:

:core                 pure domain logic
:app:shared           Compose Multiplatform app and data layer
:app:androidApp      Android shell
:app:desktopApp      Desktop JVM shell
:sync-host            embedded LAN sync engine
:server               standalone Ktor backend
Enter fullscreen mode Exit fullscreen mode

Module boundaries did most of the work

The biggest architectural decision was keeping :core free from Android and UI dependencies. That module contains domain models and deterministic logic such as SpendAnalytics, CSV generation, HTML report generation, receipt parsing, and Last-Write-Wins synchronization rules.

For example, SpendAnalytics computes the primary currency, totals, billable ratio, and category slices from ledger entries. HtmlReportExporter turns the same domain data into a self-contained, HTML-escaped report. Both are pure Kotlin, so their behavior and tests do not need platform forks.

This is the lesson I would emphasize: do not wait until the end of a project to separate domain logic from Compose and platform glue. Enforce the boundary at the Gradle module level on day one. A clean module dependency graph makes shared code the default instead of an extraction project you postpone until the deadline.

Receipt persistence and image decoding are real platform work

File I/O and image handling are where many KMP demos quietly become platform-specific—or leave one target stubbed. SnapLedger keeps the contract shared through ReceiptImageStore, then provides actual Android and iOS implementations. Android writes under the app’s private receipts directory with path-containment checks, symlink rejection, and atomic moves. iOS uses NSFileManager and atomic NSData writes in the documents directory.

The platform boundary for decoding is deliberately thin. Android uses BitmapFactory; Desktop and iOS use Skia’s Image.makeFromEncoded. Shared Compose code loads thumbnails off the main thread and applies a bounded preview size. FileKit 0.17.0 handles cross-platform file picking and export flows, while receipt storage remains behind the repository abstraction.

Local-first binary sync over LAN

I chose a Desktop LAN Hub instead of making a cloud backend mandatory. The result is a faster offline-first workflow with no cloud lock-in: the phone and Desktop can exchange ledger data directly on the local network.

A sync cycle has four phases. First, the client posts pending ledger entries and applies Last-Write-Wins reconciliation. Next, it best-effort uploads locally available receipt images with idempotent PUT requests. It then downloads missing images with GET. Finally, receipt-transfer failures remain isolated from a successful ledger sync and can be retried on the next cycle. The protocol also exposes a WebSocket event stream for live connection status.

That separation matters. A missing image should not roll back a valid ledger update or corrupt local state.

Guardrails against hackathon spaghetti

The quality gate runs Spotless, Detekt, tests, Kover verification, Desktop compilation, and an Android debug build. Detekt caps cyclomatic complexity at 10 and requires documentation for public APIs. A custom checkFileLength task rejects Kotlin files over 300 lines. The project also avoids unsafe nullable calls and keeps coverage thresholds enforced rather than lowering them to make CI pass.

The honest KMP lesson is that shared code is not achieved by hiding platform work. It comes from putting most business behavior in pure modules, isolating the unavoidable platform seams, and measuring the result with a reproducible definition.

Source: SnapLedger on GitHub

Top comments (4)

Collapse
 
gorkemkara profile image
Gorkem Kara •

LWW between a phone and a desktop hub, whose clock decides what last means tho? if updatedAt comes from the device a phone with a drifted clock can overwrite a newer edit and nobody notices. a sequence number assigned by the hub or a hybrid logical clock fixes that pretty cheap

Collapse
 
wolfof420street profile image
WolfOf420Stret •

Hey. Thanks for flagging the weak spot. I documented in SyncProtocol.md in the docs . Since Desktop is already the hub here, a hub-assigned monotonic sequence number (or a small HLC if I ever want true peer-to-peer between two phones) is actually super cheap to layer on top without changing the rest of the sync flow. Definitely one of the first things I'm swapping in today

Collapse
 
userxnom profile image
Abdullah Naseer •

The line I'd steal is "enforce the boundary at the Gradle module level on day one." Most KMP writeups show the shared percentage as a finish-line stat; yours reads like the percentage was a side effect of a rule you refused to break. The 300-line file cap is doing quiet work here too — small files push logic out of the UI layer and into the pure modules, which is exactly where shared code lives.

The receipt-transfer isolation is the other detail that shows this was actually run, not just architected: a missing image not rolling back a valid ledger update is the kind of failure separation you only add after losing data once.

One question on the LAN side: when the Desktop hub is off and the phone keeps editing for a day, how wide does the divergence window get before the next sync — do pending entries just queue up and reconcile cleanly, or is there a point where a long offline stretch makes the merge noticeably slower?

Collapse
 
wolfof420street profile image
WolfOf420Stret •

Hey. thanks for engaging with my content. !

To answer your question, For a day (or even a week) offline, everything just queues up in local SQLDelight as PENDING_SYNC (with deletes stored as tombstones) and reconciles in one SQLite transaction when the Desktop hub comes back online. For normal freelancer/small-business volumes (hundreds or a few thousand entries), the merge itself takes milliseconds over local Wi-Fi.