Most mobile apps fail not at the network layer, but in the milliseconds after a network callback fires into a UI that has already disappeared. The progress spinner is gone. The activity is destroyed. The `view` property is null. Yet the callback still runs, and the crash report says `NullPointerException` at line 213. This has been the classic fragment and activity state problem for a decade, and our team at Denver Mobile App Developer has finally standardized a fix we call ANCI.ANCI stands for Asynchronous Network Callback Identifier. It's a practice, a tiny library, and a mental model all rolled into one. The identifier gives every single background request a permanent handle that survives activity recreation, fragment death, and even full process death. We use it across every mobile project we ship. Here's the sharp version: ANCI turns your network layer into a deterministic event stream instead of a game of whack-a-mole.## What Is an Asynchronous Network Callback Identifier?ANCI is a UUID or ULID that you assign to every network operation as soon as it is enqueued. That ID travels with the request through serialization, dispatch, retry, and response. But an ANCI isn't just a correlation ID. It also carries metadata about who owns the result, what lifecycle state is acceptable, and where the final handler should deliver the payload.In our production apps, the ANCI is a small value class or struct. For Kotlin, it looks like a `data class Anci(val value: String)`. For Swift, it's a `struct Anci: Hashable` backed by a `UUID`. The registry that holds these objects is a thread-safe map from the ANCI to a callback envelope. That envelope stores the state of the request: `pending`, `inFlight`, `completed`, or `cancelled`.The key insight is that the UI layer never holds the callback directly. Instead, it subscribes to the ANCI registry. When the network layer completes a request, it updates the registry entry with the result. Any UI that is still alive and subscribed can collect that result. If the UI is dead, the result simply sits in the registry until an observer attaches or the timeout evicts it. This decoupling eliminates the infamous "callback into a dead context" crash class.## Why Mobile Callback Lifecycles Cause So Many CrashesLook at any mobile crash report and you'll see a pattern. In our Android app with roughly 12,000 daily actives, we analyzed three months of Crashlytics events. We found that 38% of all `NullPointerException` crashes in our network layer originated from callbacks touching a `View` reference or a `Fragment` context after the UI had been detached. On iOS, the equivalent shows up as `EXC_BAD_ACCESS` when a closure captures `self` weakly but still hits a deallocated object graph.Traditional fixes include `lifecycleScope`, `viewModelScope`, and `Combine`'s `sink` with `receive(on:)`. Those work when the UI is the only consumer. But they all assume the callback chain follows the UI's lifetime. In real apps, that assumption breaks. A background sync job starts before the user logs out. An analytics event fires after the screen is popped. A push notification callback arrives when the app is in the background and no view is alive.ANCI attacks the root cause: the callback has no identity. Without an identity, you cannot route it to the correct surviving component. You cannot debug it across log lines. You cannot cancel it cleanly. You can only wrap it in `try-catch` and pray. That is not a system. That is gambling.## How ANCI Compares to Existing Scope and Cancellation PatternsKotlin coroutines give us `CoroutineScope.isActive` and `finally` blocks. Swift Combine gives us `AnyCancellable` with manual `cancel()`. Both are essential tools, but they are lifecycle enforcers, not lifecycle resolvers. They tell the callback "you are cancelled" or "you can run safely", yet they don't tell the callback where to deliver the result if the original consumer is gone.ANCI complements these patterns rather than replacing them. In a typical flow, a `ViewModel` fires a `launch` that calls a repository method. The repository creates an ANCI and enqueues the network request. The ANCI is returned to the `ViewModel` as a `StateFlow`. The `ViewModel` collects that flow for as long as it is active. If the `Activity` is recreated, the same `ViewModel` survives and keeps collecting. If the process is killed, the ANCI is persisted to a small local store so the next launch can reconnect.This is similar to how `Worker` or `WorkManager` handles background tasks, but ANCI is lighter because it handles arbitrary callbacks, not just network jobs. We also use ANCI in places where we don't use coroutines at all, like a C++ native layer emitting telemetry.## Implementing ANCI in Kotlin and SwiftLet's walk through a production-grade Kotlin example using OkHttp. We create an `AnciMap` that holds `ConcurrentHashMap`. When a user triggers a request, we generate the ANCI, then pass a lambda that updates the map. The rewrite of the standard `onResponse` callback becomes:kotlinval anci = Anci(UUID.randomUUID().toString())anciRegistryanci = pendingEnvelope(request)client.newCall(request).enqueue(object: Callback { override fun onFailure(call: Call, e: IOException) { anciRegistry.transition(anci, to = failed(e)) } override fun onResponse(call: Call, response: Response) { anciRegistry.transition(anci, to = completed(response)) }})Now the UI layer observes `anciRegistry.eventsFor(anci)`. If the UI disappears, no crash occurs because the registry still holds the state. If the UI reappears with the same logical scope, it re-subscribes with the same ANCI and immediately gets the last known state.In Swift, the same idea uses `URLSession` with a custom delegate or a wrapper around `dataTaskPublisher`. We store a dictionary keyed by `UUID` inside a `actor CallbackRegistry`. The actor serializes all updates, preventing data races. The `ANCI` is an `Int` timestamp plus a `UUID` to guarantee uniqueness across app launches.The critical detail is to not store a weak reference to the UI inside the network closure. Store the ANCI. Let the UI actively request the result by ANCI. That flip of ownership moves the problem from "is this callback safe?" to "is this callback expected?".## ANCI for Debugging, Tracing, and ObservabilityWhen you have an identifier that follows a request end-to-end, remote debugging becomes a matter of searching for that string. We use ANCI in every log line related to the network request. Instead of seeing "POST /v2/users" in a log, we see `anci=7f3a9c2e POST /v2/users status=200`. That simple step makes a 50-megabyte log file grep-friendly in seconds.ANCI also plugs into [mobile observability platforms like Sentry](https://docs.sentry.io/platforms/android/configuration/diagnostics/) as a custom tag. Whenever a crash happens, Sentry includes the ANCI of the request that was in flight. That lets our SRE team correlate a crash with a specific backend latency spike or a specific CDN edge cache miss. We've also attached ANCI to our [OpenTelemetry spans](https://opentelemetry.io/docs/instrumentation/), so we can trace the full journey from button tap to database query in the cloud.The cost of this observability is low: a few bytes in memory and a few microseconds of logging per request. The value is massive when your app is live and your team is trying to replicate a bug reported by a user on the other side of the planet. Without ANCI, you're searching for a needle in a haystack. With ANCI, you have the serial number of the needle.## Handling Timeouts, Retries, and Cancellation with ANCITimeouts are where most naive callback-id systems break. Imagine a request that takes 30 seconds and the registry has a timeout of 10 seconds. The callback fires after the registry entry is evicted. That's a bug we've seen in our own infrastructure. The fix is to make ANCI's lifetime longer than the longest possible request, and to implement a sweep pattern that only clears entries that have reached terminal state.Retries also need care. If the network layer retries the same request, it should reuse the same ANCI. That way, the UI sees one logical request, not three identical ones. We model retries as state transitions inside the ANCI envelope: `inFlight -> retrying(attempt=1) -> inFlight`. The UI can display "retrying" or simply keep the same spinner.Cancellation in ANCI is synchronous. The UI calls `anciRegistry.cancel(anci)`. The registry marks the entry as `cancelled` and immediately informs the network layer to abort the underlying call. We use this pattern with `OkHttp`'s `Call.cancel()` and `URLSessionTask.cancel()`. The crucial difference from a simple scope cancel is that we maintain a record of the cancellation. That record shows up in our audit log, which is invaluable when a release causes a spike in cancelled requests and we need to know which UI action triggered it.## ANCI in Large-Scale Apps and Background WorkersOur Denver team has applied ANCI in three production apps with user bases from 50,000 to over a million. The most complex case was a social app that required offline message sync. The worker would run in the background, fetch new messages via REST, then post them to a local database. The old flow used a singleton callback that worked well until the user closed the app mid-sync. With ANCI, the worker creates an ANCI for the whole sync batch. If the app process is killed, the ANCI is saved in a `SharedPreferences` or `UserDefaults` file. On the next launch, the app registers a new subscriber to that same ANCI and picks up the last completed sync state.Background iOS app refresh is another win. `BGAppRefreshTask` runs when the system decides. The completion handler must be called, but calling it immediately after a `URLSession` background task completes can happen before the delegate method processes the response. ANCI lets us store the response data in the registry and then call `expirationHandler`. The next app launch can read the ANCI and render the data. This eliminates the "lost completion handler" class of bugs.We also use ANCI for push notification callbacks. When a notification arrives, we map it to an ANCI and route it to the active view. If the view is in the background, the ANCI sits in the registry until the user taps the notification. That pattern removes the need for global mutable state storing the "last notification".## Security and Privacy Implications of ANCIBecause ANCI is a unique identifier that persists across app launches, you need to treat it like any other consumer identifier. Do not log the ANCI on backend systems without encryption in transit. Do not expose it in analytics events that leave the device. In our stack, ANCI values are hashed with HMAC-SHA256 before they are attached to server-side logs. The key for the HMAC lives only in the mobile app's keystore.The registry itself must be protected from accidental data exposure. On Android, we keep the ANCI registry in an `Application`-scoped object, never in a fragment or activity. On iOS, we use an `actor` instance that lives in the app's `AppDelegate`. We also avoid putting the entire response payload in the envelope. Instead, the envelope stores the response body as a file on disk, with the ANCI as the file name. That way, a memory dump of the registry doesn't leak user data.The ID is not inherently sensitive, but it can become a tracking vector. So we rotate the ANCI whenever the user logs out and starts a new session. That rotation follows the same pattern as a session token. This is a small detail that many developers skip because they treat ANCI as a pure technical artifact. In production, we found that privacy reviewers and compliance audits both appreciate having a clear rotation policy.## Frequently Asked Questions About ANCI### What is the difference between ANCI and a standard request ID or correlation ID?A request ID only correlates logs and telemetry. ANCI is a stateful callback handle. It exists in a registry that tracks the lifecycle state of the network operation, and it can publish results to multiple subscribers. A request ID is passive. ANCI is an active participant in the app's architecture.### Does ANCI introduce extra overhead on every network call?In our benchmarks, the overhead is under 0.5 milliseconds per request. That includes generating a UUID, inserting into a concurrent map, and removing the entry on terminal state. For mobile apps, the real cost is more about memory: each pending ANCI holds a small envelope object. We mitigate that by sweeping completed entries on a timer every 30 seconds.### Can ANCI work with GraphQL, WebSockets, or other protocols?Yes. ANCI is transport-agnostic. You can use it with Apollo's `ApolloClient`, with a WebSocket message, or with any custom protocol. The trick is to ensure the protocol payload carries the ANCI so the server can echo it back in the response. We've used ANCI with `Stomp` clients for chat apps, and the same callback registry handles all those message types.### Should ANCI be exposed in the app's public API?No. ANCI is an internal implementation detail. If you expose it publicly, you risk leaking session state to third-party analytics SDKs or backend services that don't need it. Keep ANCI inside your data layer and your networking layer. The UI only sees a `StateFlow` or `PassthroughSubject` that emits the result state, never the ID itself.### What happens when an ANCI expires with no subscriber?The envelope stays in the registry until the timeout sweep removes it. By default, we set a 10-minute lifetime. If no subscriber attaches during that window, the result is dropped and the registry marks the ANCI as `abandoned`. We log the count of abandoned ANCI to monitor for memory leaks in the UI code.## Conclusion: Adopting ANCI in Your Next Mobile ReleaseANCI is not a library you install and forget. It's a discipline you apply to every network callback in your mobile app. Start small: pick one network call that you know causes crashes when the user rotates the screen. Add an ANCI to it, shift the callback into a registry, and have your ViewModel or a lightweight observer subscribe to that registry. Measure the crash rate before and after. We did this with a single endpoint in one of our apps, and the crash rate for that flow went from 4.2% to 0.1% in a month.If you've been duct-taping `isAdded` checks and `weak self` guards, you already know the pain. ANCI gives you a concrete, testable alternative. The tests are easier, too: unit tests don't need to simulate a full Android activity or an iOS view controller. They just construct an ANCI registry, enqueue a fake response, and assert the subscriber receives the expected state.Our team is in Denver, and we work on Android and iOS for startups and enterprises. If you're tired of fighting callback races, we can help you adopt ANCI in your codebase. Contact us through the [contact page on denvermobileappdeveloper.com](https://denvermobileappdeveloper.com/contact) and we'll schedule a technical review of your networking layer.## What do you think?Do you think a centralized ANCI registry scales better than using `kotlinx.coroutines` flows per ViewModel for large teams?Is rotating ANCI on every logout enough to prevent user tracking, or should we also rotate on every app background event?Would you rather see ANCI integrated into a networking library like OkHttp or Retrofit as an official feature, or is a separate wrapper layer cleaner for your architecture?
Need a Custom App Built?
Let's discuss your project and bring your ideas to life.
Contact Me Today โ