Mosmoxmosmox

Mosmox journal

In focus — architecture.

A selection of publications grouped under the architecture tag.

Designing an API for Mobile Clients: Pagination, Versioning and Errors

Designing an API for Mobile Clients: Pagination, Versioning and Errors

A web client and its backend usually update together: you deploy and every user gets the new version. Mobile does not work that way. Production runs versions released eighteen months ago, devices on flaky 3G in the underground and users who switched off automatic updates. An API designed "as if for a website" becomes a constant source of crashes and client-side workarounds.

This article covers the three areas where mobile specifics bite hardest: pagination, versioning and error format. Plus idempotency, caching and the team contract, without which the first three do not hold up.

How a mobile client differs from the web

FactorWebMobile appImplication for the API
Client versionsOne currentDozens at onceBackward compatibility is mandatory
NetworkMostly stableDrops, high latency, Wi-Fi/LTE handoversIdempotency, retries, small responses
UpdatesInstantThrough review and the userKeep changeable logic on the server
ResourcesDesktop-classBattery, data, memoryFewer requests, compact payloads
LifecycleTab stays openApp is suspended and killedState restoration, reloading pages

The core rule: every API change must be safe for the oldest supported app version. Google formalises what counts as a breaking change in AIP-180: removing or renaming a field, changing a type, adding a required request field, changing defaults.

Pagination: cursors instead of pages

Offset pagination (?page=3&limit=20) is simple, but in mobile feeds it causes two classic bugs. If a new order arrives between loading page one and page two, the user sees a duplicate. If a record is deleted, an item disappears. And large offsets are slow at the database level.

Cursor (keyset) pagination passes an opaque position token: the client receives next_cursor and sends it with the next request. Google recommends this approach in AIP-158 (page_token), and for GraphQL it is standardised in the Relay Connections specification.

CriterionOffset / pageCursor (keyset)
Stability under inserts and deletesDuplicates and gapsStable
Performance on deep pagesDegrades as offset growsStable with an index
Jump to arbitrary pageYesNo (rarely needed in mobile feeds)
Total countEasySeparate, ideally cached request
Implementation effortMinimalModerate

Practical rules

  • Keep the cursor opaque (for example, base64 of the id and sort date) so you can change the implementation without touching clients.
  • The server sets the maximum page size; the client may ask for less. For mobile lists, 20–50 items is usually enough.
  • Return an explicit end marker: an empty next_cursor or has_more: false.
  • For pull-to-refresh, support fetching items newer than the first one instead of reloading the whole list.
  • Make sorting deterministic, "by date, then by id", or records with identical dates shuffle between pages.

Versioning: not breaking old apps

There are three common approaches: version in the URL (/v2/orders), in a header (Accept or a custom one), or dated versions as at Stripe, where each client is pinned to a specific API date. For most mobile products we recommend the simple path: a major version in the URL and as many additive changes within it as possible.

Additive changes are safe

  • A new optional response field. The client must ignore unknown fields: verify your JSON decoder does not choke on them (in Swift Codable and kotlinx.serialization this is a configuration choice, not universal default behaviour).
  • A new endpoint or a new optional query parameter.
  • A new enum value, but only if the client maps unknown values to "unknown" instead of crashing.

Version support policy

  1. The client sends its app version and platform with every request (for example, an X-App-Version header). That gives you statistics and the option to vary behaviour selectively.
  2. Define a minimum supported version and a window, for example versions from the last 12 months.
  3. Implement soft and hard update prompts: a config endpoint returns min_supported and recommended versions. Android offers the In-App Updates API; on iOS, a custom screen linking to the App Store.
  4. Before retiring an old API version, check its share of traffic. We usually wait until it falls below 1–2% of active users and announce the forced update in advance.

Errors: one format for the whole API

The worst variant, which we see regularly: 200 OK with {"success": false} in the body, different error shapes per endpoint, and English text the client shows to users verbatim. RFC 9457 Problem Details (the successor to RFC 7807) defines a single structure: type, title, status, detail, instance plus custom extensions.

What a mobile client needs from an error

  • The correct HTTP status per RFC 9110: 400/422 for invalid input, 401 for missing authentication, 403 for missing permission, 404 for a missing resource, 409 for a conflict, 429 for too many requests, 5xx for server problems.
  • A machine-readable code (type or code) the client uses to decide what to do: show an inline error, offer a retry or sign the user out.
  • Per-field validation errors so a specific form field can be highlighted.
  • A request id for log lookups when the user contacts support.
  • Localised text, either via Accept-Language or on the client by code. What matters is that ownership is clear.
SituationStatusClient behaviour
Invalid e-mail in a form422 + per-field errorsHighlight the field, do not retry
Expired access token401Refresh the token and retry once
Item sold out during checkout409 + out_of_stock codeShow a dialog and refresh the cart
Rate limit exceeded429 + Retry-AfterWait the given time, show a message
Server failure500/503Retry with exponential backoff, show cached data

Idempotency and unreliable networks

The user taps "Pay", the request reaches the server, and the response is lost in a tunnel. The client retries and creates a second order. The fix is an idempotency key: the client generates a UUID for the operation and sends it in an Idempotency-Key header; when the server sees a retry with the same key, it returns the stored result. This is how the Stripe API works, and the header is being standardised at the IETF.

GET, PUT and DELETE are idempotent by definition; POST is not. So keys matter most for creating orders, payments, messages and any money-related operation.

Performance: fewer requests, fewer bytes

  • Aggregate data per screen. If the home screen makes eight requests at launch, consider an endpoint that returns everything in one call (the Backend for Frontend pattern).
  • Conditional requests. ETag and If-None-Match let the server reply 304 Not Modified without a body.
  • Compression. gzip or brotli shrinks JSON several-fold.
  • Image size. Serve URLs with size parameters, not multi-megabyte originals.
  • Timestamps. All dates in ISO 8601 with a time zone (UTC); formatting happens on the client.

The contract between backend and mobile teams

An OpenAPI description is not box-ticking documentation but a contract. From it you can generate client code, a mock server so mobile developers do not wait for the backend, and contract tests that catch breaking changes in CI. A practice that works well in our projects: every schema change is reviewed by a mobile developer, and CI automatically diffs the new schema against the previous one and blocks field removals.

Common mistakes

  • Renaming a field "because it reads better" without a new API version.
  • Offset pagination in frequently updated feeds.
  • Errors returned with status 200, and different error formats per endpoint.
  • No forced-update mechanism in the first release: you cannot retrofit it into old versions later.
  • Retrying POST requests without an idempotency key.
  • A client decoder that crashes on an unknown field or enum value.

API checklist before release

  1. Cursor pagination with deterministic sorting and an explicit end marker.
  2. A documented versioning policy and minimum supported app version.
  3. A config endpoint with a min_supported version in the very first release.
  4. A single error format (RFC 9457), machine-readable codes, request ids.
  5. Idempotency-Key for every non-idempotent money or order operation.
  6. The client ignores unknown fields and handles unknown enum values.
  7. OpenAPI schema in the repository, backward-compatibility checks in CI.
  8. ETags, compression and aggregated endpoints for key screens.

Sources: RFC 9457: Problem Details for HTTP APIs; RFC 9110: HTTP Semantics; Google AIP-158: Pagination; Google AIP-180: Backwards compatibility; GraphQL Cursor Connections Specification; Stripe: API versioning; Stripe: Idempotent requests; IETF: The Idempotency-Key HTTP Header Field; OpenAPI Specification; Android: In-app updates.

Mobile App Architecture: MVVM, Clean Architecture and Modularisation Without Overkill

Mobile App Architecture: MVVM, Clean Architecture and Modularisation Without Overkill

Mobile app architecture usually fails at one of two extremes. In the first, all the code lives in a 2,000-line ViewController or Activity, and any change to one screen breaks something next door. In the second, a ten-screen MVP gets a "perfect" Clean Architecture with five layers, a use case for every API call and twenty Gradle modules, and the team needs a week to add one form field.

This article explains what MVVM, Clean Architecture and modularisation actually give you, how to size them to your product and team, and which signals tell you it is time to add structure. We lean on the official Android recommendations and modern SwiftUI practice.

What problem architecture solves

Architecture is not about pretty diagrams. It answers practical questions: how much a change costs, how easily it can be tested and how many people can work in parallel without stepping on each other. Mobile adds platform challenges: screens are destroyed and recreated (rotation, memory pressure), the process can be killed in the background, and the network drops mid-request.

So the core principles are the same on iOS and Android:

  • Separation of concerns. The UI renders state and forwards events; business logic and data access live elsewhere.
  • Single source of truth. Every data type has one owner, such as a repository backed by a local database.
  • Unidirectional data flow (UDF). State flows down to the UI, events flow up to the ViewModel. Google recommends this explicitly in its architecture recommendations.
  • UI driven by a state model. A screen is a function of state, not a sequence of imperative calls.

MVVM: the baseline for most apps

MVVM (Model–View–ViewModel) is the de facto standard: on Android it is backed by Jetpack ViewModel and StateFlow, on iOS by SwiftUI with Observation (@Observable) or ObservableObject on older versions.

What a healthy ViewModel looks like

  • Exposes a single screen state object (UiState): data, a loading flag, an error.
  • Accepts UI events: "Retry tapped", "filter changed".
  • Knows nothing about concrete views, contexts or navigation controllers.
  • Delegates data work to repositories rather than calling the API directly.
  • Is covered by unit tests that run without an emulator or simulator.

A typical problem we find in code audits: the ViewModel becomes an 800–1,500-line god object that validates forms, formats dates, caches, talks to the network and handles analytics. That is the same Massive View Controller, just moved into another file. A sign it is time to extract logic: a method longer than a screen, or identical logic copied into two ViewModels.

MVI and TCA as variations

MVI treats state as an immutable object and every change as a reducer over events. On iOS, The Composable Architecture implements a similar idea. These approaches bring predictability and convenient testing of complex screens at the cost of more boilerplate. A sensible strategy is MVVM by default and a reducer approach for screens with complex state logic: multi-step forms, carts, editors.

Clean Architecture: what to keep and what to skip

Robert Martin described Clean Architecture as concentric circles with dependencies pointing inwards: business rules know nothing about frameworks, databases or UI. In mobile practice this usually becomes three layers: presentation, domain and data.

An important detail that often gets missed: the Android guide explicitly marks the domain layer as optional. It is worth introducing when logic is complex or reused by several ViewModels. A use case that merely forwards a repository call adds a file, a test and a level of indirection with no benefit.

LayerContainsWhen you need it
PresentationView, ViewModel, UiState, mapping to screen formatAlways
DomainUse cases, business rules, domain modelsWhen logic is complex or shared across screens
DataRepositories, API clients, database, cache, DTOsAlways, at least as a repository

Signs of over-engineering

  • Three nearly identical models (DTO, Entity, Domain) for every entity with no difference in fields.
  • A use case for every repository method, each containing a single line.
  • Interfaces with exactly one implementation that nobody substitutes, not even in tests.
  • Adding a field to the API requires changes in 7–10 files.

Modularisation: when to split the codebase

A module is a Gradle module on Android or a Swift package / framework on iOS. Modularisation brings faster incremental builds, clear boundaries between teams, code reuse and enforced isolation: a feature module simply cannot see another module's internals. Google covers the approaches in its modularisation guide, and the Now in Android reference app shows them in practice.

But every module means build configuration, a public API, dependencies and maintenance time. Here are guidelines from our experience:

Product sizeTeamRecommended structure
MVP, up to 20 screens1–3 mobile developersOne app module with feature packages; optionally a separate core networking module
Growing product, 20–60 screens3–6 developersapp + core (network, database, design system) + 3–8 feature modules
Large product, 60+ screensseveral teamsFeature modules split into api/impl, module owners, dependency graph checks

How to split well

  1. Start with packages by feature, not by layer. A "checkout" folder with everything inside is far easier to extract than files scattered across "viewmodels" and "repositories".
  2. Extract core first. Networking, database, design system and analytics are needed by every feature and change less often.
  3. Feature modules do not depend on each other. Navigation between them goes through the app module or a dedicated navigation contract.
  4. Watch the graph. Circular dependencies, or a "core" that depends on everything and everything depends on, destroy the benefits.
  5. Measure. Clean and incremental build times before and after; Gradle Build Scans and the build cache on Android, Xcode's build timing summary on iOS.

Cross-platform specifics

Flutter and React Native apply the same principles with their own tools. In Flutter, Riverpod and BLoC are common ViewModel equivalents with UDF; in React Native, stateful hooks, Zustand or Redux Toolkit, and React Query for server state. The most useful split here is between server state (cached API responses) and local UI state. When both live in one global store, you get stale data and unnecessary re-renders.

With Kotlin Multiplatform it makes sense to share the data and domain layers while keeping the UI native or on Compose Multiplatform. That way layer boundaries line up with platform boundaries.

Testability as a measure of architecture

The simplest architecture test is trying to write a unit test for a screen's logic. If you need an emulator, ten mocks or access to private fields, the boundaries are in the wrong place. A realistic test pyramid for a mid-complexity app, from our experience:

LevelWhat we testApproximate share
UnitViewModels, use cases, mappers, validation60–75%
IntegrationRepository + database, API client against a fake server15–25%
UI / end-to-endCritical flows: sign-in, payment, onboarding5–15%

Inject dependencies through constructors (Hilt or Koin on Android, a simple DI container or factories on iOS) so tests can swap them for fakes easily.

Common mistakes

  • Tutorial architecture without adaptation. A big company's sample project structure does not necessarily fit a team of two.
  • Business logic in the UI. A discount calculation inside a Composable or SwiftUI View cannot be properly tested or reused.
  • No single source of truth. User data cached in three places drifts apart after a profile update.
  • Modularisation for its own sake. Thirty modules for fifteen screens slow down both development and builds.
  • Postponed refactoring. Boundaries you did not draw at 20 screens will cost several times more at 80.

Checklist for your project

  1. Every screen has a ViewModel (or equivalent) with one UiState and tests.
  2. Data access goes through repositories; ViewModels never call the API directly.
  3. A domain layer appears only where there is real business logic or reuse.
  4. Code is grouped by feature; core functionality is extracted separately.
  5. Adding a simple API field touches no more than 3–4 files.
  6. Incremental build time is measured and does not creep up unnoticed.
  7. Architecture decisions are briefly recorded as ADRs (Architecture Decision Records) so new developers understand the "why".

Sources: Android: Guide to app architecture; Android: Architecture recommendations; Android: Domain layer; Android: Guide to modularization; Now in Android; Robert C. Martin: The Clean Architecture; Apple: Observation; Apple: Swift packages; The Composable Architecture.

Adaptive Apps for Foldables and Googlebook: What Google Play Will Start Looking At

Adaptive Apps for Foldables and Googlebook: What Google Play Will Start Looking At

Google has warned developers that next year Google Play will look more closely at how apps and games run on foldables and will offer more opportunities to showcase adaptive products. Specific store requirements are promised later this year. Until they appear, the best preparation is to understand what Google counts as adaptive quality and to fix weak spots now.

What is known today

In its October Android Dev Summit announcement, Google linked two things. First, with the arrival of Googlebook, apps can scale across phones and laptops without a separate codebase. Second, next year Google Play will look closely at how apps run on foldables. Details are promised "later this year", so there are no official requirements at the time of writing. For apps, Google advises following the Adaptive app quality guidelines; for games, a separate set of adaptive games guidelines.

Three tiers of adaptive quality

TierNameIn short
Tier 3 (basic)Adaptive readyThe app runs full screen or full window on all devices, without letterboxing or compatibility mode; basic support for keyboard, mouse, trackpad and stylus
Tier 2 (better)Adaptive optimizedLayout optimizations for all screen sizes and configurations, with enhanced support for external input devices
Tier 1 (best)Adaptive differentiatedAn experience designed for the device: multitasking, foldable postures, drag and drop, stylus

To earn the Large Screen Badge on Google Play, Google says to complete Tier 2 (optimize for all screen sizes) and Tier 1 (a differentiated experience for large screens). Google also notes that your app probably does not need to meet every requirement: implement the ones that make sense for your use cases.

How to test

According to Google, layout and UX testing should cover at least these device types:

  • Googlebook (160 ppi);
  • foldable (841×701 dp);
  • 8-inch tablet (1024×640 dp);
  • 10.5-inch tablet (1280×800 dp);
  • 13-inch Chromebook (1600×900 dp).

Android Studio provides emulators for this: Pixel Fold for foldables, Medium Tablet for tablets and Desktop (Preview) for desktop, which needs a Canary build. There is also the resizable emulator for arbitrary configurations.

What breaks first

Google states plainly that when screens fold, windows resize and apps move across form factors, usual layout assumptions can break and apps easily lose state. So your checklist should include:

  • State preservation when folding and unfolding, resizing the window and rotating.
  • Multi-pane layouts instead of a stretched phone screen (Grid, FlexBox, Navigation 3, WindowManager).
  • Tabletop posture for camera and media screens.
  • External input: keyboard shortcuts, hover states, tooltips, trackpad and mouse cursors.
  • Tablet and foldable screenshots on your Google Play listing: Google recommends showing the app on these devices and mentioning it in the description.

Speeding up work with agents

The updated Compose Adaptive skill helps agents turn compact screens into responsive multi-pane layouts and handle state and configuration changes. According to Google, it now adds foldable and desktop support: windowing, keyboard shortcuts, tooltips and trackpad hover states. The skill also audits Compose UI for these elements and refactors camera and media screens into tabletop layouts. It is a tool for a first-draft audit, but the result still needs manual checks on real devices.

Where to start in your project

  1. Find your current tier: go through the Tier 3 checklist and make sure the app does not run in compatibility mode.
  2. Run a critical flow on a foldable emulator while folding and resizing.
  3. Fix state loss before polishing visuals.
  4. Add keyboard and mouse support for the main actions.
  5. Update your store listing with large-screen screenshots.
  6. Watch for the Google Play announcement on requirements and opportunities for adaptive apps.

For more on technical approaches, see our article on tablet and foldable apps and our comparison of SwiftUI, Compose and classic Views.

Adaptivity is no longer a nice extra: it is becoming a visible quality signal in the store. Teams that start with state preservation and basic layouts will be ready before the requirements appear.

Sources: Android Developers Blog: Agentic and Flexible: A next era of Android development; Android Developers: Adaptive app quality guidelines; Android Developers Blog: Build for every screen with the latest Jetpack Compose updates.

Compose 1.13, AppState and Navigation 3: What Changes in Android App Architecture

Compose 1.13, AppState and Navigation 3: What Changes in Android App Architecture

Android Dev Summit 2026 brought more than new APIs: it shifted how Google recommends building UI, state and navigation. The upcoming stable Compose 1.13 adds Grid and FlexBox, Navigation 3 1.2 is already stable, and Jetpack AppState in alpha moves Compose's state model into the architecture layer. Here is what to build into a project now and what to simply watch.

What was announced

ComponentStatusWhat it gives you
Jetpack Compose 1.13Upcoming stable releaseGrid and FlexBox, Progressive Blur, Formatted Text, recomposition tracing
BasicTextFieldRewritten (according to Google)Buffer-driven architecture, TextFieldState, no IME race conditions
Navigation 3 1.2StableType-safe deep links, richer Predictive back
Jetpack AppStateAlphaTransform and StateStore: reactive state beyond the UI

Adaptive layouts: Grid and FlexBox

Google calls Compose the standard for all UI on Android and the reasoning is simple: one approach instead of fragmented codebases for phones, foldables, tablets, wearables, cars, XR and Googlebook. In Compose 1.13, built-in adaptive layout support through Grid and FlexBox moves to stable. Together with Navigation 3 and WindowManager, it is the foundation for multi-pane interfaces that rearrange to the window instead of just stretching a phone screen.

If your screens were only ever designed for phones, this is a good moment to revisit them. We covered the practical limits of this approach in our piece on tablet and foldable apps.

Text fields and graphics

Google reports that text editing in Compose is now built on a rewritten BasicTextField with a buffer-driven architecture and TextFieldState. The goal is to remove keyboard (IME) race conditions and support formatted text. For apps with complex forms, chats or editors, it is worth testing separately on real devices and different keyboards, since input bugs are usually the most painful ones.

Compose 1.13 also brings Progressive Blur and Formatted Text, and Google says graphics features such as mesh gradients run without hurting battery or frame rate. Effects are useful, but measure their impact on your own app.

Recomposition tracing: why the UI redraws

Compose 1.13 introduces recomposition tracing. It shows not only which functions recomposed but why, all the way back to the state write that triggered it. Combined with composition tracing in the Android Studio Profiler, it makes unnecessary recompositions easier to find. For coding agents, Google published the jetpack-compose-performance skill, which points them at common performance anti-patterns.

Jetpack AppState: state as part of the architecture

AppState (alpha) brings Compose's snapshot system into the app layer. Transform derives reactive state from State and Flow inputs using automatic read tracking and plain Kotlin control flow. StateStore is a keyed container that shares observable state across activities, background services, widgets and App Functions, optionally persisted through DataStore.

It is an interesting idea for apps where the same state appears on several surfaces: a screen, a widget, a notification, an agent call. But it is alpha, so APIs may change. Our recommendation is to pilot AppState in an isolated module of a non-critical feature rather than rewrite your core with it. For how app layers relate to each other, see our article on MVVM and Clean Architecture.

Navigation 3 1.2: deep links without manual parsing

Navigation 3 works with a back stack that you own. Version 1.2 adds built-in type-safe deep link support: with Kotlin Serialization you can map incoming URIs and intents to strongly typed navigation keys, customize how complex arguments are parsed, and lazily build synthetic back stacks so back navigation feels natural. Google also mentions richer Predictive back handling.

What teams should do

  1. Plan the upgrade to Compose 1.13 once it is stable, and run UI tests and profiling before and after.
  2. Check layouts at different window sizes: folding a foldable, resizing a window or using a tablet must not reset state.
  3. Evaluate Navigation 3 if you are on the previous navigation and plan deep links or multi-pane screens.
  4. Try AppState on an isolated feature and keep alpha APIs off the critical path.
  5. Add Android skills for your agents: Google offers Adaptive, Compose performance, XML to Compose migration and Ink. For choosing between UI approaches, see our comparison of SwiftUI, Compose and classic Views.

Conclusion

The core idea of these updates is that Compose is moving beyond the rendering layer: it becomes the basis for adaptive layouts, text, navigation and state. For new projects, that means designing architecture for multiple form factors from the start instead of adding them at the end.

Sources: Android Developers Blog: Build for every screen with the latest Jetpack Compose updates; Android Developers Blog: Agentic and Flexible: A next era of Android development; Android Developers Blog: What's new in Android developer tools and performance.

Journal

Ideas and products