DEV Community

Shiva Thapa
Shiva Thapa

Posted on Originally published at Medium on

The 7% You Can’t Share

A Compose Multiplatform app can share 93% of its code and still meet the platform in two places nothing abstracts away — native vendor SDKs, and the physical device. The finale is about engineering that edge so it fails loudly instead of rotting in silence.

Production Compose Multiplatform — Part 5 of 5, the finale. Part 1 — Liquid Glass · Part 2 — the case study · Part 4 — the architecture tour.

The number that sells a multiplatform rebuild is the shared-code percentage. Ours is 93% — measured, both codebases, counted in Part 2. It’s the figure I’d lead a conference talk with, because it’s true and it’s rare.

It’s also not where the engineering is.

The 93% is the part Compose Multiplatform gives you: write a screen once, it renders on both platforms. The interesting work — the work that decides whether the app is a demo or a product — lives in the other 7%. And that 7% is not scattered leftovers. It clusters at exactly two boundaries, the two places a shared codebase still has to touch something it cannot abstract:

  1. The vendor boundary  — native SDKs (Firebase, Google Maps, a payment provider) that ship no Kotlin bindings and have to be reached from shared code that must not know the difference.
  2. The device boundary  — the physical phone the app actually runs on, whose first-launch performance no amount of shared code improves, and which on our median device is a four-year-old budget Android.

Both are irreducible. And both share a failure mode that makes them dangerous out of proportion to their size: they degrade in silence. A vendor bridge keeps compiling long after its two sides have drifted apart. A performance win keeps “feeling fast” on your flagship long after it’s decayed on the phone your users own. Neither shows up in a green build.

This finale is about the one discipline that beats that, applied twice: make the seam narrow, and give it a tripwire — a failure loud enough that drift becomes a build error or a benchmark regression instead of a bug report six months late.

The Vendor Boundary: Two Ways to Bridge a Native SDK

Compose Multiplatform gives you shared UI. It does not give you shared vendors. Each native SDK arrives as a platform library with no iOS-side Kotlin bindings, and each has to be reachable from commonMain. The Android half is never the problem — the SDKs are Kotlin/Java-native, an injected implementation or an expect/actual seam covers it. The iOS half is where the real decision lives. In our codebase it resolved two different ways, and the contrast is the lesson.

Strategy 1 — header-only cinterop, when Kotlin is the caller

Firebase’s iOS SDK is Swift-first, ships through Swift Package Manager, and has no Kotlin bindings. The path of least resistance is to pull the whole SDK into the Kotlin framework through a CocoaPods integration and generate bindings against it.

We didn’t — for one reason that generalizes to every SDK you’ll ever bridge: that couples your Kotlin build to the entire vendor dependency graph  — its version, its transitive weight, its update cadence, its next CVE — for the sake of a handful of calls.

Instead, the Kotlin side binds a small header we wrote ourselves. It declares the surface Kotlin is allowed to see — nothing more:

@interface FirebaseAnalyticsService : NSObject
+ (FirebaseAnalyticsService *)shared;
- (void)logEvent:(NSString *)name params:(NSDictionary<NSString *, NSString *> *)params;
- (void)setUserId:(NSString *)userId;
- (void)setUserProperty:(NSString *)value forName:(NSString *)name;
- (void)setAnalyticsCollectionEnabled:(BOOL)enabled;
@end
Enter fullscreen mode Exit fullscreen mode

That’s one of four such blocks — analytics, messaging, crash reporting, performance — in a single 62+ line header. Swift implements each declared class with @objc(FirebaseAnalyticsService) annotations, and the Swift compiler, not the Kotlin one, resolves the real Firebase SDK from SPM.

The payoff is the whole reason to do it this way: the compiled Kotlin library carries no Firebase dependency. Kotlin calls FirebaseAnalyticsService.shared() as if it were any other object, and what stands behind that selector is entirely Swift's business. Bump Firebase's version, patch a Firebase CVE, or swap Firebase for something else — the Kotlin build doesn't recompile, because nothing it depends on changed. The blast radius of a vendor change stops at the Swift file. In a codebase whose thesis is shared code, that isolation is worth more than the few lines it costs.

And here is the tripwire. This strategy has exactly one discipline: the Swift selectors must match the header, exactly. Get one wrong and it doesn’t misbehave at runtime on one platform — it fails to link. The drift becomes a build error, caught on the machine that introduced it, not a null that surfaces in a farmer’s hands. A boundary whose only failure mode is a compile error is a boundary you can trust. (Full .def and multi-module mechanics are in my CInterop guide; this piece is about when, not how.)

Strategy 2 — a Kotlin interface implemented in Swift, when the SDK calls back

Then Google Maps refused to play that game.

The Maps SDK doesn’t want to receive fire-and-forget calls — it wants to hand you things: a map view to embed, camera callbacks, lifecycle obligations. A C-shaped “call this selector” binding is the wrong tool when the SDK’s real surface is object lifecycle plus a platform view.

So the bridge inverts. iosMain defines a plain Kotlin interface:

interface GoogleMapBridge {
    fun createMap(...): GoogleMapHandle
}

interface GoogleMapHandle {
    fun setCamera(lat: Double, lng: Double, zoom: Float, animated: Boolean)
    fun setMarker(lat: Double, lng: Double, title: String)
    fun cameraTargetLat(): Double // camera state read back out
    fun cameraZoom(): Float
    fun dispose()
}
Enter fullscreen mode Exit fullscreen mode

Swift implements both, wrapping GMSMapView, and injects the implementation at the one moment both worlds sit in a single hand — when Swift constructs the Compose host:

MainViewControllerKt.MainViewController(
    mapBridge: IosGoogleMapBridge(),
    placesBridge: IosGooglePlacesBridge()
)
Enter fullscreen mode Exit fullscreen mode

The shared map composable hosts the returned view through UIKitView and drives it through the handle. No header, no cinterop at all — the Kotlin/Native compiler already knows how to let Swift implement a Kotlin interface; we just hand the object across.

This inversion buys something cinterop can’t: testability. A Kotlin interface has a fake. Shared code that depends on GoogleMapBridge can be exercised in commonTest against a no-op or a scripted implementation, on any machine, no device, no SDK. The cinterop surface has no such seam — it's only real on a linked iOS binary. When the SDK sits behind an interface you defined, the SDK stops being a thing your tests have to reach.

The rule, and the corollaries that matter

One codebase, two strategies. After shipping both, the rule is clean:

Kotlin is the caller and the SDK’s surface is stable and Objective-C-representable? Header-only cinterop. Keep the SDK out of your Kotlin library entirely.

The SDK hands you views, delegates, or lifecycle callbacks? Define a Kotlin interface, implement it in Swift, inject at startup.

Shorter: cinterop when Kotlin calls; interface-injection when the SDK calls back. Firebase is fire-and-forget — cinterop. Maps is a conversation with a view in the middle — injection.

Three corollaries earned in production, the kind nobody writes on the box:

  • Don’t reach for a bridge first. Most iOS platform APIs need neither strategy: Kotlin/Native’s built-in platform.* bindings already cover LocalAuthentication, Security, CoreLocation, AVFoundation, WebKit. Across 46+ modules there is a single cinterop binding, wired in one module. Bridges are for vendor SDKs, not the OS — if you're writing a header to reach something Apple ships, check for the platform.* binding first.
  • Keep every dependency where its package manager lives. Firebase stays in SPM. Maps stays in SPM. The payment SDK stays an .xcframework behind a Swift factory on iOS and an .aar on Android. The Kotlin build never becomes the place iOS dependencies are managed — that job already has a tool, and taking it over is how KMP builds turn slow and brittle.
  • Mind what you own across the line. The object you hand across is retained by the other runtime; writes that land in Compose snapshot state must happen on the main thread (UIKit already obliges); and an exception thrown Swift-side is not a Kotlin Throwable until you make it one. The bridge is narrow on purpose, but "narrow" is not "free" — every method on it is a small contract about threading and ownership.

