By Pavlo Stavytskyi (Software Engineer, Meta) and Rebecca Franks (Developer Relations Engineer, Google)

Instagram Direct, one of the foundational surfaces of the social media giant handling billions of user messages every single day, has undergone a massive technological transformation. Following years of iterative development, the engineering team at Meta had squeezed every possible micro-optimization out of the legacy Android View system. However, maintaining and expanding a heavily optimized legacy architecture incurs significant technical debt and engineering overhead—challenges that grow increasingly pronounced as development teams adopt declarative user interfaces and AI coding assistants.

In a deep technical collaboration with Google, the Instagram Direct team migrated its core messaging infrastructure to Jetpack Compose. This initiative went far beyond a routine UI modernization. Instead, the team built an entirely AI-native UI codebase. The results of this architectural shift are striking: the new codebase is 50 percent smaller than the original implementation, while achieving a 35 percent reduction in AI agent execution time, 32 percent fewer engineer-agent exchanges, and a 33 percent reduction in token costs. Furthermore, the rigorous performance optimizations developed jointly by Meta and Google have improved Jetpack Compose not only for Instagram, but for the broader Android developer ecosystem.

Modernizing the Codebase at Massive Scale

Artificial intelligence has rapidly evolved into a daily companion for software engineers across the technology industry. Applying AI to large-scale codebases already yields measurable productivity gains, but the Instagram Direct team set a much more ambitious goal. Rather than simply pointing modern AI tools at existing legacy code, the team redesigned the codebase and its architecture to be AI-native by design, multiplying the impact of automation far beyond what simple retrofitting could ever achieve.

How Instagram Direct engineers built AI-native UI architecture with Jetpack Compose and reduced token cost per agent session by 33%

The team chose Jetpack Compose as a cornerstone for this new AI-native UI architecture. Because Compose is declarative, its code is inherently more concise, predictable, and structurally transparent for AI models to reason about. It introduces fewer side effects, less implicit state, and much clearer component boundaries than imperative frameworks.

Migrating a codebase of this magnitude required meticulous planning. Hundreds of millions of people send messages on Instagram every single day, meaning the migration had to proceed gradually and smoothly, with zero disruption to the user experience while the team completely re-architected the underlying foundation. To illustrate the sheer scale of the challenge, individual UI components can render in over 160 distinct state permutations, and a single conversation screen alone handles more than 200 distinct message types.

When migrating a massive codebase to Compose, developers often face the temptation to take a shortcut by embedding Compose UI components directly inside an existing View hierarchy. While this approach can serve as an acceptable intermediate step during a gradual transition, it introduces long-term complications. AI tools typically take the path of least resistance. When declarative and imperative UI code are mixed together, AI models frequently blend them incorrectly, inadvertently introducing subtle bugs, technical debt, and performance regressions.

Building an AI-Native UI Architecture

At the scale of Instagram, architectural abstractions are unavoidable to keep the application maintainable as it grows. Consider a common pattern where every list item type is modeled as a descendant of a custom base class that exposes standard lifecycle hooks. In legacy setups, mixing imperative contexts with declarative lambdas often creates subtle coupling across paradigms. Furthermore, mutable fields can survive list re-binding and recycling across rows, leading to memory leaks and difficult-to-reproduce bugs.

How Instagram Direct engineers built AI-native UI architecture with Jetpack Compose and reduced token cost per agent session by 33%

Even when code is cleaned up by assigning a dedicated composable function to an item, the underlying architectural tensions remain if proper boundaries are not enforced. Without strict separation, AI tools hitting friction will often route around guardrails to unblock themselves, lowering the overall quality of the generated code over time. To make the codebase truly AI-friendly, the Instagram team established practical rules ensuring that Compose UI code is cleanly separated from mutable class members and state, relying solely on constructor arguments.

Migrating a codebase of this size was a monumental undertaking. For an extended period, hundreds of UI components that make up the majority of Direct UI had to coexist with their legacy counterparts, with both systems maintained in parallel. AI workflows helped make this parallel migration possible by accelerating the creation of massive amounts of code, allowing the team to complete the transition in record time without disrupting daily feature development for millions of users.

Multiple engineers ran their own AI agents against a shared knowledge base of reusable skills and conventions established during the migration. This strategy kept workflows and best practices synchronized across the entire team. By splitting the migration of each surface into distinct stages, individual engineers could move quickly to settle core architecture and tricky edge cases up front, leaving others free to focus on getting the user interface production-ready.

The resulting data validated the entire approach. For migrated Instagram Direct surfaces, Jetpack Compose allowed the team to reduce the total amount of UI code by half. Less code for AI to generate directly correlated with higher-output quality and lower token costs per task.

How Instagram Direct engineers built AI-native UI architecture with Jetpack Compose and reduced token cost per agent session by 33%

