Mosmoxmosmox

Mosmox journal

In focus — development.

A selection of publications grouped under the development tag.

Feature Flags and Remote Config: Shipping Features Without a New Release

Feature Flags and Remote Config: Shipping Features Without a New Release

On the web you can fix a bug and deploy in ten minutes. In a mobile app, between "found the problem" and "fixed for every user" lie a build, App Store review, a staged rollout and weeks of waiting for people to update. Some users don't update for months. So anything you can change without a new binary, you should be able to change without one.

Feature flags and Remote Config give you exactly that: turning features on and off, changing copy and parameters, running gradual launches and killing something broken in an emergency. Below is how we at Mosmox design these systems, which tools we choose, what the store rules allow, and how to keep flags from turning into tech debt.

Four kinds of flags, and why they shouldn't be mixed

A useful classification comes from Pete Hodgson's article Feature Toggles on Martin Fowler's site. The types differ in lifespan and in who controls them:

TypePurposeLifespanOwned by
Release toggleHide unfinished work, gradually expose finished workWeeks; removed after 100% launchEngineering, product
Experiment toggleA/B test: different variants for different groupsLength of the experimentProduct, analytics
Ops toggle / kill switchSwitch off a feature or integration under load or during an outageLong, sometimes permanentEngineering, support
Permission toggleAccess for paying users, beta testers, staffPermanentProduct, business logic

The mistake we see most is using one mechanism for everything. Access to a paid feature decided by Remote Config on the client is trivial to bypass: any flag stored on the device can be tampered with. Entitlements must be checked on the server; a client-side flag should only control presentation.

Firebase Remote Config: capabilities and limits

Firebase Remote Config is the most common free option on mobile. What to know before adopting it:

  • In-app defaults. The app must ship a default for every parameter. A first launch with no network has to work correctly.
  • Fetch interval. The default minimum fetch interval is 12 hours; you lower it during development, while overly frequent fetches in production hit throttling.
  • Real-time updates. A real-time Remote Config listener receives changes right after they're published — useful for a kill switch when waiting 12 hours is unacceptable.
  • Conditions. Targeting by app version, platform, country, language, Analytics audiences and a random percentage of users.
  • Limits. Up to 2,000 parameters and 500 conditions per template. Plenty for most projects, but a signal not to turn Remote Config into a database.
  • Version history and rollback. Every publish creates a template version you can revert to in one click.

Activation strategy

The key decision is when to apply fetched values. Change the UI mid-session and users see the screen jump. We usually fetch in the background and activate on the next launch; the exception is a kill switch, which applies immediately.

When a dedicated service is worth it

ToolStrengthsWhen to choose it
Firebase Remote ConfigFree; integrates with Analytics, A/B Testing and CrashlyticsMost mobile projects on Firebase
LaunchDarkly, StatsigRich targeting, change audit, roles, experiments, backend and web supportMultiple teams, audit requirements, flags across the whole stack
Unleash, Flagsmith, GrowthBookOpen source, self-hosting availableData residency requirements, infrastructure control
Your own config endpointFull control, zero third-party SDKsSimple needs, strict security requirements — but you'll build targeting and history yourself

Our approach: whatever the tool, app code reads flags through our own wrapper. Switching vendors then takes days rather than months, and flags are easy to override in tests.

What the App Store rules allow

Flags are not a way around review. The App Review Guidelines forbid hidden, dormant or undocumented features in section 2.3.1, and section 2.5.2 forbids downloading code that changes the app's functionality. In practice:

  • Changing copy, colours, block order, prices within existing products, or algorithm parameters is normal practice.
  • Gradually exposing a feature that is already in the binary and documented is fine. If it's switched off at review time, describe it in the reviewer notes and give a way to see it.
  • Switching on, after review, functionality hidden from Apple — especially anything that changes what the app is or circumvents payment rules — is a direct route to removal from the store.

Launching a feature behind a flag, step by step

  1. Code behind the flag. The feature is merged into the main branch switched off. This avoids long-lived branches and merge conflicts.
  2. Internal testing. The flag is enabled for staff and testers via an ID- or audience-based condition.
  3. Binary release. The version containing the feature passes review and rolls out; the feature is still off, or available to the reviewer as documented.
  4. Gradual enablement. 1% → 5% → 20% → 50% → 100% of users on the new version. At each step we watch crashes, API errors and business metrics for 24–72 hours.
  5. Stop criteria. Agreed upfront: if crash-free users with the feature enabled fall below the control group, or backend errors rise, the flag goes off without debate.
  6. Clean-up. After two to four stable weeks at 100%, the flag and the old code path are removed in the next release.

Firebase offers Remote Config rollouts, which show Crashlytics stability separately for the group with the feature enabled. That makes step 4 much easier.

Kill switches and forced updates

We add two flags to every project before the first release, because by the time you need them it's too late to add them:

  • A kill switch for risky integrations — a payment provider, a third-party SDK, a new endpoint. If the integration breaks, you can disable it and show a clear fallback instead of a crash.
  • A minimum supported version. A parameter compared with the app version: a soft update prompt, or a blocking screen for versions with a critical vulnerability or an incompatible API.

Both mechanisms have to work even when the rest of the app is broken, so we cover them with dedicated tests.

Common mistakes and flag debt

  1. Flags nobody removes. A year later the code has 80 conditions, half of them always on, and nobody remembers why. Every release toggle needs an owner and a removal date.
  2. Combinatorial explosion. Ten independent flags make 1,024 possible configurations. Test the main combinations and avoid dependencies between flags.
  3. No defaults. Offline, the app gets empty values and renders a broken screen.
  4. Entitlements on the client. A paid feature "protected" only by a Remote Config flag.
  5. Uncontrolled changes. Someone edits a value in the console on a Friday evening with no review. Production parameters need roles, history and a four-eyes rule.
  6. No idea what the user saw. Flag state isn't passed to analytics or crash monitoring, so you can't tell which configuration a problem occurred in.

Adoption checklist

  • A tool is chosen, and flags are accessed through your own wrapper.
  • Every parameter has an in-app default.
  • An activation strategy is defined: next launch for UI, immediate for kill switches.
  • Kill switches for critical integrations and a minimum-version parameter exist from the first release.
  • Entitlements are checked on the server; flags only control presentation.
  • Key flag states are sent to analytics and to crash monitoring as custom keys.
  • Every release toggle has an owner and removal date; flags are reviewed quarterly.
  • Production configuration changes are reviewed by a second person.
  • Features switched off at review time are described in the App Review notes.

Sources: Pete Hodgson, Feature Toggles (martinfowler.com); Firebase Remote Config; Remote Config parameters and conditions; Real-time Remote Config; Remote Config rollouts; App Store Review Guidelines.

The Mobile Test Pyramid: Unit, Integration and UI Tests, and What to Automate First

The Mobile Test Pyramid: Unit, Integration and UI Tests, and What to Automate First

"We have tests" can mean almost anything on a mobile project: from three unit tests for date formatting to two hundred UI scenarios that fail every other run and that everyone ignores. Neither extreme protects you from regressions. The question isn't whether to write tests, but which ones, how many, and in what order.

This article explains how we at Mosmox build a testing strategy for iOS and Android: what belongs on each level of the pyramid, where to start on a project with no tests, how to tame flaky UI tests and how much time to budget.

The test pyramid: the classic model and what's different on mobile

Mike Cohn popularised the pyramid: lots of fast, cheap unit tests at the base, fewer integration tests in the middle, and a small number of end-to-end tests through the UI at the top. The model is explored in depth in The Practical Test Pyramid on Martin Fowler's site.

Android's documentation uses similar language: small, medium and large tests, defined by how much code they exercise and where they run. The logic is simple: the higher a test sits, the slower and costlier it is to maintain and the more often it fails spuriously — but the closer it gets to the real user experience.

Mobile adds two factors. First, UI tests need an emulator or simulator, which means CI minutes and start-up time. Second, mobile bugs often live at the boundary with the platform: permissions, screen lifecycle, rotation, process death and restoration. That makes the middle of the pyramid more important for mobile apps than for many backends.

What each level covers

LevelWhat it checksToolsSpeedRough share
UnitViewModels, use cases, validation, formatting, calculations, mappersJUnit, Kotest, MockK; XCTest, Swift TestingMilliseconds60–75%
IntegrationRepository + database, network layer against a fake server, cross-module navigationRobolectric, in-memory Room, MockWebServer; XCTest with URLProtocol stubsSeconds15–30%
UI component / snapshotA single screen or component in isolation, visual regressionsCompose UI testing, Paparazzi, Roborazzi; swift-snapshot-testingSeconds5–15%
End-to-endCritical journeys through the real UI and a test backendEspresso, UI Automator, XCUITest, MaestroMinutes5–10%

The shares are a guideline from our projects, not a rule. One principle matters more than percentages: write each check at the lowest level where it can be written at all. If email validation can be covered by a unit test, it has no business living in a UI scenario.

Unit tests: a foundation that needs the right architecture

Unit tests are only cheap when the code is ready for them. If business logic lives inside an Activity, Fragment or SwiftUI View, you can only test it through the UI — and the pyramid flips. So testability is an architectural requirement for us: logic in ViewModels and use cases, dependencies passed through constructors, time, network and storage hidden behind interfaces.

What to cover with unit tests first:

  • calculations involving money, discounts, taxes and currencies;
  • access rules: what free and paying users can see;
  • screen state transitions: loading → content → error → empty;
  • parsing and mapping API responses, including incomplete or malformed data;
  • date and time-zone logic — one of the most frequent bug sources on our projects.

On iOS, consider Swift Testing, introduced with Xcode 16, for new code: parameterised tests and clearer failure messages cut boilerplate. XCTest remains necessary for UI tests and existing suites.

Integration and snapshot tests: the sweet spot

Integration tests prove the layers actually work together: the repository writes to and reads from the database correctly, a schema migration doesn't lose data, the network layer handles a 401 and retries after refreshing the token. This is where you catch bugs that mock-heavy unit tests miss.

On Android, Robolectric runs tests against the Android framework on the JVM without an emulator — an order of magnitude faster than instrumented tests. For networking we use a fake server with recorded responses, so tests don't depend on the state of staging and don't break when someone edits test data.

Snapshot tests compare a rendered screen with a reference image. They're excellent at catching visual regressions: broken padding, truncated text in a long localisation, wrong colours in dark mode. One snapshot test can check a component in ten states — light and dark theme, large font, right-to-left language — in a few seconds.

End-to-end: few, but the most important

E2E tests are the most expensive. They're slow, depend on a test environment and are the most likely to be flaky. Google found that about 1.5% of all test runs in the company produced a flaky result, and roughly 16% of tests showed some level of flakiness. Mobile UI tests usually have it worse.

So we cover only the 5–10 journeys without which the business stops:

  1. sign-up and sign-in;
  2. the core product action (ordering, booking, creating an entry);
  3. payment or subscription purchase in a sandbox;
  4. account recovery;
  5. upgrading from the previous version with existing data.

For a quick start we often pick Maestro: flows are written in YAML, work on both platforms and wait for elements automatically, which reduces flakiness. Espresso and XCUITest remain the choice for deep integration with the codebase.

How to remove flakiness

  • No fixed sleeps — only waits for a specific element state.
  • Animations disabled on test devices.
  • Every test creates its own data and doesn't depend on execution order.
  • A flaky test is quarantined immediately with a ticket to fix it, not re-run "until it passes".

What to automate first on a project with no tests

Many projects come to us with no tests at all. Writing everything at once burns the team out and halts feature work. We go in stages:

StageWhat we doDuration (estimate)Outcome
1Run tests in CI on every pull request, even if there are only a handful1–2 daysInfrastructure that keeps tests from rotting
23–5 E2E tests for critical journeys as a pre-release smoke suite3–5 daysProtection against the costliest regressions
3Unit tests for money, access rules and screen statesOngoing, 10–20% of each taskCoverage where a bug costs most
4Rule: every fixed bug gets a test that reproduces itOngoingBugs don't come back
5Snapshot tests for the design system and key screens3–7 daysControl over visual regressions

Note that stage 2 temporarily inverts the pyramid by starting at the top. It's a deliberate trade-off: in code not designed for testing, a few E2E journeys give the most protection for the least time, and unit tests arrive alongside refactoring.

Metrics: how to tell your tests are working

  • PR pipeline duration. Target: under 10–15 minutes. Any longer and developers start working around the checks.
  • Flaky test rate. If more than 1–2% of runs fail without code changes, trust in the suite collapses.
  • Production regressions. How many post-release bugs involve features that previously worked. This is the main measure of test value.
  • Code coverage. Useful as an indicator of untested areas, harmful as a KPI: an "80% coverage" mandate breeds tests that assert nothing.

Common mistakes

  1. The inverted pyramid. Hundreds of UI tests and no unit tests; the suite takes an hour and fails for a different reason every time.
  2. Testing the mocks. The test verifies the mock returned what it was told to return, not how the code behaves.
  3. Depending on staging. Tests fail whenever someone changes data on the test server.
  4. No migration tests. A database schema update that wipes user data is one of the most painful bugs, because once released it can't be rolled back.
  5. Tests nobody runs. If a suite isn't wired into CI, it goes stale within weeks.

Testing strategy checklist

  • Tests run automatically on every pull request, and failures block the merge.
  • Business logic is pulled out of the UI layer and covered by unit tests.
  • The network layer and database have integration tests, migrations included.
  • Critical journeys (sign-in, core action, payment) are covered by E2E tests.
  • Key screens have snapshot tests for dark mode and large fonts.
  • Flaky tests are quarantined with a ticket to fix them.
  • Every fixed bug gets a regression test.
  • The PR pipeline takes no longer than 15 minutes.

Sources: The Practical Test Pyramid (martinfowler.com); Android: Fundamentals of testing; Apple XCTest; Swift Testing; Google Testing Blog: Flaky Tests at Google; Maestro; Firebase Test Lab.

CI/CD for Mobile Apps: Fastlane, GitHub Actions, Code Signing and Automated Releases

CI/CD for Mobile Apps: Fastlane, GitHub Actions, Code Signing and Automated Releases

A manual mobile release usually goes like this: a developer bumps the build number, opens Xcode or Android Studio, builds an archive, tries to remember where the right certificate lives, uploads to TestFlight and Play Console, types release notes — twice a week. It takes 1–3 hours, and every step is a chance to get it wrong: the wrong keystore, a forgotten build number, a debug configuration shipped to production.

CI/CD takes the human out of that chain. Below is how we at Mosmox build pipelines for iOS and Android with Fastlane and GitHub Actions: pipeline structure, code signing, secrets management, costs, and the traps that break automation at the worst possible moment.

What a mobile CI/CD pipeline actually needs to do

A mobile pipeline differs from a web one in three ways: every build has to be cryptographically signed, iOS only builds on macOS, and "deploying" goes through store review, which you cannot roll back instantly. So we split the pipeline into three tiers:

  • CI on every pull request: linting, unit tests, a debug build. Target: an answer within 10–15 minutes.
  • Internal builds: after a merge to the main branch, a signed build goes to TestFlight (internal), Play Console internal testing or Firebase App Distribution. Testers get new versions without pinging developers.
  • Release pipeline: triggered by a tag — production build, upload to App Store Connect and Google Play, metadata, release notes, start of a staged rollout.

Fastlane: why bother when you have scripts

Fastlane is an open-source tool that wraps xcodebuild, Gradle, the App Store Connect API and the Google Play Developer API into declarative "lanes". The key actions:

ActionPlatformWhat it does
matchiOSStores certificates and profiles in an encrypted repo or cloud bucket and syncs them across developers and CI
gym (build_app)iOSBuilds and exports a signed IPA
pilot (upload_to_testflight)iOSUploads a build to TestFlight and distributes it to testers
deliver (upload_to_app_store)iOSUploads metadata and screenshots and submits for review
gradleAndroidBuilds an AAB/APK for the chosen flavor
supply (upload_to_play_store)AndroidUploads the AAB to a track, with metadata and rollout fraction

Fastlane's main value isn't doing anything the CLI can't. It's that a lane behaves the same on a developer's laptop and on CI. When the pipeline fails, you reproduce it locally with one command instead of picking apart 400 lines of YAML.

iOS signing: the number one cause of broken builds

iOS needs a development or distribution certificate plus a provisioning profile tied to the bundle ID, the certificate and (for development) a list of devices. Managing these files by hand in a team of three or more sooner or later ends with a revoked certificate and everyone's builds broken.

How we set it up

  1. Create a dedicated private repo (or bucket) for match and an encryption passphrase kept only in the secrets manager.
  2. One designated person generates certificates with match for the development and appstore types.
  3. On CI, match runs in readonly mode: it only downloads existing certificates and never creates new ones. That protects you from CI accidentally revoking a certificate.
  4. For App Store Connect access we use an API key (.p8, Key ID, Issuer ID) instead of an Apple ID and password — no two-factor prompts, no expiring sessions.
  5. CI creates a temporary keychain for the build and deletes it afterwards.

An Apple distribution certificate is valid for one year. Set a reminder a month before expiry — five minutes of renewal beats an emergency release on a Friday.

Android signing: the upload key, not the app key

Play App Signing is mandatory for new apps on Google Play: Google holds the app signing key and you sign builds only with an upload key. This matters: if the upload key is lost or compromised, it can be reset through support, whereas losing the app key under the old scheme meant you could never update the app again.

  • We base64-encode the keystore and store it in CI secrets along with passwords and alias; it never goes into the repository.
  • For Play Console access we create a Google Cloud service account with minimal permissions (releases for the specific app only) and store its JSON key as a secret.
  • The very first build of a new app is uploaded to Play Console manually — the API can't create an app from scratch.
  • For new personal developer accounts, remember the closed testing requirement: 12 testers for 14 days before production access. No automation gets around it, so put those two weeks in the launch plan.

GitHub Actions: structuring the workflows

We keep three separate workflow files rather than one do-everything file:

  • pr.yml — on every pull request: Android on a Linux runner (cheaper and faster), iOS tests on macOS only when iOS code or shared modules change (path filters).
  • beta.yml — on push to the main branch: signed builds for internal testers.
  • release.yml — on a tag such as v1.4.0: production build, store uploads, a GitHub Release with the changelog.

Build numbers without conflicts

The simplest approach is to derive the number from GITHUB_RUN_NUMBER, or from the latest TestFlight or Play Console build number plus one. A build number committed by hand guarantees merge conflicts and rejected uploads with "build number already used".

Caching

Caching Gradle, CocoaPods/SPM and DerivedData cuts build time several-fold. On our projects a typical cold iOS build takes 15–25 minutes; with a warm cache, 6–10. But the cache must be keyed on lock-file hashes, or sooner or later you get "works on CI, fails locally".

Costs and which option to choose

macOS runner minutes on GitHub Actions are billed at a much higher rate than Linux, so anything that doesn't need Xcode runs on Linux. The options compared:

OptionProsConsBest for
GitHub Actions (hosted runners)Code and CI in one place, huge action marketplaceExpensive macOS minutes, lag in new Xcode imagesMost teams up to 10 developers
Xcode CloudNative Xcode and App Store Connect integration, 25 compute hours a month included with Apple Developer Program membershipApple platforms only, less flexibleiOS-only teams
Codemagic, BitriseReady templates for Flutter / React Native, fast Mac machinesAnother vendor and invoiceCross-platform projects, teams without DevOps
Your own Mac mini as a self-hosted runnerLowest cost per minute, fast warm cacheMaintenance, Xcode upgrades, physical securityTeams with heavy build volume

Setting up a baseline pipeline for both platforms typically takes us 3–6 working days, provided the project already has tests and tidy build configurations. It pays back within weeks: a team shipping weekly saves 6–12 developer hours a month on routine alone, not counting the mistakes that never happen.

Common mistakes

  1. Secrets in the repo. A keystore, .p8 key or production config sitting in git history. Deleting the file in a new commit doesn't help — the history remains.
  2. CI with admin rights. A service account with the Admin role in Play Console, or an App Store Connect API key with the Admin role. A role that can only upload builds is enough.
  3. One giant workflow. Any README edit triggers a 40-minute iOS build.
  4. Automatic 100% release. The pipeline ships to every user at once. The production lane should start a staged rollout to a small share of users; increasing it is a human decision made after looking at stability metrics.
  5. A stale Xcode. Apple regularly raises the minimum SDK required for App Store Connect uploads. If CI is pinned to an old image, the release hits an upload error exactly when it's urgent.
  6. No artifacts. Failing to keep dSYMs and R8 mapping files means production crash reports are unreadable.

A two-week rollout plan

  1. Days 1–2. Audit the current release process: write down every manual step and where the keys live. Move all secrets into a secrets manager.
  2. Days 3–4. Fastlane locally: test, beta and release lanes per platform; match for iOS, upload key and service account for Android.
  3. Days 5–6. PR pipeline in GitHub Actions with caching and path filters.
  4. Days 7–8. Beta pipeline: automatic internal builds, CI-generated build numbers, notifications in the team chat.
  5. Days 9–10. Tag-triggered release pipeline: store uploads, dSYM and mapping retention, staged rollout start.
  6. Afterwards. Document the process in the README and run the first release as a pair so the knowledge doesn't live in one head.

Readiness checklist: no secrets in the repository; match readonly on CI; App Store Connect API key instead of an Apple ID; Play App Signing enabled; least-privilege service accounts; build numbers generated automatically; dSYMs and mapping files retained; production starts with a staged rollout; reminders set for certificate expiry.

Sources: fastlane docs; fastlane match; GitHub Actions documentation; GitHub Actions billing; App Store Connect API; Xcode Cloud; Play App Signing; Google Play Developer API.

OWASP MASVS in Practice: A Security Checklist for Your Mobile App

OWASP MASVS in Practice: A Security Checklist for Your Mobile App

When a client asks "is our app secure?", the honest answer is almost always "secure against what?". That is why at Mosmox we never start an audit with a random grab-bag of checks. We anchor it in OWASP MASVS, the industry standard for mobile app security requirements. It gives developers, testers, lawyers and the security teams of banks or insurers a shared vocabulary — and those teams increasingly make compliance a contractual condition.

This article covers how MASVS is structured since version 2, which control groups we actually check on every project, how to choose the right level of rigour, how much time to budget, and the mistakes we keep finding. We have covered general security mistakes in an earlier journal post; here the focus is a methodical, standard-based review.

MASVS, MASTG and MASWE: what each one is for

The OWASP Mobile Application Security (MAS) project consists of three linked documents:

  • MASVS (Mobile Application Security Verification Standard) — high-level requirements: what must be ensured, e.g. "the app securely stores sensitive data".
  • MASTG (Mobile Application Security Testing Guide) — the hands-on manual: how to verify it on Android and iOS, with tools, commands and code samples.
  • MASWE (Mobile Application Security Weakness Enumeration) — a catalogue of concrete weaknesses that links abstract requirements to tests.

Version 2.0 (2023) simplified the standard dramatically: dozens of granular items were removed, and the old L1/L2/R levels are no longer part of the standard itself. MASVS now describes requirements, while testing profiles (L1, L2, R, P) live in MASTG. For a business, this means that a "MASVS L2" clause in an old tender document needs translating into current terminology — otherwise vendor and client will mean different things.

Eight control groups and what sits behind them

Current MASVS has eight groups. Here is how we explain them to the team and what we check first.

GroupCoversWhat we check first
MASVS-STORAGEOn-device data storageTokens only in Keychain / Android Keystore-backed storage; no personal data in logs, WebView caches or backups
MASVS-CRYPTOCryptographyNo home-grown algorithms, no hardcoded keys, modern modes (AES-GCM), proper random number generation
MASVS-AUTHAuthentication and authorizationPermissions enforced on the server, not the client; biometrics bound to a cryptographic key; proper session termination
MASVS-NETWORKNetwork communicationTLS only, no ATS or cleartext exceptions, a deliberate decision about certificate pinning
MASVS-PLATFORMInteraction with the OS and other appsExported activities, deep links, WebViews with JavaScript bridges, IPC, screenshot protection on sensitive screens
MASVS-CODECode quality and dependenciesInput validation, up-to-date SDKs, minimum OS version, a forced-update mechanism
MASVS-RESILIENCEResistance to reverse engineeringObfuscation, root/jailbreak and tamper detection, integrity checks via Play Integrity / App Attest
MASVS-PRIVACYPrivacyData minimisation, transparency, user control; consistency with the Privacy Manifest and Data safety form

The PRIVACY group arrived in version 2.1 (2024), which makes sense: Apple's Privacy Manifest requirements and Google Play's Data safety section turned privacy into something verifiable rather than aspirational.

Choosing a profile: L1, L2, R or P

The most expensive mistake is applying banking-grade requirements to a habit tracker, or the reverse. MASTG profiles let you scale the effort:

  • L1 — baseline security for any app. This is hygiene we treat as mandatory even for an MVP.
  • L2 — defence in depth for apps handling sensitive data: finance, health, government services, corporate access.
  • R — resilience against reverse engineering and client tampering. Needed when the value lives in the client itself: games with in-app economies, DRM content, anti-bot protection.
  • P — privacy; relevant to anyone processing personal data.

Our rule of thumb: L1 + P always; L2 if one user's data leaking means direct financial or medical harm to them; R if an attacker can profit from a modified client. R without L2 rarely makes sense — obfuscation will not save you if the server trusts the client.

Step by step: how we run an audit

Step 1. A one-page threat model

Before any testing we write down which data is valuable (tokens, payment data, medical records), who the attacker is (someone holding an unlocked phone, a malicious app on the same device, a public Wi-Fi attacker, a competitor decompiling the APK) and what the consequences would be. Without this, the report becomes a list of "findings" nobody knows how to prioritise.

Step 2. Static analysis

We decompile the build (jadx for Android, IPA analysis for iOS) and look for API keys, staging URLs, disabled certificate validation and debug flags. In parallel we run automated scanners such as MobSF — they surface the obvious quickly but produce plenty of false positives, so every finding is verified by hand.

Step 3. Dynamic analysis

We install the app on a rooted or jailbroken device, intercept traffic through a proxy and instrument it with Frida. We check what sits in the sandbox after login and after logout, what lands in the system log, and whether internal screens open via a deep link without authentication.

Step 4. Testing the backend from the client's side

Most critical findings in mobile audits are actually server-side: the API returns extra fields, lets you modify someone else's resource by swapping an ID (IDOR), or doesn't rate-limit OTP attempts. MASVS explicitly requires authorization to happen on the server, so we consider a mobile audit without API testing incomplete.

Step 5. Report and retest

Every finding gets a MASVS group and MASTG test reference, a severity rating and a concrete recommendation. A retest after fixes is mandatory: in our experience roughly one in five "fixes" addresses the symptom rather than the cause.

How long it takes

The estimates below are guidelines from our own practice for a mid-complexity app (20–40 screens, one platform). For two platforms budget roughly 1.6–1.8×, since part of the work (API, threat model) is shared.

ScopeDurationWhen it fits
Team self-review against an L1 checklist1–2 daysBefore every major release
External L1 + P audit3–5 daysBefore public launch or a funding round
L2 audit including the API7–12 daysFintech, healthtech, enterprise apps
L2 + R with protection-bypass testing10–20 daysPayment services, games with economies, DRM

An automated scanner in CI costs next to nothing and catches regressions, but it does not replace a manual audit: it cannot see broken authorization logic, which is exactly what hurts most.

The mistakes we find most often

  1. Secrets in the client. Third-party API keys that unlock paid services or other people's data. Anything shipped in the build should be treated as public — obfuscated or not.
  2. Tokens in insecure storage. SharedPreferences or UserDefaults instead of Keychain/Keystore; refresh tokens that never expire.
  3. Logs with personal data. Request bodies with phone numbers, addresses or tokens left over from debugging, ending up in system logs or a third-party analytics tool.
  4. Trusting the client. Price, discount, user role or subscription status sent from the app and never validated server-side.
  5. Open Android components. An activity with exported="true" that opens an internal screen without checking the session.
  6. Unrestricted WebViews. JavaScript enabled, a native bridge and arbitrary URL loading — the classic path to running someone else's code inside your app's context.
  7. Box-ticking pinning. Certificate pinning with no rotation plan: one day the app stops working for every user. Pinning makes sense at L2, but only with a backup key and a way to update the configuration.
  8. No forced update. When a vulnerability is found, old versions live on for years. MASVS-CODE explicitly calls for a mechanism that makes users update.

Making MASVS part of the process, not a one-off audit

A one-off audit is a snapshot of a single day. To keep security from decaying, we build MASVS into the normal development cycle:

  • Definition of Done. Tasks touching authentication, storage or networking get 3–5 relevant L1 items in the pull request checklist.
  • CI automation. Dependency scanning for known vulnerabilities, secret detection in the repository and static analysis of every release build.
  • Device attestation. For L2/R — the Play Integrity API on Android and App Attest on iOS, with the verdict checked on the server, not in the app.
  • Cadence. A full audit once a year or after significant architectural changes (a new payment provider, a new sign-in method).

An L1 checklist to start with

  • Tokens and keys are stored only in Keychain / Android Keystore.
  • The release build has no debug logs containing personal data or tokens.
  • Backups contain no sensitive data (allowBackup / backup rules configured on Android, file protection attributes on iOS).
  • All traffic is TLS; no unjustified ATS exceptions or cleartext traffic.
  • The build contains no secrets granting access to paid services or data.
  • Authorization and business rules (prices, roles, subscriptions) are enforced on the server.
  • Exported components and deep links cannot open protected screens without a session.
  • WebViews don't load arbitrary URLs and expose no unnecessary JavaScript bridges.
  • Dependencies are up to date with no known critical vulnerabilities.
  • A forced-update mechanism exists for the minimum supported version.
  • The Privacy Manifest and Data safety form match what the app actually collects.

If three or more of these items fail today, fix them before commissioning an in-depth audit: an external specialist will find the same things, just at a higher price.

Sources: OWASP MASVS; OWASP MASTG; OWASP MASWE; Android: Security guidelines; Apple Security documentation; Play Integrity API; Apple DeviceCheck / App Attest.

Secrets in Mobile Apps: Keychain, Android Keystore and What Never Belongs in the Build

Secrets in Mobile Apps: Keychain, Android Keystore and What Never Belongs in the Build

Every mobile build is a file you voluntarily hand out to millions of people. An IPA or APK can be unpacked, its strings extracted in a minute, and its traffic inspected through a proxy on your own device. So the core security rule is blunt: treat everything in the build as public. Obfuscation makes analysis harder, but it does not turn a key into a secret.

At the same time, the app needs somewhere to keep session tokens, local encryption keys and user credentials. That is what the system stores are for: Keychain on iOS and Android Keystore. This article covers what may and may not go into code, how to use the system stores correctly and how to design an architecture in which real secrets never reach the device at all.

Why "hiding the key in code" does not work

It is no accident that first place in the OWASP Mobile Top 10 (2024) goes to M1: Improper Credential Usage, which includes keys hardcoded into the app. Here are the usual ways secrets get "hidden" and why they fail:

Hiding methodHow it is bypassedTime for an experienced analyst
String in code or Info.plist / strings.xmlUnpack the archive and search stringsMinutes
BuildConfig, .xcconfig, build variablesThe same values end up in the binaryMinutes
Base64 or XORDecode once the routine is foundMinutes to hours
Native library (NDK, C)Disassembler, or hooking the call on a rooted deviceHours
Fetching the key from a server at launchIntercepting traffic or process memoryHours

The time estimates come from our practical penetration-testing experience, not a formal metric. The point is that each approach raises the cost of an attack without changing the model: a key the app uses is available to whoever controls the device.

What may and may not ship in the build

Value typeIn the build?Condition or alternative
Firebase config (apiKey, projectId)YesIdentifiers, not secrets; access is enforced by Security Rules and App Check
Google Maps / Places SDK keyYes, restrictedRestrict by package name + SHA-1 / bundle ID and by API list
Public key for pinning or signature checksYesPublic by definition
Payment provider publishable keyYesOnly for client-side operations the provider intends
Payment provider secret keyNoBackend only
Cloud keys (AWS, GCP service account)NoBackend, or temporary least-privilege credentials
LLM / AI API keysNoProxy through the backend with authentication and limits
OAuth client secretNoPKCE for a public client, backend exchange if needed
JWT signing key, admin tokens, DB passwordsNo, neverServer only, in a secrets manager

Firebase states plainly in its documentation that Firebase API keys are not secrets and can be included in code, with protection provided by security rules. For Google Maps keys, Google recommends application and API restrictions and separate keys per platform.

A word on AI keys. An LLM API key inside an app is a direct route to a bill of thousands of dollars: it will be extracted and used for someone else's requests. Always proxy such calls through your backend, tied to a user, with limits and monitoring.

An architecture with no secrets on the device

The right question is not "how do I hide the key" but "how do I make the client not need it".

  1. The backend as intermediary. The app authenticates the user, gets their token and calls your API. Your server calls third-party services with its own secrets.
  2. Short-lived credentials. If the client needs direct access (say, uploading a file to object storage), the backend issues a signed URL or a token valid for minutes with minimal permissions.
  3. App integrity checks. App Attest on iOS and the Play Integrity API on Android let the server confirm a request comes from a genuine, unmodified copy of the app on a real device. That is not a secret in the build but a cryptographic attestation from the platform.
  4. Limits and monitoring. Even "public" keys deserve quotas and alerts on unusual usage.

iOS: Keychain and the Secure Enclave

Keychain Services is the system's encrypted store for small secrets: tokens, passwords, keys. Data is encrypted with hardware-protected keys and accessible only to your app (or an app group via Keychain Sharing).

The accessibility class is the key setting

The kSecAttrAccessible attribute determines when an item can be read (Apple documentation):

  • WhenUnlocked: only while the device is unlocked. Right for most data used on screen.
  • AfterFirstUnlock: after the first unlock since reboot. Needed if the token is used in the background (background refresh, push handling).
  • WhenPasscodeSetThisDeviceOnly: only if a passcode is set; the item is deleted if the passcode is removed.
  • The ThisDeviceOnly suffix keeps the item out of backups restored to other devices. For session tokens this is usually the right choice.

For sensitive actions, add access control with biometrics (SecAccessControl with .biometryCurrentSet): the item then cannot be read without Face ID or Touch ID, and access is invalidated when biometric enrolment changes.

For keys that must never leave the device, use the Secure Enclave: the private key is generated inside the coprocessor and cannot be exported; the app only asks it to sign or decrypt. The limitation: the Secure Enclave supports P-256 elliptic curve keys.

An often forgotten nuance: in practice Keychain items can survive app deletion. If users are unexpectedly signed in after reinstalling, clear the Keychain on first launch, keyed off a flag in UserDefaults.

Android: Keystore and data encryption

The Android Keystore stores cryptographic keys so their material never enters the app process: encryption and signing are performed by the system, on most modern devices in a hardware environment (TEE), and on devices with StrongBox (Android 9+) in a separate secure chip.

A typical scheme for tokens

  1. Create an AES key in the Keystore via KeyGenParameterSpec for encryption and decryption, in GCM mode.
  2. Encrypt the token with that key and store the ciphertext in DataStore or a file.
  3. For sensitive operations enable setUserAuthenticationRequired so the key works only after biometrics or a PIN (via BiometricPrompt with a CryptoObject).
  4. Where available, request StrongBox (setIsStrongBoxBacked) and provide a fallback when it is not.

An important change: Google deprecated the Jetpack Security library (EncryptedSharedPreferences, MasterKey) in 2025 in favour of platform APIs and direct use of the Keystore. Do not rely on it in new projects, and plan a migration in existing ones.

Backups

Keystore keys are not backed up, but data encrypted with them can be. After a restore on a new device, the app gets ciphertext without a key. Exclude such files via dataExtractionRules / fullBackupContent (Auto Backup) and handle decryption failures gracefully: clear the data and ask the user to sign in again.

Secrets in the repository and CI

Many leaks come not from the build but from git: a key committed "temporarily" stays in history forever.

  • Enable secret scanning: GitHub secret scanning with push protection, or gitleaks in pre-commit hooks and CI.
  • Keep environment configuration out of the repository; in CI, use encrypted variables or a secrets manager.
  • Store signing keys (the Android keystore, iOS certificates) separately, with restricted access and a backup. A lost Android upload key can be recovered through Play App Signing, but it is a support procedure.
  • If a secret reaches the repository, rotate it. Rewriting history does not help if someone already cloned it.

Common mistakes

  • Tokens in UserDefaults or plain SharedPreferences.
  • A payment or AI provider secret key in app code "because it is faster for the MVP".
  • Logging the Authorization header or token-bearing responses in release builds; tokens in crash reports and analytics.
  • The deprecated "Always" Keychain accessibility class, or AfterFirstUnlock with no background need.
  • No handling for a Keystore key becoming invalid (screen lock changed, new biometrics enrolled).
  • Google Maps keys without application restrictions.
  • Relying on obfuscation to protect secrets.

Secrets audit checklist

  1. Unpack your own release build and search for strings such as key, secret, token, sk_, AKIA.
  2. Build a register of every key in the build: purpose, whether it is a secret, which restrictions apply.
  3. Move every real secret to the backend; restrict client keys by application and quota.
  4. Tokens only in the Keychain (ThisDeviceOnly) or encrypted with a Keystore key.
  5. Add App Attest / Play Integrity for critical endpoints.
  6. Check logs, crash reports and analytics for tokens and personal data.
  7. Set up secret scanning in the repository and CI; rotate anything that ever landed there.
  8. Compare the implementation against the MASVS-STORAGE and MASVS-CRYPTO groups of OWASP MASVS.

Which tokens the app receives and how to refresh them is covered in our article on OAuth 2.0 + PKCE.

Sources: OWASP Mobile Top 10 (2024); OWASP MASVS; Apple: Keychain Services; Apple: Restricting keychain item accessibility; Apple: Protecting keys with the Secure Enclave; Android Keystore system; AndroidX Security release notes; Android Auto Backup; Firebase: API keys; Google Maps Platform: API security best practices; Apple: App Attest; Play Integrity API; GitHub: Secret scanning.

Mobile App Authentication: OAuth 2.0 with PKCE, Access and Refresh Tokens

Mobile App Authentication: OAuth 2.0 with PKCE, Access and Refresh Tokens

Authentication is one of the few parts of a mobile app where "works" and "correct" can be very far apart. Sign-in through a WebView that can read the password, a refresh token living forever in SharedPreferences, several parallel token refreshes that end up signing the user out: all of these "work" until the first security audit or the first incident.

This article is a practical walkthrough of OAuth 2.0 with PKCE for native apps: what the flow looks like, why WebViews are off the table, how to choose token lifetimes, how to refresh without race conditions and what to do on sign-out. It is grounded in current IETF standards, primarily RFC 8252 and RFC 9700.

Why a mobile app is a "public client"

In classic OAuth a server-side application holds a client secret stored on the server. A mobile app cannot keep a secret: any string in the build can be extracted by decompilation in minutes. So the specification classifies native apps as public clients, and RFC 8252 (OAuth 2.0 for Native Apps) requires two things: use an external user agent (the system browser) and protect the code exchange with PKCE.

The takeaway for the team is simple: no client secret in the mobile build. If a provider insists on one, the code-for-token exchange must happen through your backend.

Authorization Code + PKCE, step by step

  1. The app generates a code_verifier, a random 43–128-character string, and computes code_challenge = BASE64URL(SHA-256(code_verifier)), as described in RFC 7636. Avoid the plain method.
  2. It opens the authorisation page in the system browser with client_id, redirect_uri, scope, state, code_challenge and code_challenge_method=S256.
  3. The user signs in on the provider's page: password, passkey, 2FA, Google or Apple sign-in. The app never sees these details.
  4. The provider redirects to redirect_uri with a one-time authorisation code and the state. The app checks that the state matches what it sent.
  5. The app exchanges the code for tokens, including the original code_verifier. The server checks that its hash matches the code_challenge.
  6. The app receives an access token, a refresh token and, with OpenID Connect, an ID token, and stores them in secure storage.

PKCE solves a specific problem: if a malicious app intercepts the redirect carrying the code (for example by registering the same custom URL scheme), it cannot redeem the code without the code_verifier, which never left your app's memory.

System browser, not a WebView

An embedded WebView gives the app full control over the sign-in page: it can read the typed password and the cookies. That is why RFC 8252 explicitly rules it out for authorisation, and since 2021 Google has blocked Google sign-in in embedded WebViews. The right tools:

PlatformToolWhat you get
iOSASWebAuthenticationSessionA system browser sheet, optional Safari cookie sharing, return via callback
AndroidCustom TabsA browser tab over the app, with the browser's password manager and passkeys
BothAppAuth librariesA ready-made flow implementation, PKCE, redirect handling

On iOS that is ASWebAuthenticationSession, on Android Custom Tabs, and the open-source AppAuth libraries implement the whole flow on both platforms. A bonus for users: password managers and saved sessions work, so sign-in gets faster.

Redirect URI

The safest option is a domain-verified HTTPS link: Universal Links on iOS and App Links on Android. RFC 8252 permits a custom scheme (com.example.app:/callback), but another app can register it too, which is exactly why PKCE is mandatory. Use a reverse-domain scheme rather than something short like myapp://.

Access and refresh tokens: lifetime and rotation

The access token is short-lived and sent with every API request. The refresh token lives longer and is used only to obtain new access tokens. Exact values depend on the product's risk profile; these are the guidelines we use:

Product typeAccess tokenRefresh tokenExtra measures
Content, media, social15–60 min30–90 days, slidingRefresh token rotation
E-commerce, delivery10–30 min30–60 daysRe-authentication to change payment details
Finance, health5–15 minHours to days, absolute session capBiometrics for sensitive actions, device binding

RFC 9700 (OAuth 2.0 Security Best Current Practice) recommends that public clients either bind refresh tokens to a client key (for example with DPoP) or use rotation: every refresh issues a new refresh token and invalidates the old one. If the server sees an already invalidated token being reused, that signals theft and the whole token family should be revoked.

Refreshing without race conditions

A typical bug we find in audits: on returning from the background the app fires five requests at once, all get 401, and all five refresh the token in parallel. With rotation, the first gets a new refresh token, the other four present the invalidated one, the server detects "reuse" and signs the user out.

The correct pattern

  1. All requests go through one HTTP client with an interceptor (OkHttp Authenticator on Android, a wrapper around URLSession on iOS).
  2. On 401 the interceptor checks whether a refresh is already in progress. If so, it waits for that result instead of starting another (mutex, actor or single-flight).
  3. After a successful refresh, all queued requests are retried with the new access token. Each request is retried at most once.
  4. If the refresh fails with invalid_grant, clear the tokens and send the user to sign-in while preserving context (where they were heading).
  5. Do not confuse a network error during refresh with invalid_grant: never sign a user out just because they are offline.

A useful optimisation is proactive refresh: if the access token expires in under a minute, refresh it before the request rather than after a 401.

Storing tokens

Tokens are secrets and must be stored accordingly: Keychain on iOS, Android Keystore (for example, a key that encrypts the storage) on Android. Never UserDefaults, plain SharedPreferences, logs, analytics or crash reports. Make sure the debug HTTP logger does not ship in release builds and does not print the Authorization header. We will cover storage in depth in a separate article on Keychain and Keystore. Baseline authentication and storage requirements are collected in OWASP MASVS (the MASVS-AUTH and MASVS-STORAGE groups).

Sign-out and revocation

  • Revoke the refresh token on the server via the revocation endpoint (RFC 7009), not just delete it from the device.
  • Clear local data: caches, database, user files, the push token on the backend.
  • End the browser session if SSO is used; otherwise the next sign-in silently reuses the same account, which surprises users on shared devices.
  • Let users end other sessions from settings: a device list and a "Sign out everywhere" button.
  • After a password change, revoke every refresh token except the current one.

Common mistakes

  • Sign-in in a WebView, or a native form sending the password straight to the OAuth server (Resource Owner Password Credentials, a grant RFC 9700 says must not be used).
  • The implicit flow with a token in the URL fragment: deprecated and not recommended.
  • A client secret in app code or a build configuration file.
  • No state check, or PKCE with the plain method.
  • A non-expiring refresh token without rotation.
  • Parallel token refreshes that sign the user out.
  • Signing out on any network error during refresh.

Implementation checklist

  1. Authorization Code + PKCE (S256), state validation.
  2. System browser: ASWebAuthenticationSession / Custom Tabs, or AppAuth.
  3. Redirect via Universal Links / App Links or a reverse-domain scheme.
  4. No secrets in the build; confidential exchanges go through the backend.
  5. Short-lived access tokens, refresh token rotation with reuse detection.
  6. Single-flight refresh in the network layer, one retry per request.
  7. Tokens only in Keychain / Keystore, never in logs or analytics.
  8. Server-side revocation on sign-out, "sign out everywhere", revocation after a password change.
  9. Tests: expired token, parallel 401s, sign-out while offline, returning from the background after a week.

Sources: RFC 8252: OAuth 2.0 for Native Apps; RFC 7636: PKCE; RFC 9700: OAuth 2.0 Security Best Current Practice; RFC 7009: Token Revocation; RFC 9449: DPoP; Apple: ASWebAuthenticationSession; Chrome Custom Tabs; AppAuth; Google: OAuth in embedded WebViews; OWASP MASVS.

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.

Jetpack Compose 1.13: What Is Deprecated, What Changed and What to Migrate Now

Jetpack Compose 1.13: What Is Deprecated, What Changed and What to Migrate Now

On 18 November 2026 stable Jetpack Compose 1.13 shipped (BOM 2026.11.01). It is not only about new effects: the release deprecates several familiar tools and changes how clickable elements behave. Below we go through what to migrate now and what can wait.

All facts below come from the Android Developers Blog post.

Upgrade requirements

Moving to BOM 2026.11.01 requires Kotlin 2.2 or newer and compileSdk 37.1. If a project is still on an older toolchain, start the upgrade there:

implementation(platform("androidx.compose:compose-bom:2026.11.01"))

What is deprecated

WhatWhat changedWhat to move to
Value-based BasicTextField and Material 2 TextFieldOfficially deprecatedState-based BasicTextField with TextFieldState; in Material 3 the value-based overloads are not deprecated yet, but Google recommends migrating
VisualTransformationDeprecatedOutputTransformation and InputTransformation
Compose Material 2Deprecated and no longer actively maintainedMaterial 3 1.5.0
ConstraintLayout and MotionLayout in ComposeDeprecated (the constraintlayout-compose artifact)Modern Compose layout and animation tools, including the Shared Element APIs
Modifier.onFocusedBoundsChangedImplementation removed; the modifier has no effectFocusTargetModifierNode.getFocusedRect(), onFocusChanged, BringIntoViewRequester

Built-in scrolling containers such as LazyColumn and Modifier.verticalScroll already bring focused content into view, so the removed modifier does not affect them.

What was added

  • FlexBox and Grid are stable. FlexBox gained maxItemsInEachLine and, according to Google, supersedes FlowRow and FlowColumn in new code.
  • computedStateOf is a lighter alternative to derivedStateOf for condition checks and filtered state computed from frequently changing values such as scroll position. It does not cache the result, so it has less overhead. Keep derivedStateOf for heavy calculations or where caching is needed.
  • Stable LazyLayoutCacheWindow. Window-based prefetching replaces item-based prefetching in lists, grids and staggered grids; the cache window settings moved from rememberLazyListState into the layout composables themselves.
  • Progressive blur, PolygonShape and MorphPolygonShape. Blur properties can be set directly on DialogProperties.
  • CapturedAnimatedVisibility. It animates a snapshot of the last frame instead of keeping state alive, which helps when data disappears immediately (for example closing a details pane sets the selected item to null). In Google's benchmarks, frame time during exit is 7–8% faster than with AnimatedVisibility.
  • TestFailurePolicy. It automatically saves a screenshot and the semantics tree when a UI test fails, which is handy in CI.
  • Material 3 1.5.0. Experimental annotations dropped from 120 to 58; Slider and RangeSlider moved to SliderState.

Behavior change: click sounds

Elements using Modifier.clickable (and components built on it) now automatically play standard Android interaction sounds, respecting the user's system sound settings. If you previously triggered such sounds manually or deliberately avoided them, check screens with clickable elements after the upgrade.

Performance: what the numbers say

Google states that on a Pixel 6, Compose 1.13 matches version 1.12.1 on baseline startup and scrolling benchmarks with a 0% jank rate. Cold start Time to Initial Display is 147.65 ms for Compose versus 152.87 ms for Views. Views are still faster on Time to Full Display (180.32 ms versus 202.79 ms for Compose), and P50 scrolling frame duration is 3.51 ms for Compose versus 3.06 ms for Views.

On the tooling side there is Perfetto recomposition tracing (recording state reads and writes) and a static analysis performance skill available through Android CLI. Google warns that recomposition tracing adds overhead, so disable it when measuring performance.

Migration plan

  1. Update the toolchain: Kotlin 2.2+ and compileSdk 37.1, then BOM 2026.11.01.
  2. Find deprecated APIs: value-based text fields, ConstraintLayout in Compose, Material 2, onFocusedBoundsChanged.
  3. Start with text fields: moving to TextFieldState changes the state model, so do it as a separate step.
  4. Walk through clickable screens: check the new system sounds.
  5. Measure: compare startup and scrolling before and after on real devices.

Two experimental tracks are worth knowing about: the Styles API remains experimental, and the androidx.web:web:1.0.0-alpha01 library and the A2UI renderer (material3-a2ui:1.0.0-alpha02) are still alpha, so do not plan production work on them.

Conclusion

Compose 1.13 does not break an app out of the box, but it clearly shows what will be removed next: value-based text fields, Material 2 and ConstraintLayout in Compose. It is better to plan the migration across the next sprints than to do it all at once alongside other changes.

Need help migrating a Compose app or an audit of your UI code? Get in touch: we will look at the project and propose a plan.

Black Friday and the Holidays: Preparing Your App and Backend for Peak Load

Black Friday and the Holidays: Preparing Your App and Backend for Peak Load

In 2026 Black Friday falls on 27 November and Cyber Monday on the 30th, followed without a break by Christmas and New Year sales. For e-commerce, delivery, ticketing and fintech apps these are the weeks when traffic can multiply within minutes and every minute of downtime costs real money. The worst part is that peak-time problems are rarely new: they existed all year, and the load simply exposed them.

Below is a practical plan for preparing the mobile client and the backend: what to measure, how to run load tests, which safeguards to build into the app and how to organise on-call on the day. If you are reading this a week before the peak, skip straight to "Short on time".

Why a mobile app breaks differently from a website

A website can be fixed with a five-minute deploy. A mobile app cannot: the fix must pass review, and users take days or weeks to update. According to Apple, on average 90% of submissions are reviewed in less than 24 hours, but "on average" does not mean "guaranteed on Friday morning". So anything you might need to change during the peak has to be server-controlled.

The second difference is that clients generate load themselves. Millions of devices opening the app after the same push, or thousands of clients aggressively retrying after an error, can take down a backend harder than real shoppers. The Google SRE Book describes this as cascading failure: overload in one service, amplified by retries, spreads across the whole system.

Preparation timeline

WhenWhat we doOutcome
6–8 weeks outPeak forecast, bottleneck audit, load test planTarget RPS and a risk list
4–6 weeks outLoad tests, query optimisation, caching, autoscaling tuningConfirmed capacity headroom
3–4 weeks outLast release with safeguards: kill switch, backoff, degradationA server-controlled app
2 weeks outCode freeze for mobile releases and infrastructure changesA stable version on most devices
1 week outDress rehearsal, runbook, on-call rota, warn providersThe team knows what to do
The dayWar room, dashboards, controlled push campaignsFast incident response

Why ship the last feature release 3–4 weeks ahead? So the version with safeguards has time to spread. With a phased release on the App Store, an update rolls out via automatic updates over 7 days (1%, 2%, 5%, 10%, 20%, 50%, 100%); on Google Play a staged rollout is controlled manually. And some users never enable automatic updates.

Step 1. Forecast the load and set targets

  1. Use historical data. Last year's peak requests per second (RPS), hourly dynamics, the share of mobile traffic.
  2. Factor in audience growth and marketing. Planned pushes, e-mails and ads. A push to the whole base creates a wall of traffic within minutes.
  3. Add headroom. The practical guideline we use: test at 2–3× the forecast peak.
  4. Define SLOs for the critical path. For example, catalogue API p95 ≤ 300 ms, checkout 5xx error rate ≤ 0.5%.

The critical path is not the whole app. For a store it is launch, catalogue, product page, cart, payment and order status. Recommendations, reviews and wishlists can degrade without losing revenue. Remember that according to the Baymard Institute around 70% of carts are abandoned even on ordinary days; a slow checkout at peak only makes that worse.

Step 2. Load-test the backend

Tools such as k6, Gatling or Locust let you script realistic behaviour. The key is to test mobile client scenarios, not isolated endpoints.

Test typeWhat it checksWhat to watch
Load testStability at the forecast peak for 30–60 minp95/p99 latency, error rate, database utilisation
Stress testThe breaking point and behaviour beyond itGraceful degradation versus total failure
Spike testA sudden jump, as after a mass pushAutoscaling speed, cold starts, connection queues
Soak testSeveral hours under loadMemory leaks, exhausted pools, growing queues

Typical bottlenecks we find

  • The database. Unindexed queries, N+1 in lists, an exhausted connection pool. The database usually breaks first.
  • The app's startup request. One heavy configuration endpoint called by every client at launch is a perfect candidate for a CDN and caching.
  • Third-party services. Payment, SMS, search and recommendation providers have their own limits. Warn them about the peak and confirm quotas in advance.
  • Autoscaling. New instances take minutes to start while a spike lasts seconds. Raise the minimum instance count for the peak period ahead of time.

Step 3. Safeguards in the mobile client

These must be in the app before code freeze; you cannot add them on the day.

Retries with exponential backoff and jitter

If the client retries immediately after an error, thousands of devices hit an already struggling server in sync. The right approach is exponential backoff (1 s, 2 s, 4 s…) with random jitter and a cap on attempts. The AWS Architecture Blog shows in detail why jitter matters. Retry only idempotent requests; for order creation use an idempotency key so that a retry does not create a duplicate.

Respect 429 and Retry-After

An overloaded server should return 429 Too Many Requests with a Retry-After header, and the client should honestly wait that long while showing a clear message rather than an endless spinner.

Remote config and a kill switch