That last pattern — a Kotlin interface a native runtime implements, with state crossing back into Compose — turned out to be the most general tool in the whole app. Its furthest use isn’t an SDK at all: it’s the iOS 26 Liquid Glass UITabBar from Part 1, a Swift ObservableObject implementing a Kotlin interface, writing its height back into Compose snapshot state. The bridge you build for Maps is the bridge you'll reuse for everything the platform owns and Kotlin can't hold.

The Device Boundary: Performance Born on the Phone Your Users Own

The second place shared code runs out is not a vendor — it’s the metal. There’s a moment when performance work stops being abstract: the first cold start of your app on the cheapest phone your users actually own. Not the emulator. Not your flagship. The four-year-old budget device with the storage nearly full.

GeoKrishi Farm serves farmers across Nepal, and that phone is our median device — minSdk 24 is a deliberate choice, not an oversight. Compose Multiplatform runs beautifully on it, after the first launch. But the first launch is where a JIT-compiled UI framework pays its tax: ART interprets and JIT-compiles the hot paths — all of Compose's — as they first run. On low-end hardware, that tax is very visible, and it lands on the worst possible moment, the one where a new user decides whether the app is worth keeping.

A Baseline Profile is the fix: a list of methods and classes, shipped inside the app, that ART ahead-of-time compiles at install time, so the first launch skips interpretation for everything on the list. A Startup Profile additionally informs how that code is laid out in the DEX. Google documents the effect at roughly 30% faster code execution from first launch , and the startup profile at around another 15%. We ship both. Turning them on is trivial; the engineering is in two decisions the tutorials skip — what goes in the profile, and how you keep it honest.

The journey is the profile

A profile is only as good as the code paths its generator exercises. Ours drives the app’s genuine first session, in order — dismiss onboarding, scroll the public feed with real flings so image decode is captured, reach login, visit all five bottom-nav tabs — and one line of it is the whole philosophy in miniature:

// at the login step, the generator waits for the title a real user sees
device.wait(Until.hasObject(By.text("आफ्नो खातामा लग इन गर्नुहोस्")), timeout)
Enter fullscreen mode Exit fullscreen mode

It asserts on the Nepali login title. The profile should capture the app that ships, and our users see Nepali; profiling an English debug variant would ahead-of-time-compile a UI that never runs. includeInStartupProfile = true means this single journey feeds both profiles — the code that matters for startup is, definitionally, the code the startup journey touches.

And the generator runs on a physically connected budget device , not a Gradle-managed emulator. A profile is a bet about which code paths matter; place the bet on hardware that resembles the audience. An emulator on a development machine has never once behaved like a four-year-old phone with a full disk.

Shipping it, and the trap that eats an afternoon

The generator writes a 64,265+ line profile into the release sources; the app module consumes it and adds profileinstaller, which applies the packaged profile on first run — before Play's cloud-distilled profile has arrived, which is exactly when a new install is most fragile.

Here’s the senior half nobody warns you about: verify the profile actually installed. A baseline profile that silently failed to apply is indistinguishable from a working one until you measure — same app, same green build, no AOT benefit, no error. A performance optimization you didn't verify is a performance optimization you don't have.

The harness is the tripwire

A profile is not a one-time win; it’s a claim that decays. Every release moves code, and a profile describing last quarter’s hot paths slowly stops describing yours. So next to the generator lives a macrobenchmark — the device-boundary equivalent of the compile error that guards the vendor boundary:

@Test fun startupCompilationNone() = benchmark(CompilationMode.None())
@Test fun startupCompilationBaselineProfile() =
    benchmark(CompilationMode.Partial(BaselineProfileMode.Require))
// StartupTimingMetric, COLD, 10 iterations each
Enter fullscreen mode Exit fullscreen mode

Two details in there are load-bearing. BaselineProfileMode.Require — not Enable — means the benchmark fails if the profile is missing, rather than quietly measuring an uncompiled build and reporting a flattering non-result. And ten cold iterations, compared by median , because a single cold start is noise and a mean is hostage to one slow outlier. The delta between the two modes is the profile's value, measured — and re-measurable on demand, on the same class of device the profile was born on. On our reference device, the current medians are 1,518 ms without the profile and 1,108 ms with it  — a 410ms cold-start win, about 27%, on the hardware that needs it most.

Two honest limits, because a finale that only sells is a finale you shouldn’t trust:

  • The number is time-to-initial-display, not time-to-full-display. We measure the first frame; we don’t yet call reportFullyDrawn(), so the async settling after first paint — the feed's images resolving, the first data landing — is outside the measurement. The number is real and it's the right first metric, but it's honest about the frame and blind to what fills it. reportFullyDrawn() is the next instrument, not a box already ticked.
  • A profile compiles your startup code; it doesn’t remove it. AOT can’t help a cold start that’s slow because Application.onCreate is doing too much — SDK initialisation, strict-mode setup, dependency-graph construction all land there, on the main thread, before the first frame. The profile makes that work run compiled instead of interpreted; doing less of it is a separate discipline the profile can't substitute for. Measure before you assume the profile is the whole answer.

The Through-Line: Build a Tripwire, Not a Rule

Step back and the two halves of this piece are the same move made twice.

The vendor boundary and the device boundary are where a multiplatform app quietly stops being what its shared-code percentage claims. A bridge drifts and keeps compiling. A profile decays and keeps feeling fast on the wrong phone. In both cases the danger isn’t the difficulty — it’s the silence. Neither failure raises its hand.

You don’t fix silent decay with discipline, because discipline doesn’t survive deadlines and new teammates. You fix it with a loud failure wired into the seam itself : on the vendor side, a selector mismatch that won’t link; on the device side, a benchmark whose delta collapses when the profile drifts and a Require mode that refuses to measure a build without one. The rule you have to remember is worth nothing at 6pm on a Friday. The build error and the red benchmark remember for you.

That’s the shape of every durable decision in this series, now that I line them up: the module boundary that makes a forbidden import fail to resolve rather than merely be discouraged; the redaction that lives in the logging pipeline so no future caller can leak a token; the Liquid Glass shell that reverts by deleting one if-branch. Good architecture isn't a set of rules people follow. It's a set of mistakes the system won't let them make.

What We’ve Built — the Series, Closed

Five parts, one production app, live on both stores, serving farmers across Nepal:

  1. A real iOS 26 UITabBar rendering Apple's Liquid Glass over an unchanged shared Compose host (Part 1) — native chrome, shared behavior, no forked navigation.
  2. A KMP app that shared 848 lines with iOS, rebuilt to 93% shared — every number counted from both codebases (Part 2).
  3. The rewrite shipped as an ordinary store update — credential migration under R8 obfuscation, a new encrypted cache layer, deep-link archaeology.(Part 3)
  4. The 46-module architecture, with boundaries the compiler enforces and a dependency graph rendered straight from the build (Part 4).
  5. The 7% that can’t be shared — native-SDK bridges chosen by who calls whom, and baseline profiles born on the hardware our users actually own — each with a tripwire against silent decay.

The thread through all five was never “how to share more code.” It was where to draw the boundary, and how to make the boundary defend itself.

What’s Next

The practice continues — coverage growing over the framework-free domain layers, reportFullyDrawn() to close the gap between first frame and first useful frame, the release pipeline hardening, and a quarterly re-run of every number this series quoted. If the numbers move interestingly, you'll read about it.

If you ship to low-end devices and profile on flagships — run one cold start on the phone your median user owns, and confirm the profile actually installed while you’re there. Then come tell me what you found, in the comments.

Drop a ❤️ if this series was useful — it helps more developers find it.

Top comments (0)