Internal data analyses comparing AI agent sessions working on Compose UI against identical tasks executed using traditional Android Views revealed clear efficiency gains. Engineer-agent exchanges and execution time figures demonstrated superior resource utilization per unit of landed output, while token metrics confirmed reduced overall costs for typical agent sessions.

Meta also tracks code changes using a risk score that evaluates overall quality and the likelihood of introducing production incidents. As files accumulate a higher risk score, AI agent sessions naturally become less resource efficient. When a file’s accumulated risk score doubles, user interfaces implemented with Android Views suffer a 30 percent reduction in agent resource efficiency per landed character. Under the exact same circumstances, user interfaces built with Jetpack Compose experience a reduction of only 9 percent.

Through this close partnership, Google and Meta approached Compose adoption through the lens of AI-readiness rather than a simple visual rewrite. The project demonstrated the exceptional strength of Compose as a foundation for building AI-first codebases and architectures at scale.

Performance Optimizations

Because Instagram Direct is one of the most critical surfaces of the application, users expect it to feel instantaneous and responsive at all times. Adopting Jetpack Compose meant executing a substantial UI rewrite, and the primary directive was to preserve this high-quality experience without introducing a single regression. Years of prior iteration had already pushed the legacy View-based implementation to an exceptionally high performance benchmark, and the new framework had to meet or exceed that exact standard.

How Instagram Direct engineers built AI-native UI architecture with Jetpack Compose and reduced token cost per agent session by 33%

Instagram tracks hundreds of performance metrics, but three stand out as most essential during the migration: runtime performance evaluated through production A/B tests, startup latency, and frame stability during complex scrolling interactions. A common pitfall in migrations of this scale is starting too small—moving a handful of components and studying their behavior in isolation. While helpful, small-scale tests paint an incomplete picture and can yield false negatives because bridging interruptions between frameworks obscure the true performance profile. The end-to-end migration of entire surfaces provided a much clearer and more favorable performance reality.

The core screens in Instagram Direct rely on long lists of varied item types, originally implemented using standard Android recycler views. The team executed a gradual migration of several hundred individual list items to Compose within the existing architecture, rolling them out in production via independent groups under A/B tests without any visible changes for users. As a natural next step, the team replaced the legacy list core with the Compose-native alternative, known as LazyColumn.

This transition required abstracting Compose UI components away from their enclosing frameworks while maintaining simultaneous compatibility with both traditional recycler views and modern lazy columns. Furthermore, the architecture enabled runtime switching via feature flags to facilitate rigorous A/B testing.

The immense scale and sensitivity of Instagram posed unique challenges that required an iterative, hands-on engineering partnership. Google and Meta engineers jointly analyzed production metrics to design new Compose capabilities capable of matching or surpassing legacy benchmarks. Key additions resulting from this collaboration include pausable composition and advanced visibility tracking.

How Instagram Direct engineers built AI-native UI architecture with Jetpack Compose and reduced token cost per agent session by 33%

Pausable composition, enabled by default in recent versions of Compose, allows expensive lazy-list items to be composed incrementally across multiple frames to prevent visual stutter. When paired with specialized cache windows, this combination significantly improves scroll smoothness. Recent internal testing at Meta showed that combining pausable composition with an optimized lazy layout cache window reduced large frame drops per minute by roughly 13 percent compared to vanilla Compose. Cache windows alone yielded an 8 percent reduction against the same baseline.

These cache windows prepare and retain off-screen items within a pixel-based band around the viewport to enable fast, fluid flings. The Instagram team fine-tuned these cache configurations specifically for the content structure and item sizes native to Direct messaging.

Another vital outcome of the technical partnership is the introduction of improved visibility tracking APIs. These tools provide large-scale Jetpack Compose surfaces with a consistent, reliable mechanism to determine when a composable element is actively visible on screen, replacing custom, hand-rolled implementations used in the past. Within Instagram Direct, these visibility signals drive product quality metrics across hundreds of files.

Startup performance for Compose UI inside Instagram Direct was further optimized through the use of baseline profiles, which pre-compile critical code paths at installation time so that the framework renders rapidly from the very first launch. Interestingly, adopting Compose in messaging also yielded unexpected performance benefits across other areas of the application. Because the Compose runtime incurs a warmup cost that is paid only once, and messaging is a high-traffic surface frequently visited early in a user session, other app surfaces relying on Compose saw noticeable startup improvements.

How Instagram Direct engineers built AI-native UI architecture with Jetpack Compose and reduced token cost per agent session by 33%

The successful migration of Instagram Direct to Jetpack Compose highlights the profound advantages of aligning modern declarative UI frameworks with AI-assisted development workflows. By significantly reducing boilerplate, simplifying state management, and elevating engineering productivity, the initiative has laid a robust foundation for future development. The engineering teams at Meta and Google plan to continue their collaboration, bringing further enhancements to both Instagram and the broader Android developer ecosystem.

Leave a Reply

Your email address will not be published. Required fields are marked *