With Firebase Remote Config or your own config endpoint you should be able to switch off heavy features (recommendations, live chat), lengthen refresh intervals, put the app into a "catalogue and checkout only" mode and show a maintenance banner. Check that every flag actually works, not just that it exists in code.

Circuit breakers and graceful degradation

The circuit breaker pattern, on the backend and in the client, stops calling a service that keeps failing. The app shows cached data or a simplified screen instead of a full-screen error. Google SRE advises designing systems that, under overload, shed load in a controlled way instead of collapsing entirely.

Step 4. Push campaigns without self-sabotage

A push to a million users at midnight is the easiest way to DDoS your own backend. What helps:

  • Send in waves by segment, 5–15 minutes apart, rather than to everyone at once.
  • Make the push tap open cached or static content and load personal data afterwards.
  • Mind provider limits: FCM throttles fan-out rate and messages per device.
  • Agree the push schedule with the infrastructure team, not just marketing.

Step 5. The day: monitoring and response

MetricWhere to lookAction signal (example threshold)
5xx rate on the critical pathAPM / API logs> 1% for 5 min
Checkout p95 latencyAPM> 2× baseline
Crash-free sessionsCrashlytics / SentryDrop of 0.5 pp from normal
Payment conversionProduct analyticsSharp drop while traffic grows
Database and pool utilisationInfrastructure monitoring> 80% sustained
Payment provider errorsIntegration logs, status pageAny rise in declines

Prepare a runbook: for every scenario (database down, payment provider failing, a 429 surge) define who decides, which flags to flip and what to tell users. Assign on-call engineers to each shift and a communication channel. "Turn off recommendations" should take a minute to decide, not half an hour of debate.

Common mistakes

  • Shipping a new feature the day before the peak. Any change in this window is a risk that does not pay off.
  • Testing only on staging with an empty database. A query that takes 5 ms over thousands of rows can take seconds over tens of millions.
  • Aggressive client retries. Without backoff, your app becomes the attacker.
  • Untested flags. A kill switch that does not work in older app versions is useless.
  • Forgotten third-party limits. Your backend held, but the SMS provider or geocoder started refusing.
  • No retrospective. Capture metrics and decisions after the peak, or next year starts from scratch.

Short on time: the minimum checklist

  1. Freeze releases and infrastructure changes until the peak is over.
  2. Raise minimum instance counts and check your cloud provider's limits.
  3. Cache startup config, catalogue and banners on a CDN.
  4. Warn your payment provider, SMS service and other integrations about the expected peak.
  5. Verify which remote flags actually work in the versions users have installed.
  6. Split push campaigns into waves.
  7. Set alerts on 5xx, latency, crash rate and conversion; assign on-call.
  8. Prepare user-facing messages in case of an outage.

Sources: Google SRE Book: Handling Overload; Google SRE Book: Addressing Cascading Failures; AWS: Exponential Backoff and Jitter; Martin Fowler: Circuit Breaker; RFC 6585: 429 Too Many Requests; App Store Connect: phased release; Google Play: staged rollouts; Apple: App Review; Firebase Remote Config; Firebase Cloud Messaging: throttling and quotas; Grafana k6; Baymard Institute: cart abandonment rate.

R8 Keep Rules and DEX Optimization: How Third-Party Libraries Block Google Play's Requirement

R8 Keep Rules and DEX Optimization: How Third-Party Libraries Block Google Play's Requirement

In February 2027 Google Play will start requiring a minimum level of code optimization from large apps and games. We are talking about DEX code: at least 25% optimization, obfuscation and shrinking for every upload to Play Console. It sounds like the app team's own business, but there is a catch: the result depends on more than your code. It is also affected by the keep rules that third-party libraries ship with themselves.

On 17 November 2026 the Android Developers team published a guide for library authors explaining how overly broad rules block optimization in apps. Here is what it means for your product and how to check your dependencies before the deadline.

What Google Play requires

According to the Google Play help page, the new requirement applies from February 2027 and covers all form factors:

  • a minimum of 25% optimization, obfuscation and shrinking for uploads to Play Console;
  • it applies only to apps with more than 10 MB of DEX code and games with more than 50 MB of DEX code; smaller projects are not required to optimize;
  • the numbers for each app bundle are visible in the app bundle explorer in Play Console (Release → Releases overview); builds from CI/CD may differ slightly from the uploaded one;
  • the tool is not prescribed: any shrinker or optimizer works, such as R8, and Google recommends the R8 Configuration Analyzer for tuning.

Google stresses that Play requirements are not optional: failing to meet one "can affect an app's visibility and publishing capabilities" on Google Play. The page does not list separate penalties for DEX optimization specifically.

Why dependencies can block the result

R8 removes unused code, optimizes the rest and obfuscates names. But it can only work within the limits set by keep rules. And you are not the only one writing them: libraries ship consumer keep rules embedded in the AAR or JAR so that R8 does not remove classes the library reaches through reflection or JNI.

The problem is that library authors often play it safe. To keep an SDK from crashing on a removed class, they add a rule for an entire package. A typical example from Google's guide:

-keep public class com.google.android.gms.** { *; }

A rule like this makes R8 keep everything in the package, even if the app uses only a tiny part of it. If you yourself restricted another GMS library to a narrow rule, the SDK's broad rule overrides yours. According to Google, the result is a bloated app, slower startup, more memory use, a bigger download and a higher ANR rate. And the numbers in Play Console reflect the combined impact of the rules from your code and from your libraries.

What Google advises library authors, and what you should check

PracticeThe ideaWhat to check in your project
Narrow rulesDescribe only what the library reaches through reflection; for dynamic access the entry point is enough, and R8 handles the restWhether your dependencies ship rules like com.vendor.**
Codegen instead of reflectionSerialization and dependency injection work better with code generation (Hilt is an example): R8 sees code usage at build timeWhich libraries still rely on reflection
Conditional keep rulesFor example for ad mediation adapters: keep a format only if the matching adapter is includedWhether you pull in ad adapters you do not need
Rules in the library, not in documentationConsumer rules have been supported in AARs and JARs for years; rules in documentation create manual work and leftovers of obsolete rulesWhether your proguard-rules.pro still contains "README recipes" that are no longer needed
JNI targetsSDKs with native code (games, photo and video editors) need rules for every class used through JNIIf you use Unity or Unreal, check the plugins

Google also advises against using keepnames just to get readable stack traces: Firebase Crashlytics, Play Console and Logcat in Android Studio deobfuscate traces from the mapping file on their own, so there is no need to disable obfuscation for that.

How to check your app in one day

  1. Open the numbers in Play Console. In the app bundle explorer look at the DEX size and optimization percentage of the uploaded bundle. If the DEX is under 10 MB (50 MB for a game), the requirement does not affect you.
  2. Run the R8 Configuration Analyzer. It shows optimization, shrinking and obfuscation percentages, and also inefficient keep rules: yours and the consumer rules from libraries.
  3. Find the broadest rules. Look for package patterns with ** and { *; }. The analyze command in Android CLI shows used and unused package-wide keep rules in an AAR or JAR.
  4. Test critical flows in a release build. After every rule change, go through sign-in, payment and the main flow: errors caused by removed classes only show up in an optimized build.
  5. Talk to the library authors. If an SDK ships broad rules, file an issue with the analyzer result. That is better than maintaining your own rules that override the library's: according to Google, such apps then become reluctant to update the library for fear of risk.

It is also worth watching SDK versions in the Google Play SDK Console and uploading the mapping file so you can see deobfuscated traces.

Why it matters for the product

For product teams this is more than technical hygiene. Google links DEX optimization to faster startup and lower memory use, and the Play requirement means optimization becomes a condition of publishing rather than a nice-to-have. If your Android app has not had its R8 configuration reviewed in a long time, schedule an audit before February 2027: it is better to find a blocker calmly than on release day.

Need an R8 configuration audit or help optimizing an Android app? Get in touch: we will look at your build and dependencies and propose a plan.

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.

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