Netflix Senior Mobile Developer Interview Preparation Guide
Netflix's senior-level mobile developer interview spans recruiter screening, two technical phone screens, and four onsite rounds. The process evaluates coding excellence, system design for mobile-scale challenges, distributed systems architecture, mobile platform expertise, and cultural alignment with Netflix's freedom and responsibility philosophy. For senior candidates, the process emphasizes leadership capabilities, architectural influence, and the ability to mentor team members while solving complex mobile engineering problems.
Interview Rounds
Recruiter Screening
What to Expect
Your initial conversation with Netflix's recruiting team covers professional background, career progression as a mobile developer, and preliminary cultural alignment. The recruiter discusses the senior mobile developer role, Netflix's mobile engineering organization, expectations, compensation, and benefits. This is a mutual evaluation—ask about the team's mobile tech stack, current architectural challenges, growth opportunities, and how Netflix approaches mobile development (native vs. cross-platform strategy). A potential follow-up recruiter call may occur before technical rounds to confirm alignment and answer remaining logistical questions.
Tips & Advice
Be authentic and specific about your mobile development journey. Prepare 2-3 concise stories showcasing ownership—such as leading a major mobile feature launch, optimizing app performance significantly, or recovering from a critical production incident. Research Netflix's mobile products and strategy; mention specific challenges or technologies that excite you (e.g., optimizing the Netflix app for low-bandwidth regions, improving iOS/Android parity, or building offline-first features). Ask substantive questions: What's the team's current mobile architecture? How do you balance iOS and Android investment? What's the biggest technical challenge the mobile team faces? Be direct about expectations regarding role scope, team size, on-call responsibilities, and work flexibility.
Focus Topics
Netflix Culture Fit & Autonomy Comfort
Familiarity with Netflix's freedom and responsibility culture. Concrete examples of thriving in autonomous environments: making independent technical decisions, driving change without heavy oversight, and taking accountability for outcomes.
Practice Interview
Study Questions
Mobile Development Career Progression & Impact
Your evolution as a mobile engineer from individual contributor to senior level. Key projects, scale of systems you've worked on, and how your responsibilities have expanded. Emphasis on progression to architectural influence and mentoring others.
Practice Interview
Study Questions
Mobile Development Passion & Netflix Alignment
Genuine interest in mobile development and specific reasons for pursuing Netflix's mobile team. Concrete examples of impactful mobile experiences you've built, performance optimizations you've delivered, or mobile-specific problems you've solved.
Practice Interview
Study Questions
Technical Phone Screen 1 - Mobile Coding & Algorithms
What to Expect
Your first technical screen evaluates coding proficiency through one to two problems with mobile development contexts. Problems may involve implementing features for mobile apps (e.g., implementing an efficient caching layer, optimizing list rendering with data filtering, handling real-time updates), algorithmic challenges with mobile constraints, or solving data structure problems relevant to mobile systems. Problems range from medium to hard difficulty, emphasizing both algorithmic thinking and practical mobile engineering knowledge. You'll code in a collaborative editor (CoderPad, LeetCode, etc.) while explaining your approach verbally.
Tips & Advice
Begin by clarifying requirements: ask about constraints, data size, edge cases, and whether mobile-specific optimizations are important. Think aloud as you code—interviewers value understanding your reasoning over perfection. For mobile problems, discuss platform-specific considerations proactively (memory management in Kotlin, view recycling in Android, view controller lifecycle in iOS). Write clean, maintainable code with proper error handling. Test solutions with examples and articulate trade-offs clearly. If stuck, discuss your approach and ask for hints intelligently—struggling thoughtfully is valued. For senior candidates, propose optimizations or discuss how your solution scales if requirements change.
Focus Topics
Mobile Performance Optimization Fundamentals
Techniques for optimizing mobile app performance: reducing memory footprint, minimizing CPU usage, improving battery efficiency, optimizing rendering performance (frame rates, jank prevention), and choosing efficient data structures. Understanding profiling tools and performance metrics.
Practice Interview
Study Questions
Comprehensive Error Handling & Edge Cases
Robust error handling for mobile contexts: network failures, timeouts, memory pressure, device rotations, background/foreground transitions, incomplete data, and partial failures. Write defensive code that gracefully handles unexpected scenarios.
Practice Interview
Study Questions
Swift/Kotlin Core Language Proficiency
Deep competency in Swift (iOS) or Kotlin (Android): understanding language features (optionals/nullability, closures/lambdas, type systems), idiomatic patterns, memory safety, and best practices. Write clean, production-quality code without hesitation.
Practice Interview
Study Questions
Algorithms & Data Structures with Mobile Context
Strong foundations in common algorithms (sorting, searching, dynamic programming, graph traversal) and data structures (arrays, linked lists, trees, graphs, hashmaps). Understand complexity analysis and apply these concepts to mobile scenarios like feed rendering, caching, or real-time updates.
Practice Interview
Study Questions
Technical Phone Screen 2 - Complex Mobile Architecture Problem
What to Expect
Your second technical screen tackles more complex mobile development scenarios. You might face problems involving offline-first synchronization between client and server, implementing sophisticated caching strategies for large datasets, managing complex state in interactive features, handling real-time updates with consistency guarantees, or optimizing data loading patterns for poor networks. Problems are medium-to-hard and test your ability to think systematically about mobile architecture challenges while balancing competing concerns: data consistency, performance, battery efficiency, and user experience.
Tips & Advice
For complex problems, discuss architecture decisions explicitly before coding. Explain why you chose particular patterns (e.g., why use reactive streams for state management, or why implement offline-first architecture). Proactively consider mobile constraints: network reliability, battery life, device memory, and user experience during state transitions. If the problem involves state management or data flow, sketch your architecture before implementing. For senior candidates, discuss scalability: how your solution evolves as features are added or data volumes increase. Discuss testability and how you'd validate your design. Be prepared to discuss trade-offs between consistency models and acknowledge when simpler approaches might be better.
Focus Topics
Offline-First & Persistence Strategies
Local caching and persistence for mobile: in-memory caches, disk persistence (SQLite, Realm), cache invalidation strategies, offline-first architectures. Syncing local changes to servers, handling conflicts, and managing storage constraints.
Practice Interview
Study Questions
Networking & API Design for Mobile Efficiency
Building robust mobile networking layers: request/response design for mobile efficiency, handling retries and timeouts, request cancellation, session management, certificate pinning. Designing mobile-friendly APIs: pagination, sparse field selection, request batching, and versioning strategies.
Practice Interview
Study Questions
Mobile Architecture Patterns (MVC/MVP/MVVM/Clean Architecture)
Deep understanding of architectural patterns in iOS and Android: separation of concerns, dependency injection, testability, and maintainability. Understanding how to structure growing codebases for scalability and how architectures evolve as complexity increases.
Practice Interview
Study Questions
State Management & Reactive Data Flows
Handling complex state in interactive mobile apps: reactive patterns (Combine, RxJava/RxKotlin, Flow), unidirectional data flow, state management libraries. Keeping UIs in sync with data, handling concurrent updates, preventing state inconsistencies, and managing side effects.
Practice Interview
Study Questions
Onsite Round 1 - System Design: Mobile-Scale Backend System
What to Expect
This onsite round assesses your ability to design large-scale systems supporting millions of mobile users. You'll tackle scenarios like designing a mobile notification system for Netflix content updates, a real-time synchronization backend for offline-first apps, a content recommendation service optimized for mobile clients, or a streaming metadata delivery system serving millions of mobile users. Discussion covers end-to-end architecture: API design, backend services, database choices, caching strategies, fault tolerance, global distribution, and operational considerations. You must make thoughtful trade-offs between availability, consistency, latency, and cost while accounting for mobile-specific constraints like intermittent connectivity and bandwidth limitations.
Tips & Advice
Start with clarifying questions about scale, user behavior, mobile-specific requirements, and constraints. Ask about expected latency, throughput, consistency needs, geographic distribution, and device diversity. Proactively discuss mobile considerations: how the design handles intermittent connectivity, what happens when apps go offline, how battery drain is minimized, and how bandwidth usage is controlled. Sketch your architecture before diving into details. Justify decisions: why this database, why cache at this layer, why replicate this data. Discuss monitoring, alerting, and graceful degradation. Consider failure scenarios: what happens when critical services fail? How does the mobile client behave? For senior candidates, discuss architectural evolution: how you'd handle 10x growth, emerging mobile platforms, or new requirements.
Focus Topics
Multi-Layer Caching for Mobile Systems
Caching strategy spanning multiple layers: CDN for static content, server-side caching (Redis), client-side HTTP caching, and in-app memory caching. Cache invalidation strategies, TTL policies, and serving stale data during network failures.
Practice Interview
Study Questions
Graceful Degradation & Mobile-Specific Resilience
Designing systems that degrade gracefully when services fail: circuit breakers, fallback strategies, serving cached/stale data, progressive disclosure of features. How mobile clients behave during partial failures and maintain usability despite service degradation.
Practice Interview
Study Questions
Distributed Systems for Mobile-Scale Operations
Architectural patterns for serving millions of mobile clients globally: load balancing, database replication and sharding, CDN usage for content delivery, service-oriented architecture, asynchronous processing, and trade-offs between consistency models (CA vs. AP for mobile use cases).
Practice Interview
Study Questions
Mobile-Optimized API Design & Contracts
Designing APIs specifically for mobile consumption: pagination and cursor-based navigation, sparse fieldsets, efficient caching directives, request batching, and versioning strategies. Understanding how API design choices impact bandwidth, battery life, and user experience on mobile.
Practice Interview
Study Questions
Onsite Round 2 - Distributed Systems Deep Dive & Mobile Architecture
What to Expect
This round explores deeper distributed systems thinking and architectural nuance typical of senior roles. You'll engage with complex scenarios like designing mobile-backend synchronization at scale handling eventual consistency, architecting multi-region deployment strategies for mobile apps, handling network partitions gracefully in mobile contexts, or designing real-time features (live recommendations, activity feeds, comments) resilient to distribution complexities. The interviewer probes your understanding of subtle architectural trade-offs: when eventual consistency is acceptable vs. when strong consistency is required, how to handle state divergence between mobile clients and servers, and how to evolve systems as requirements and scale change. This round assesses comfort navigating inherent complexity in distributed systems.
Tips & Advice
Bring production experience with distributed systems—Netflix values engineers with real-world scars. Discuss what worked, what didn't, and what you learned. Engage deeply on trade-offs and constraints rather than reciting textbook patterns. If discussing consistency models, explain CAP theorem implications for mobile (typically choosing AP over C). Discuss operational realities: how you deploy changes, implement rollbacks, monitor systems, and observe behavior with millions of mobile clients. For senior roles, discuss your leadership in architectural decisions: how you've communicated trade-offs to non-technical stakeholders, built consensus around architectural changes, and influenced your team's technical direction.
Focus Topics
Handling Heterogeneous Mobile Client Base at Scale
Designing systems serving millions of diverse mobile clients: different device capabilities, OS versions (iOS/Android), network conditions, feature compatibility. Versioning strategies, feature flags, progressive rollouts, A/B testing on mobile, and gracefully handling incompatible client versions.
Practice Interview
Study Questions
Observability & Production Debugging at Mobile Scale
Strategies for monitoring and debugging distributed mobile systems: structured logging, metrics, distributed tracing, debugging techniques for anonymous clients. Understanding mobile-specific observability challenges: tracing requests through client-server systems, correlating events across devices, and diagnosing issues affecting specific user populations.
Practice Interview
Study Questions
Multi-Region Architecture & Global Mobile Deployment
Designing systems for global distribution: CDN strategies, regional backends, data replication across regions, handling latency across geographies, compliance with regional data residency requirements. Serving content efficiently to mobile users worldwide.
Practice Interview
Study Questions
Eventual Consistency & Conflict Resolution for Mobile
Eventual consistency models necessary when mobile clients can work offline and sync later. Conflict resolution strategies: last-write-wins, custom application logic, or human resolution. Detecting and handling state divergence between client and server. Vector clocks, timestamps, and operational transformation concepts.
Practice Interview
Study Questions
Onsite Round 3 - Mobile Platform Expertise & Technical Leadership
What to Expect
This round evaluates your deep technical expertise in mobile development and your leadership impact. You'll discuss complex mobile technical challenges: evolving app architecture as codebases grow, performance optimization initiatives, cross-platform strategy decisions, handling platform-specific constraints and opportunities, or managing technical debt. The interviewer also explores your leadership: how you've mentored junior mobile developers, influenced architectural decisions beyond your immediate code, advocated for technical improvements, and led cross-functional initiatives (collaborating with product, design, backend). You might discuss navigating mobile-specific trade-offs (iOS vs. Android investment), adopting new technologies or frameworks, or how you've elevated your team's technical capabilities. This round assesses both technical depth and your ability to lead.
Tips & Advice
Prepare specific examples of complex mobile technical problems you've solved—explain your problem-solving process, design decisions, and how you communicated solutions to stakeholders. Share architectural evolution stories: how you've refactored codebases, migrated to new frameworks, improved performance significantly, or paid down technical debt. Discuss mentoring: how you've helped junior developers grow, code review feedback you've given, technical discussions you've led. Go deep on platform expertise: iOS/Android specifics, strengths/weaknesses, how you've navigated cross-platform trade-offs. Show how you stay current with platform evolution and share new knowledge with your team. For senior roles, demonstrate leadership in technology decisions and influence across teams.
Focus Topics
Cross-Platform Strategy & Framework Decisions
Understanding cross-platform frameworks (React Native, Flutter) vs. native development trade-offs. When to choose each approach based on requirements, team capabilities, performance needs, and maintenance burden. Managing codebases with both native and cross-platform components. Platform-specific requirements, app store policies, and distribution strategies.
Practice Interview
Study Questions
Mentoring, Influence & Mobile Team Leadership
Examples of mentoring junior mobile developers: how you've guided their growth, code review feedback, helping them navigate complex problems, and elevating their skills. How you've influenced architectural decisions, advocated for technical improvements (e.g., refactoring, framework migrations, performance initiatives), and led adoption of new technologies or practices.
Practice Interview
Study Questions
Android Architecture Patterns & Advanced Kotlin Techniques
Deep Android expertise: Jetpack Compose vs. traditional Android UI architecture, Kotlin coroutines and Flow for reactive programming, ViewModel and LiveData patterns, Room database optimization, dependency injection (Hilt), testing strategies (JUnit, Espresso, Robolectric), memory optimization, and Android-specific constraints.
Practice Interview
Study Questions
iOS Architecture Patterns & Advanced Swift Techniques
Deep iOS expertise: SwiftUI vs. UIKit architecture trade-offs, reactive patterns with Combine framework, dependency injection patterns, advanced Swift features (protocols, generics, type erasure), testing strategies (XCTest, mocking), memory management (ARC), and lifecycle management. Knowledge of iOS-specific constraints and optimization techniques.
Practice Interview
Study Questions
Onsite Round 4 - Netflix Culture, Values & Leadership Philosophy
What to Expect
This final onsite round evaluates cultural alignment and leadership philosophy. The interviewer uses structured behavioral questions (STAR format: Situation, Task, Action, Result) to explore your embodiment of Netflix values: freedom and responsibility, context over control, bias for action, and continuous improvement. Topics include: ownership examples showing you take full responsibility for critical outcomes, operating with ambiguity (driving progress without clear direction or oversight), continuous improvement (learning from failures and raising the bar), cross-functional collaboration and communication, and handling difficult interpersonal situations. For senior candidates, expect questions about influencing without formal authority, building trust with peers, and contributing to positive team culture. Stories should be recent, specific, and demonstrate measurable impact. This round carries equal weight with technical rounds in hiring decisions.
Tips & Advice
Prepare 6-8 specific STAR-structured stories from recent roles covering Netflix values. For ownership, discuss taking responsibility without being asked, making tough decisions, and accepting accountability even when outcomes were suboptimal—show learning. For ambiguity, explain how you brought structure to unstructured situations, made progress with incomplete information, and adjusted course as you learned. For continuous improvement, show how you learn from failures, share lessons with your team, and raise the bar. Keep stories concise but specific: include metrics, business impact, and your personal learning. Avoid generic statements; Netflix values concrete examples. Practice delivering conversationally—your stories should feel authentic, not rehearsed. Show humility and self-awareness: acknowledge what you could have done better. Demonstrate you embody Netflix culture as a leader, not just as an individual contributor—show how you influence others' approaches to ownership and autonomy.
Focus Topics
Handling Production Incidents & Learning Culture
Stories about managing production incidents: how you triaged mobile app issues, communicated with stakeholders, implemented fixes, and conducted post-mortems. Examples of failures you've experienced and what you learned. Demonstrating you see failures as learning opportunities and have implemented improvements preventing recurrence.
Practice Interview
Study Questions
Cross-Functional Leadership & Influence Without Authority
Examples of working effectively across product, design, and backend teams. Situations where you influenced decisions despite lacking direct authority. Navigating conflicting priorities across teams and finding solutions balancing different perspectives. How you've built trust and credibility enabling your influence.
Practice Interview
Study Questions
Ownership & End-to-End Responsibility for Mobile Outcomes
Examples of owning mobile features or systems completely: from conception through launch and operation. Taking responsibility for app quality, managing technical debt, handling production incidents, driving improvements without being asked. Stories showing accountability for outcomes even when situations were ambiguous or beyond your direct control.
Practice Interview
Study Questions
Operating with Ambiguity & Driving Mobile Initiative Progress
Examples of navigating unclear situations: building mobile features with vague requirements, making architectural decisions with incomplete information, driving mobile initiatives where direction wasn't established, shipping products with incomplete knowledge. How you bring structure, gather information, make decisions, and execute with confidence despite uncertainty.
Practice Interview
Study Questions
Frequently Asked Mobile Developer Interview Questions
Explain recommended minimum touch target sizes and strategies to ensure comfortable hit targets across platforms. Provide platform-specific guideline values (for example 44x44 pt on iOS and 48dp on Android), techniques to enlarge tappable areas without changing visuals (padding, hitSlop), how to test hit targets on-device, and how to handle crowded toolbars or inline small controls.
Sample Answer
Recommended minimums
- iOS: 44 x 44 pt (Apple HIG)
- Android: 48 x 48 dp (Material Guidelines)
- Web / touch: ~48 x 48 px recommended
These are minimum tappable areas including any invisible padding — not just visual asset size.
Techniques to enlarge hit area without changing visuals
- Add invisible padding/margins around control (but keep visual bounds unchanged).
- Use platform APIs: hitTest override on iOS, touchDelegate on Android, hitSlop/pressRetentionOffset in React Native, GestureDetector padding in Flutter.
- Ensure accessible labels and focus targets for screen readers.
Example – React Native:
<TouchableOpacity hitSlop={{ top: 10, left: 10, right: 10, bottom: 10 }}>
<Icon />
</TouchableOpacity>
Example – iOS (Swift) override:
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let margin: CGFloat = 10
let largerBounds = bounds.insetBy(dx: -margin, dy: -margin)
return largerBounds.contains(point)
}
Example – Android XML (TouchDelegate in code is typical)
Testing hit targets on-device
- Use finger-thumb testing: try single-finger taps, varying hand positions.
- Record taps with developer builds (Analytics for missed taps).
- Use accessibility inspector (iOS Accessibility Inspector, Android Layout Inspector) to visualize bounds.
- Test on different screen sizes and with system font/accessibility sizes.
Handling crowded toolbars / small inline controls
- Prefer overflow menus for less-frequent actions.
- Increase spacing between controls; use grouping and separators.
- Convert small inline icons to combined controls (long-press for secondary actions).
- Offer alternate large targets in edit modes or when accessibility settings enabled.
- Document and align with designers to keep visual density but preserve hit areas with invisible padding.
Focus on measurable minimums, test on real devices, and use platform APIs to expand interactive areas while keeping your UI visually intact.
In Kotlin (Android), implement a utility that serializes an app's navigation stack and transient UI state into a compact JSON string and a corresponding restore method. Requirements: support nested fragments with stable identifiers, persist simple view state (text fields, selected indices), handle missing/older fields gracefully, and run in O(n) time where n is the number of UI elements. Provide class/function signatures and a clear code outline showing the main data structures and algorithms (no UI framework glue required).
Sample Answer
Approach (brief)
Serialize a tree of navigation entries (activity -> back stack -> nested fragments) where each node has a stable id, type, and map of simple view states. Use kotlinx.serialization to produce a compact JSON and include a schema version. Restoration traverses JSON and applies states where matching ids exist; ignore unknown/missing fields to be forward/backward compatible. Work in O(n) where n = number of UI elements by single-pass traversal/serialization.
Signatures
data class UiNode(
val id: String,
val type: String,
val children: List<UiNode> = emptyList(),
val viewState: Map<String, Any> = emptyMap()
)
object NavigationStateSerializer {
fun serialize(root: UiNode, version: Int = 1): String
fun restore(json: String, applyState: (UiNode) -> Unit)
}
Code outline
// Use kotlinx.serialization with a polymorphic wrapper for view values (String/Int/Boolean)
@Serializable
data class UiNodeDto(val id: String, val type: String, val children: List<UiNodeDto>, val viewState: Map<String, JsonElement>)
fun NavigationStateSerializer.serialize(root: UiNode, version: Int = 1): String {
// BFS/DFS single-pass convert UiNode -> UiNodeDto, convert simple values to JsonPrimitives
// wrap with {"version":version,"root":...}
}
fun NavigationStateSerializer.restore(json: String, applyState: (UiNode) -> Unit) {
// parse JSON defensively, check version, traverse dto tree
// for each dto, build UiNode-like minimal object and call applyState(node)
// applyState should find real UI element by id and set fields (text, selectedIndex) safely
}
Key concepts & guarantees
- Stable ids required for matching; nested structure preserved.
- Graceful handling: unknown keys ignored; missing keys leave defaults.
- O(n): each node visited once in serialize and once in restore.
- Edge cases: malformed JSON (try/catch), unsupported version (best-effort), non-serializable view values filtered.
- Alternative: use ProtoBuf for smaller payloads if binary storage desired.
Walk through how you would scope and run a small, timeboxed test (a spike, prototype, or lightweight experiment) to reduce uncertainty on an ambiguous request. Cover how you would set its scope and timebox, what deliverables and success criteria you would define upfront, and how the results would shape your next steps.
Sample Answer
A good spike has five parts, and the order matters: frame the uncertainty as a falsifiable question, scope and timebox it, set deliverables and a success threshold before you start, run it, then interpret the result including the case where it's inconclusive. Skipping the "before you start" steps is what turns a spike into an unfalsifiable exercise where any result gets rationalized afterward as "directionally promising."
-
Frame the uncertainty as a falsifiable question. Not "let's explore whether we can support real-time sync with this partner," but "we believe webhook round-trip latency to this partner's sandbox API will be under 2 seconds for most events; if true we build on webhooks, if false we fall back to polling."
-
Scope and timebox. Pick the smallest test that would actually move your confidence on that specific question, and box it in days, not weeks, for example a 3-day spike. If you can't state the timebox in days, the scope is still too broad.
-
Deliverables and success criteria, locked before you run anything. Deliverable: a working prototype demonstrating the round trip against the partner's sandbox for at least 50 test events. Success criterion: round-trip latency under 2 seconds for at least 90% of those events. Writing the threshold down before you see any data is what makes the result mean something; otherwise any outcome gets reinterpreted as good enough after the fact.
-
Run it, then interpret three possible outcomes, not two. A spike doesn't just pass or fail, it can also come back inconclusive, and you need a predefined response for that case too, not an improvised one. Take a debugging example rather than a build example: an on-call engineer spikes a 3-day investigation into a flaky checkout failure, hypothesizing database connection-pool exhaustion. The spike adds pool-utilization metrics and retry logging. The result: pool utilization is near saturation during 2 of the 5 observed failures, but not the other 3, an inconclusive signal, neither confirmation nor rejection. The predefined response for exactly this case: don't declare the root cause found, apply a cheap mitigation anyway (widen the connection pool, since it's low-cost and directionally justified even under uncertainty), extend the observation window by a week with the logging left in place, and open a tracked follow-up so the open question doesn't silently disappear once the immediate pressure is off.
-
Communicate the result either way, and frame it as roll-forward or rollback. Even a null or inconclusive result is a shipped learning. Write two paragraphs, what was tried and what was learned, and share it with adjacent teams so nobody re-runs the same spike next quarter. State explicitly whether the mitigation is staying (roll-forward, with the criteria that would make you revert it) or whether you're reverting it (rollback, and why).
For a bigger ambiguous decision, chain spikes with a decision gate between each rather than running one big test. For example, validating whether a new ranking approach will actually help: stage 1, hand-sample and manually review 20 examples (cheap, a day); gate, if the signal looks real, proceed to stage 2, an offline evaluation against a held-out set, possibly using synthetic data to cover edge cases the real data doesn't have enough of; gate, if the offline eval is still positive, proceed to stage 3, a small live A/B test on a slice of real traffic. Each gate is a checkpoint where you can stop cheaply instead of committing the full test upfront.
The trap: running the spike without a threshold defined in advance. Without that, whatever the spike produces gets described as "promising" or "a good sign" regardless of the actual numbers, because nobody agreed beforehand on what would have counted as a failure.
Tell me about a time you took initiative on a larger or higher-impact problem that nobody assigned to you (for example: a recurring quality problem, a failing training job or pipeline right before a deadline, a data-quality issue that threatened a deliverable, or resistance to a change you knew was needed). Describe the concrete steps you took to drive it to resolution despite constraints, limited authority, or resistance, and the measurable impact.
Sample Answer
Direct answer
Pick the problem based on real impact rather than visibility, build a small credible first result to earn the standing to push further, and keep going despite resistance or a lack of formal authority by making the cost of the status quo concrete to the people who could actually unblock you.
Structured elaboration
- Recognize scope beyond a quick fix: this is bigger than something you can just quietly do alone, so the approach itself has to build support along the way, not only execute in isolation.
- Start with something small and contained you can do inside your own access, rather than asking for a broad mandate up front, to demonstrate the problem is real and the direction is right.
- Use that early proof to make the cost of doing nothing concrete to whoever's buy-in or code you actually need, rather than arguing the point in the abstract.
- Where you hit resistance or lack formal authority, address the actual objection, whose time it costs, whose code it touches, rather than repeating the same pitch louder.
- Track and report the measurable impact once resolved, so the initiative reads as a delivered result, not just a completed effort.
Worked example
A nightly model-retraining pipeline had been intermittently failing for weeks, and the team's workaround was to manually re-trigger it each morning, so it never showed up as a real incident. Nobody owned it because the pipeline crossed a job built by data engineering and a model owned by the machine learning team, and each side assumed the other was tracking it. Tracing one failure to a schema change upstream that the retraining job was not handling, a contained fix was built in a day, adding validation and a clear error message for just that one failure mode. Showing the data-engineering lead the actual failure logs alongside the manual-retrigger pattern in the on-call history, a cost that had been invisible because nobody had tallied it, earned the buy-in to extend the validation to the other failure modes over the following week, something the team had been reluctant to prioritize when it was framed as a routine review request rather than shown as an ongoing cost. The manual re-triggering stopped being needed within two weeks of the fix landing.
Trade-offs and pitfalls
A common wrong turn is trying to fix an entire cross-team problem in one large change before anyone trusts you with it, which tends to stall on review and ownership questions. Another is treating initial resistance as a final no rather than a signal the cost is not yet visible; a credible small result often changes the conversation more than repeating the ask. Also watch for claiming full ownership of a fix that genuinely needed another team's sign-off, which undermines the trust you are trying to build.
Someone you're mentoring has been stuck on a hard problem for a while and asks for help. Walk through how you decide whether to pair with them, give a hint, or step in directly.
Sample Answer
Direct answer
Default to a diagnostic question or a hint first, since that's the cheapest intervention and preserves ownership of the solution. Escalate to pairing when hints aren't moving them or they're clearly missing a building block they can't discover alone in reasonable time. Reserve stepping in directly for cases bounded by a hard constraint: a real deadline, cost, safety issue, or someone else being blocked by their block.
Decision framework
Start with a diagnostic question, not a hint. "What have you tried, and what's your current hypothesis?" tells you whether they're missing information, missing a concept, or just haven't structured their attempts yet. This costs almost nothing and often unblocks people on its own.
Escalate to pairing when the pattern repeats. If they're cycling through the same failed approach without adjusting, or they're missing a conceptual piece they genuinely can't discover unaided in the time available, sit with them. Let them keep driving; you're there to redirect attention, not take over.
Escalate to stepping in directly only under a real constraint. A hard deadline, a cost or safety issue, someone else waiting on this to move, or clear signs of demoralization (not just frustration) are the legitimate triggers. "I could solve this faster myself" is not one of them; that's true of almost every delegation ever made.
Time-box the struggle explicitly. Instead of leaving it open-ended, agree on a checkpoint: "take another thirty minutes with this angle, then let's regroup regardless of where you land." This protects both their learning and the actual delivery timeline.
Debrief after any intervention, at any level. Even a small hint deserves a quick "here's the reasoning trap you were in" afterward, so the moment converts into a transferable lesson instead of just an unblock.
Worked example
Someone you're mentoring has been stuck for a while and comes to you for help. You ask what they've tried and what they currently believe is going wrong. Their answer reveals a specific reasoning gap, not a knowledge gap, so you give a pointed hint rather than the answer itself. They make progress but hit a second wall later, closer to a real deadline, and this time you sit down and pair with them directly, letting them stay at the keyboard while you ask redirecting questions. Once it's resolved, you debrief separately from the fix itself: what was the actual reasoning trap, and what's the general takeaway for the next similar problem, distinct from the specific bug.
Trade-offs and pitfalls
Defaulting to stepping in because it's faster erodes the person's own problem-solving muscle over time and can create a pattern where they escalate immediately instead of trying, because they've learned help arrives fast if they ask.
Refusing to intervene out of a rigid "let them struggle" stance burns real time and morale, and can backfire if they land on a fragile or outright wrong solution through persistence rather than understanding, and you didn't catch it.
The honest trade-off with hints: they preserve the person's ownership of the solution, but they slow things down and risk letting someone loop past the point where struggle is still productive into the point where it's just frustration with no learning attached.
A subtler failure mode worth naming: a "hint" that's actually the answer in disguise. It looks like coaching and feels generous, but the person doesn't actually earn the insight, and you won't be able to tell the difference from watching them succeed.
Explain Kotlin's null-safety features and the typical patterns used in Android: nullable types, safe-call operator (?.), Elvis operator (?:), non-null assertion (!!). Also explain differences between lateinit var and lazy { } delegates and when you'd use each in an Android component.
Sample Answer
Kotlin null-safety overview
- Kotlin types are non-null by default:
val s: String = "hi". To allow null:val s: String? = null. - Compiler forces you to handle nullable types to avoid NPEs.
Common operators & patterns
- Safe-call
?.— call only if not null, returns null otherwise:
val len = user?.name?.length
- Elvis
?:— provide a default when left side is null:
val display = user?.name ?: "Anonymous"
- Non-null assertion
!!— force unwrap, throws NPE if null (avoid except for quick checks):
val must = user!!.id
- Smart casts —
if (s != null) { /* s treated as non-null */ }
lateinit vs lazy
lateinit var(mutable, non-null) — for vars initialized later (e.g., view references, injected deps). Useful in Android components where lifecycle supplies value:
lateinit var binding: ActivityMainBinding
override fun onCreate(...) {
super.onCreate(...)
binding = ActivityMainBinding.inflate(layoutInflater)
}
val lazy { }(immutable, thread-safe by default) — deferred initialization on first access, good for expensive computations or singletons:
private val repo by lazy { RepoImpl() }
When to use which
- Use
lateinitfor lifecycle-initialized, mutable properties (views, DI fields) where you guarantee init before use. - Use
lazyfor read-only, possibly expensive initialization that you want only when needed.
Keep !! rare; prefer safe-call + Elvis or explicit checks to provide robust Android code.
What are over-fetching and under-fetching in client-server APIs, and how do REST and GraphQL each deal with them? Describe what a frontend or mobile client feels from each approach.
Sample Answer
Direct answer
Over-fetching means the response carries more data than the screen uses. Under-fetching means one response is not enough, so the client must make follow-up requests to assemble a screen. Both waste the client's time, data allowance and battery. REST fixes them by shaping resources and endpoints on the server: sparse fieldsets (a fields= parameter that lists the only fields the client wants, shown below), embedded related data, or screen-specific endpoints. GraphQL, a query language where the server publishes a schema (a typed list of every object and field a client may ask for), fixes them by letting the client name exactly the fields it wants in a single request, at the price of a heavier server and a harder caching story.
What each problem looks like
Take a feed screen. Each row shows a post title, the author's name and a thumbnail.
- Over-fetching.
GET /postsreturns the whole post: body text, tags, view counts, edit history. The row uses three fields. If each post is 2,000 bytes and a row needs about 100, a page of 20 rows downloads 20 x 2,000 = 40,000 bytes to render 20 x 100 = 2,000 bytes of content, a factor of 20. The phone also parses all of it as JSON (JavaScript Object Notation) and holds it in memory. - Under-fetching.
GET /postsreturnsauthorIdbut not the name. If the 20 posts have 3 distinct authors, the client makes 1 + 3 = 4 requests (the pattern is called N+1: one request for the list, then one more per distinct related item). The author lookups cannot start until the list has arrived, so the screen waits for at least two sequential network round trips (list, then authors), and each extra hop on a weak cellular link is a chance to stall.
How REST deals with it
REST (resources addressed by URL, standard HTTP verbs) has no built-in query language, so you shape responses with conventions:
- Sparse fieldsets:
GET /posts?fields=id,title,author.name,thumbnailUrl. - Embedding or inclusion:
GET /posts?embed=authororinclude=author, so related data rides along (JSON:API, a public REST convention, definesfields[TYPE]andincludeand requires400 Bad Requestwhen a server does not supportinclude). - Screen-shaped endpoints:
GET /screens/feed, which belongs to a Backend-for-Frontend (BFF, a server layer owned by the client team that returns exactly what one client needs).
How GraphQL deals with it
GraphQL exposes one typed schema. The client sends a query that names fields, and the response mirrors its shape:
{ posts(first: 20) { id title author { name } thumbnailUrl(width: 96) } }
Over-fetching disappears because only named fields come back. Under-fetching disappears because the nested author { name } is resolved on the server in the same request (a resolver is the server function that produces the value of one field, here the author's name). Per the GraphQL over HTTP documentation, servers must accept POST for queries and mutations (mutations are the GraphQL operations that write data) and may accept GET for queries only. A response can hold both data and errors, and a response with non-null data should still use a 2xx status, because HTTP has no status for partial success.
What the client feels
| Concern | REST with fieldsets / BFF | GraphQL |
|---|---|---|
| Bytes per screen | Small if the server implements shaping; fixed endpoints over-fetch for other screens | Small by construction, per query |
| Round trips | 1 with embeds or a screen endpoint, otherwise 1 + N (one list request plus one per related item) | 1 per screen query |
| Client CPU | Parses a small JSON; no query building | Parses a small JSON; a client library may normalize results into a cache (split each response into one record per object, keyed by id, so an author shared by many posts is stored once), and that splitting and merging costs CPU on low-end devices |
| CDN (content delivery network) caching | Easy: URL is the cache key, GET is cacheable | Hard with POST; possible with GET plus persisted query ids (short identifiers that replace long query text, which also avoids URL length limits) |
| Developer velocity | Frontend waits for a new field or endpoint if the shape is missing | Frontend adds a field to its own query, no backend ticket, if the schema already exposes it |
| Versioning | New fields are additive; breaking shapes need /v2 or negotiation | Add fields freely and mark old ones with the built-in @deprecated directive (an annotation on a schema field that tells tools and developers the field is going away); usage is visible per field |
| Error handling | HTTP status per request tells the story | Often HTTP 200 with an errors array and partial data, so clients must inspect the body |
Which screens feel it most
- Personalized feed: many small rows, several related entities per row (author, counts, reaction). Under-fetching dominates, so one composed request (GraphQL query or BFF endpoint) matters most.
- Settings screen: one small object, rarely changing. Plain REST is fine and caches well; GraphQL adds little.
- Analytics sync: the client uploads or downloads bulk data in the background. The cost is bytes and radio wake-ups (every time the phone's cellular radio leaves idle to send a request it draws extra battery, so many small requests cost more energy than one batched request), not flexible field choice. Batch it into one request and compress it; a query language is not the lever.
Pitfalls
- GraphQL does not remove over-fetching on the server: a resolver (the function that produces one field) may still load the whole database row. Field selection saves wire bytes, not necessarily database work.
- A permissive
fields=parameter can leak internal columns. Validate it against an allowlist. - Choosing GraphQL to fix under-fetching, then discovering that each nested field issues its own database query (the N+1 problem), swaps a client problem for a server one.
Explain Swift's memory ownership model for value and reference types with emphasis on copy-on-write (CoW) semantics used by Array, Dictionary, and String. Describe how CoW works internally, how mutations trigger copying, and design considerations when implementing a custom collection type that must avoid unnecessary copies and remain performant.
Sample Answer
Ownership model — value vs reference types
- Swift value types (struct, enum) have copy semantics: assigning or passing copies the value logically. Reference types (class) share identity and are reference-counted (ARC).
- Many standard value types (Array, Dictionary, String) use a reference-counted mutable buffer under the hood plus copy-on-write (CoW) so copies are cheap until mutation.
How CoW works internally
- A value type holds a pointer to a heap-allocated buffer object that contains storage and metadata (count, capacity, element storage).
- The buffer is reference-counted by ARC. Multiple value instances can point to the same buffer.
- Before an in-place mutation, the runtime checks buffer uniqueness:
- For Swift-managed buffers it uses isKnownUniquelyReferenced(&buffer) to test ARC count.
- For bridged ObjC storage there are other checks (bridging/copying).
- If not unique, the mutating operation allocates a new buffer and copies elements (deep copy of storage), then mutates the new buffer. This preserves value semantics.
When mutations trigger copying
- Any mutating operation that would change contents or capacity (append, remove, sort, inout mutation) triggers the uniqueness check.
- read-only operations don’t copy.
- reserveCapacity can preemptively allocate unique storage to avoid repeated copies.
Designing a custom CoW collection
- Use a private final class Storage { var elements: UnsafeMutableBufferPointer<Element>; var count, capacity } and expose a struct wrapper.
- Always run guard isKnownUniquelyReferenced(&storage) in mutating methods and call makeUnique() to clone when needed.
- Provide reserveCapacity to pre-allocate and avoid repeated realloc/copies.
- Keep storage contiguous when possible for performance and bridging with C APIs.
- Avoid unnecessary copies: minimize intermediate mutations, implement in-place algorithms when unique, use move semantics where supported.
- Consider thread-safety: CoW uniqueness checks are not synchronization; concurrent mutations require external synchronization.
- Benchmark with realistic workloads and use Instruments to inspect allocations and refcounts.
Result: correct CoW yields cheap reads and isolated writes; proper Storage design, uniqueness checks, and capacity management avoid surprising copies and keep performance competitive on mobile.
A phone streams sensor readings at a high rate. You must transform them off the main thread, keep memory bounded when processing falls behind, and hand finished batches to the UI with low latency. Build this as a reactive pipeline in RxSwift, RxKotlin or Flow and explain what you chose at each stage and why.
Sample Answer
Direct answer
The sensor cannot be slowed down, so the pipeline must decide what to do when it is outrun, and it must decide explicitly. My choice: take readings from the platform callback without ever blocking it, put them into a bounded buffer that drops the oldest reading when full (sensor data is perishable: a reading loses its value within moments, so the newest one matters most), transform on a background thread, group results into batches of at most 32 or 50 ms, whichever comes first, and deliver each batch on the UI thread. The pipeline is shown in Kotlin Flow (the option built on coroutines, where work started inside a scope is cancelled when the scope ends), in RxJava 3 Flowable (the library RxKotlin wraps) and in Swift with a built-in AsyncStream; all three were compiled and run. Memory is bounded because every queue in the chain has a fixed size; the batch time limit keeps latency low when the sensor is quiet; cancelling the consumer unregisters the sensor listener.
Stage by stage
Back-pressure means the slow consumer limiting how fast the producer may send. A hardware sensor callback cannot be told to wait, so here "back-pressure" has to be a policy for the surplus: drop, keep the latest, buffer without limit (unsafe), or fail.
| Stage | Flow | RxJava 3 / RxKotlin | Why |
|---|---|---|---|
| Source | callbackFlow { register; trySend; awaitClose { unregister } } | Flowable.create(..., BackpressureStrategy.MISSING) with setCancellable | Wraps the callback. trySend / onNext never suspend, so the sensor thread is never blocked. awaitClose / setCancellable unregister the listener on cancel, so a closed screen stops draining the battery. |
| Overflow policy | .buffer(64, BufferOverflow.DROP_OLDEST) | .onBackpressureBuffer(64, null, DROP_OLDEST) | Bounded memory. Drop oldest because a stale reading is worth less than a fresh one. conflate() is the same with capacity 1 and suits "latest value only" UI. Documented: buffer with a non-SUSPEND overflow never suspends its upstream. |
| Off the main thread | .map(transform).flowOn(Dispatchers.Default) | .observeOn(Schedulers.computation(), false, 16) then .map | flowOn changes the context of everything above it, not below. The observeOn prefetch of 16 bounds its queue. |
| Batching | custom batched(32, 50 ms) | .buffer(50, MILLISECONDS, 32) | Fewer UI updates, but the time limit means a slow sensor still delivers a partial batch. |
| Empty batches | not produced | .filter { it.isNotEmpty() } | RxJava's buffer(time, count) also emits empty lists on quiet ticks; without the filter the UI receives empty batches (the test below fails when the filter is removed). |
| To the UI | collect in the UI dispatcher | .observeOn(ui) | Only the final, small stream touches the UI thread. |
Terms in the table: callbackFlow turns a listener-style API into a Flow; trySend hands one value to that Flow and returns at once instead of waiting for room; awaitClose keeps the Flow open until the collector cancels and then runs its cleanup block. In Rx, Flowable.create does the same job: BackpressureStrategy.MISSING means "apply no policy here" (the next operator supplies it), and setCancellable registers the cleanup that runs on dispose. A prefetch is how many items an operator requests from upstream ahead of need, so observeOn(..., 16) keeps at most 16 queued between the threads. Schedulers.computation() is RxJava's fixed pool of threads sized for CPU-bound work, the counterpart of Dispatchers.Default. DROP_OLDEST discards the longest-waiting item when the buffer is full.
The Flow pipeline builds its batches in the collector's context, so collecting on the UI dispatcher delivers them there. Flow has no built-in "count or time" operator, which is why batched is written out: a channelFlow with a mutex-guarded list, a ticker coroutine that flushes after the wait, a flush when the list reaches the size limit, and a final flush when the stream ends. In order: the collector appends each reading to batch under the lock and, if that makes 32, calls flush() at once. flush() swaps in a fresh list under the lock and sends the full one outside it, so a slow consumer never holds the lock. The ticker coroutine calls the same flush() every 50 ms, which delivers whatever has accumulated (it is not reset per batch, so a flush can come sooner than 50 ms after a batch started). The lock is there because the collector and the ticker are two coroutines that can interleave, or run on different threads under a multi-threaded dispatcher, and both touch batch. When the sensor stops, the ticker is cancelled and the leftover items go out in a last flush.
Which to pick. For new Android code, Flow: cancellation is tied to a coroutine scope, there is no separate disposable to forget, and callbackFlow is built for listener APIs. Choose RxKotlin or RxJava when the app already standardises on Rx and needs its operator set. Both express the same four decisions above. RxSwift's documentation covers observeOn, subscribeOn, MainScheduler and background schedulers for the off-main-thread and UI-delivery stages, but documents no back-pressure mechanism, so on iOS the drop-oldest policy would have to be applied where the sensor callback hands values to Rx (a small bounded buffer of your own) rather than being an operator in the chain. Swift's standard library has such a buffer: AsyncStream with .bufferingNewest(64) keeps at most 64 waiting values and discards the oldest when a new one arrives. A producer thread stands in for the sensor callback (yield never blocks it), and a for await loop is the slow consumer:
import Foundation
struct Reading: Sendable { let seq: Int; let x: Double }
func transform(_ r: Reading) -> Int { // CPU work per reading, slower than the producer
var acc = r.x
for _ in 0..<3_000 { acc = (acc * acc + 1.0).squareRoot() }
return r.seq
}
let total = 100_000
// bufferingNewest(64): when 64 readings are waiting, the oldest is discarded to make room.
let (stream, continuation) = AsyncStream.makeStream(of: Reading.self, bufferingPolicy: .bufferingNewest(64))
// Stand-in for the platform sensor callback: its own thread, never waits for the consumer.
let producer = Thread {
for i in 1...total { continuation.yield(Reading(seq: i, x: Double(i))) } // yield never blocks
continuation.finish()
}
producer.start()
// Consumer: leaves the producer's thread behind and processes one reading at a time.
var seen: [Int] = []
for await reading in stream {
seen.append(transform(reading))
}
func report(_ name: String, _ ok: Bool) { print(ok ? "PASS" : "FAIL", name); precondition(ok) }
report("some readings were dropped", seen.count < total)
report("the newest reading was delivered", seen.last == total)
report("order preserved", zip(seen, seen.dropFirst()).allSatisfy { $0 < $1 })
Compiled with Swift 6.0.3 (swiftc -swift-version 5, the swift:6.0 container, aarch64 Linux), it prints:
PASS some readings were dropped
PASS the newest reading was delivered
PASS order preserved
The values from this stream can be handed to an Rx pipeline (or consumed directly) on the main actor for the UI stage; the same three decisions (never block the callback, drop oldest at a fixed bound, process off the main thread) apply.
The code and its tests
A fake sensor stands in for the platform's sensor manager: it calls listeners on its own thread as fast as the producer loop runs (100,000 readings in a tight loop). The transform does CPU work per reading so it is slower than the producer. The checks assert properties, not exact counts, because how many readings are dropped depends on timing: some are dropped, the newest reading is always delivered, order is preserved, no batch exceeds 32, the transform ran on a background thread, delivery was on the UI thread, a quiet sensor still produces a partial batch, a finished stream flushes its last partial batch, a quiet tick produces no empty batch, and cancelling unregisters the listener. A failed check throws an AssertionError and the program exits with a non-zero status (the UI executor's thread is a daemon thread, so the JVM does not wait for it). A control pipeline with an unbounded buffer must still have most of its input queued when the producer stops, showing what the bound prevents.
import io.reactivex.rxjava3.core.BackpressureOverflowStrategy
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
data class Reading(val seq: Int, val x: Double)
data class Sample(val seq: Int, val magnitude: Double, val thread: String)
// A stand-in for SensorManager: the platform calls the listener on ITS thread, whenever it likes, and cannot be slowed down.
class FakeSensor {
private val listeners = CopyOnWriteArrayList<(Reading) -> Unit>()
val listenerCount get() = listeners.size
fun register(l: (Reading) -> Unit) { listeners.add(l) }
fun unregister(l: (Reading) -> Unit) { listeners.remove(l) }
fun emit(r: Reading) { listeners.forEach { it(r) } }
}
fun transform(r: Reading): Sample { // deliberately slower than the producer: CPU work per reading
var acc = r.x
repeat(3_000) { acc = Math.sqrt(acc * acc + 1.0) }
return Sample(r.seq, acc, Thread.currentThread().name)
}
// ---------- Kotlin Flow ----------
fun FakeSensor.readings(): Flow<Reading> = callbackFlow {
val listener: (Reading) -> Unit = { trySend(it) } // never suspends: a sensor callback must not block
register(listener)
awaitClose { unregister(listener) } // runs when the collector is cancelled
}
// Flow has no built-in "size or time, whichever comes first" operator, so this one is written out.
fun <T> Flow<T>.batched(maxSize: Int, maxWaitMs: Long): Flow<List<T>> = channelFlow {
val lock = Mutex()
var batch = ArrayList<T>(maxSize)
suspend fun flush() {
val out: ArrayList<T>? = lock.withLock { if (batch.isEmpty()) null else batch.also { batch = ArrayList(maxSize) } }
if (out != null) send(out)
}
val ticker = launch { while (true) { delay(maxWaitMs); flush() } } // a quiet sensor still delivers what it has
collect { v ->
val full = lock.withLock { batch.add(v); batch.size >= maxSize }
if (full) flush()
}
ticker.cancelAndJoin()
flush() // the final partial batch when the stream ends
}
fun flowPipeline(sensor: FakeSensor): Flow<List<Sample>> =
sensor.readings()
.buffer(capacity = 64, onBufferOverflow = BufferOverflow.DROP_OLDEST) // bounded memory: keep the newest 64
.map(::transform) // heavy work ...
.flowOn(Dispatchers.Default) // ... runs on a background thread; everything above this line
.batched(maxSize = 32, maxWaitMs = 50) // batches are built and delivered in the collector's context
// ---------- RxJava 3 (what RxKotlin wraps) ----------
fun rxPipeline(sensor: FakeSensor, ui: io.reactivex.rxjava3.core.Scheduler): Flowable<List<Sample>> =
Flowable.create<Reading>({ emitter ->
val listener: (Reading) -> Unit = { emitter.onNext(it) }
sensor.register(listener)
emitter.setCancellable { sensor.unregister(listener) }
}, BackpressureStrategy.MISSING) // the sensor cannot be slowed, so choose the policy explicitly next
.onBackpressureBuffer(64, null, BackpressureOverflowStrategy.DROP_OLDEST)
.observeOn(Schedulers.computation(), false, 16) // hand over to a background thread with a small prefetch
.map(::transform)
.buffer(50, TimeUnit.MILLISECONDS, 32) // up to 32 items or 50 ms, whichever first
.filter { it.isNotEmpty() } // buffer(time, count) also emits EMPTY lists on quiet ticks
.observeOn(ui) // deliver on the UI thread
fun check(name: String, ok: Boolean) { println("${if (ok) "PASS" else "FAIL"} $name"); if (!ok) throw AssertionError(name) }
fun main() = runBlocking {
val uiThread = Executors.newSingleThreadExecutor { Thread(it, "ui-thread").apply { isDaemon = true } } // daemon: a failed check must end the JVM, not hang it
val uiDispatcher = uiThread.asCoroutineDispatcher()
val total = 100_000
println("== Flow ==")
val sensor = FakeSensor()
val batches = ArrayList<List<Sample>>()
val collectorThreads = HashSet<String>()
val job = launch(uiDispatcher) {
flowPipeline(sensor).collect { batches.add(it); collectorThreads.add(Thread.currentThread().name) }
}
while (sensor.listenerCount == 0) delay(5)
val producer = Thread { for (i in 1..total) sensor.emit(Reading(i, i.toDouble())) } // hammer: ~no pauses
producer.start(); producer.join()
delay(1_000) // let the pipeline drain; slow tail is dropped data, not backlog
val all = batches.flatten()
check("some readings were dropped because processing fell behind", all.size < total)
check("the newest reading was delivered", all.last().seq == total)
check("order preserved (strictly increasing seq)", all.zipWithNext().all { (a, b) -> a.seq < b.seq })
check("no batch larger than 32", batches.all { it.size <= 32 })
check("transform ran off the main thread", all.all { it.thread.startsWith("DefaultDispatcher-worker") })
check("batches were delivered on the ui thread", collectorThreads == setOf("ui-thread"))
job.cancelAndJoin()
check("cancelling the collector unregistered the sensor listener", sensor.listenerCount == 0)
println("== Flow: slow sensor still delivers a partial batch ==")
val slow = FakeSensor()
val got = CompletableDeferred<List<Sample>>()
val job2 = launch(uiDispatcher) { flowPipeline(slow).collect { got.complete(it) } }
while (slow.listenerCount == 0) delay(5)
repeat(3) { slow.emit(Reading(it + 1, 1.0)) }
val partial = withTimeoutOrNull(2_000) { got.await() }
check("3 readings arrive as one partial batch without waiting for 32", partial?.size == 3)
job2.cancelAndJoin()
println("== Flow: batching edge cases ==")
check("a finished stream flushes its last partial batch", flowOf(1, 2, 3, 4, 5).batched(32, 10_000).toList() == listOf(listOf(1, 2, 3, 4, 5)))
check("quiet ticks produce no empty batch", flow { delay(300); emit(1) }.batched(32, 50).toList() == listOf(listOf(1)))
println("== Control: unbounded buffer keeps everything ==")
val s3 = FakeSensor()
val received = AtomicInteger()
val job3 = launch(uiDispatcher) {
s3.readings().buffer(kotlinx.coroutines.channels.Channel.UNLIMITED).map(::transform).flowOn(Dispatchers.Default).collect { received.incrementAndGet() }
}
while (s3.listenerCount == 0) delay(5)
val p3 = Thread { for (i in 1..total) s3.emit(Reading(i, i.toDouble())) }
p3.start(); p3.join()
val backlogRightAfterProducerStops = total - received.get()
check("unbounded: most of the input is still queued when the producer stops", backlogRightAfterProducerStops > total / 2)
job3.cancelAndJoin()
println("== RxJava 3 ==")
val rxSensor = FakeSensor()
val rxBatches = java.util.Collections.synchronizedList(ArrayList<List<Sample>>())
val rxThreads = java.util.Collections.synchronizedSet(HashSet<String>())
val uiScheduler = Schedulers.from(uiThread)
val disposable = rxPipeline(rxSensor, uiScheduler).subscribe { rxBatches.add(it); rxThreads.add(Thread.currentThread().name) }
val rp = Thread { for (i in 1..total) rxSensor.emit(Reading(i, i.toDouble())) }
rp.start(); rp.join()
delay(1_500)
val rxAll = rxBatches.flatten()
check("rx: some readings were dropped", rxAll.size < total)
check("rx: the newest reading was delivered", rxAll.last().seq == total)
check("rx: no empty batch reached the UI", rxBatches.none { it.isEmpty() })
check("rx: no batch larger than 32", rxBatches.all { it.size <= 32 })
check("rx: transform ran on a computation thread", rxAll.all { it.thread.startsWith("RxComputationThreadPool") })
check("rx: delivered on the ui thread", rxThreads == setOf("ui-thread"))
disposable.dispose()
check("rx: dispose unregistered the listener", rxSensor.listenerCount == 0)
uiThread.shutdown()
}
Run in an eclipse-temurin:21 container (JDK 21, Kotlin 2.0.21, kotlinx-coroutines 1.9.0, RxJava 3.1.9), the program printed the following and exited with status 0 on every repeated run:
== Flow ==
PASS some readings were dropped because processing fell behind
PASS the newest reading was delivered
PASS order preserved (strictly increasing seq)
PASS no batch larger than 32
PASS transform ran off the main thread
PASS batches were delivered on the ui thread
PASS cancelling the collector unregistered the sensor listener
== Flow: slow sensor still delivers a partial batch ==
PASS 3 readings arrive as one partial batch without waiting for 32
== Flow: batching edge cases ==
PASS a finished stream flushes its last partial batch
PASS quiet ticks produce no empty batch
== Control: unbounded buffer keeps everything ==
PASS unbounded: most of the input is still queued when the producer stops
== RxJava 3 ==
PASS rx: some readings were dropped
PASS rx: the newest reading was delivered
PASS rx: no empty batch reached the UI
PASS rx: no batch larger than 32
PASS rx: transform ran on a computation thread
PASS rx: delivered on the ui thread
PASS rx: dispose unregistered the listener
Which check proves which decision: "some readings were dropped" and the unbounded control show the bound is real (the control keeps everything and falls behind); "the newest reading was delivered" shows the policy is drop-OLDEST rather than drop-newest; "order preserved" shows dropping never reorders; "no batch larger than 32" and "3 readings arrive as one partial batch" show the size limit and the 50 ms limit; the two batching edge cases show that the Flow batched operator flushes the leftover items when the stream ends and never emits an empty list (each check fails when the matching line in flush() or the final flush() is removed); "transform ran off the main thread" shows the flowOn / observeOn(computation) stage; "delivered on the ui thread" shows the final hop; "cancelling ... unregistered" and "dispose unregistered" show the awaitClose / setCancellable cleanup; "no empty batch reached the UI" shows the filter.
Trade-offs and pitfalls
- Dropping is a product decision. For a live chart or a gesture it is right. If every sample must be kept (for example a recording), do not drop: write to a file or database in the background and let the UI read a downsampled view.
- Capacity 64 and batch limits 32 / 50 ms are starting points, not rules. Size the buffer to cover the longest pause you expect from the transform (a garbage-collection pause or a slow frame), and size the batch time to the UI's refresh need.
- Unbounded buffers hide the problem until the app runs out of memory.
Channel.UNLIMITEDor RxonBackpressureBuffer()with no capacity is the control in the test. flowOnonly moves what is above it. Putting it after the collector's code does not move the collector.- Never do work in the sensor callback. Do the minimum (
trySend) and return. - Lifecycle: collect only while the screen is visible, so the listener is registered only when someone is looking.
Running the code
mkdir demo && cd demo && cp /path/to/SensorPipeline.kt .
curl -fsSL -O https://github.com/JetBrains/kotlin/releases/download/v2.0.21/kotlin-compiler-2.0.21.zip && jar xf kotlin-compiler-2.0.21.zip
curl -fsSL -o cor.jar https://repo1.maven.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core-jvm/1.9.0/kotlinx-coroutines-core-jvm-1.9.0.jar
curl -fsSL -o rx.jar https://repo1.maven.org/maven2/io/reactivex/rxjava3/rxjava/3.1.9/rxjava-3.1.9.jar
curl -fsSL -o rs.jar https://repo1.maven.org/maven2/org/reactivestreams/reactive-streams/1.0.4/reactive-streams-1.0.4.jar
bash kotlinc/bin/kotlinc SensorPipeline.kt -cp cor.jar:rx.jar:rs.jar -d out
java -cp out:cor.jar:rx.jar:rs.jar:kotlinc/lib/kotlin-stdlib.jar SensorPipelineKt
# Swift: save the Swift listing as sensor_stream.swift, then in the swift:6.0 image run
swiftc -swift-version 5 sensor_stream.swift -o sensor_stream && ./sensor_stream
What items should a code-review checklist contain to enforce production-quality, defensive-programming standards across distributed teams? Draft a prioritized checklist of at least eight review items, and for each one explain why it directly impacts production reliability or operability.
Sample Answer
Direct answer
A code-review checklist for defensive, production-quality standards should be short enough that reviewers actually use it every time, and should focus on the handful of items that correlate most directly with real production incidents: error handling, observability, resource leaks, secrets management, idempotency, and input validation, each with a concrete one-line test a reviewer can actually apply while reading a diff.
Structured elaboration
1. Error handling. Does every external call (network, database, file system) have explicit failure handling, and is there no bare, silent catch-and-ignore? This matters because a swallowed exception is one of the most common root causes of "the system silently stopped working and nobody noticed for days".
2. Observability. Does this change add or preserve logging/metrics for its new failure paths, not just its happy path? A new code path with no visibility into whether it's failing in production is effectively unmonitored the moment it ships.
3. Resource leaks. Are file handles, database connections, and locks acquired in this diff guaranteed to be released even when an exception occurs (via try/finally, a context manager, or the language's equivalent)? This matters because a resource leak in an error path specifically (the path least likely to be exercised in normal testing) is a classic source of a slow production degradation that only appears under sustained load or over a long uptime.
4. Secrets management. Does this diff introduce any hardcoded credential, API key, or token, or log anything that could contain one? This is a fast, mechanical check (often automatable via a pre-commit secret scanner) but still worth a human's attention, since scanners miss secrets embedded in less obvious places like a debug log statement.
5. Idempotency. If this diff adds or touches an operation that could be retried (by a client, a queue redelivery, or an internal retry mechanism), is that operation actually safe to run more than once? This matters because a non-idempotent operation that silently becomes retriable somewhere in the call stack is a duplicate-side-effect bug waiting to happen, often not caught until production traffic patterns exercise the retry path that testing never did.
6+. Input validation and the remaining prioritized items. Does every externally-supplied input reaching this code get validated at a clear boundary, rather than trusted implicitly? Beyond these top items, a fuller checklist includes: test coverage for the new failure paths specifically (not just the happy path), whether any deprecated or discouraged pattern was introduced, and whether the change includes a rollback plan for anything touching a schema or a stateful migration.
Why these six, and why prioritized. Each is chosen because it maps directly to a common, real production-incident root cause, and they are ordered so a reviewer under time pressure who only gets through the first three still caught the highest-impact categories.
Worked example
A pull request adds a new endpoint that calls an internal payments service and writes a record to a local database. Applying the checklist: (1) error handling: the diff has a bare except: pass around the payments call, flagged; (2) observability: no log line exists for the payments-call failure path, flagged; (3) resource leaks: the database connection is correctly used inside a context manager, passes; (4) secrets: no hardcoded credentials found, passes; (5) idempotency: the endpoint is a POST that creates a payment record with no idempotency key, and the client-facing API documentation doesn't mention retry safety, flagged as a real production risk given payments-adjacent code specifically; (6) input validation: the request body is validated via a shared schema, passes. Three of six items are flagged, and the two most severe (the swallowed exception and the missing idempotency key on a payments-adjacent endpoint) block the merge, while the missing log line is a required fix but not necessarily a hard blocker if paired with a fast-follow commitment.
Trade-offs and pitfalls
A checklist with thirty items reliably gets skimmed rather than actually applied under normal review-time pressure; keeping it to the highest-impact handful, with a concrete one-line test for each, is what makes it something a reviewer genuinely runs through on every diff rather than something referenced once and then forgotten. The most common failure mode for a checklist like this is treating it as a one-time training exercise rather than something enforced consistently: without periodic reinforcement (referencing it explicitly in review comments, tracking how often flagged items actually get raised) it tends to fade from active use within a few months of being introduced.
Want to create your own tailored preparation guide using our deep research?
Get Started for FreeInterview-Ready Courses
Visual-first, interactive, structured learning paths
Browse Mobile Developer jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs