Amazon Senior Mobile Developer Interview Preparation Guide
Amazon's interview process for Senior Mobile Developers typically includes an initial recruiter screening, a technical phone screen, and a 4-5 round onsite interview loop. The onsite typically assesses mobile development technical expertise, system design and architectural thinking, performance optimization knowledge, behavioral alignment with Amazon Leadership Principles, and depth of technical knowledge through a bar raiser round. The entire process is designed to evaluate both technical capabilities and cultural fit.
Interview Rounds
Recruiter Screening
What to Expect
Your initial contact with Amazon's recruiting team. The recruiter will verify your background, confirm your interest in the role, discuss compensation expectations, and answer logistical questions about the interview process. This is your opportunity to ask about the team, the charter, and the hiring manager's leadership style. Be professional and responsive to the recruiter—they are your advocate throughout the process.
Tips & Advice
Be genuine and enthusiastic. Ask thoughtful questions about the team's goals, tech stack, and current challenges. Mention specific Amazon mobile products or services you're interested in. Avoid discussing compensation too early; let the recruiter lead that conversation. This is not a technical assessment, so focus on demonstrating cultural fit and genuine interest in the role.
Focus Topics
Compensation and Logistics Expectations
Be prepared to discuss salary expectations, relocation preferences, and timeline availability in a professional manner.
Practice Interview
Study Questions
Understanding of the Role and Team
Demonstrate familiarity with the mobile development landscape and show curiosity about the specific team's challenges and products.
Practice Interview
Study Questions
Motivation and Interest in Amazon
Clearly articulate why you want to work at Amazon specifically and what attracts you to this mobile developer role.
Practice Interview
Study Questions
Background and Experience Summary
Articulate your mobile development career journey, highlighting senior-level projects and your evolution as a developer.
Practice Interview
Study Questions
Technical Phone Screen
What to Expect
A 45-60 minute technical screening typically with a hiring manager or senior engineer. This round assesses your mobile development fundamentals and coding ability under pressure. You'll be expected to write code (often in a shared document or whiteboard tool) and discuss your approach. Questions may focus on data structures, algorithms, or mobile-specific scenarios. This is your first technical evaluation and sets the bar for the onsite rounds.
Tips & Advice
Think out loud and explain your approach before coding. Ask clarifying questions about requirements and constraints. For mobile-specific problems, discuss platform trade-offs (iOS vs Android). Be prepared to optimize your solution if asked. At the senior level, interviewers expect you to identify edge cases and propose scalable solutions. Practice on a collaborative document editor to simulate the real experience. Ensure your environment is quiet and your internet connection is reliable.
Focus Topics
Optimization and Scalability Thinking
Ability to analyze time and space complexity, identify bottlenecks, and propose optimized solutions.
Practice Interview
Study Questions
Code Quality and Communication
Writing clean, readable code with proper variable naming, comments, and clear logic flow. Explaining your reasoning while coding.
Practice Interview
Study Questions
Platform-Specific Knowledge (iOS or Android)
Deep familiarity with either iOS (Swift, UIKit/SwiftUI, memory management) or Android (Kotlin, Jetpack, lifecycle), or both.
Practice Interview
Study Questions
Mobile-Specific Problem Solving
Ability to solve problems in the context of mobile constraints (memory, battery, network latency, storage) and platform-specific APIs.
Practice Interview
Study Questions
Data Structures and Algorithms Fundamentals
Solid understanding of arrays, linked lists, trees, graphs, hashing, and common algorithms (sorting, searching, dynamic programming).
Practice Interview
Study Questions
Mobile Development Technical Interview (Onsite - Round 1)
What to Expect
This is the first onsite round focused on hands-on mobile development skills. You may be asked to design and implement a mobile feature, debug existing code, or solve a more complex mobile-specific problem. This round evaluates your practical mobile development expertise, understanding of platform conventions, and ability to think about user experience alongside technical implementation. Expect 45-60 minutes of deep technical discussion.
Tips & Advice
Come prepared with recent projects you've built and be ready to dive deep into technical decisions. If asked to implement a feature, start with a basic solution and iterate based on feedback. Discuss trade-offs between different approaches (native vs cross-platform, state management libraries, navigation patterns). At senior level, interviewers expect you to consider performance, testability, and maintainability. If you encounter an unfamiliar API or framework, think through how you would approach learning it rather than pretending to know. Ask clarifying questions about requirements, constraints, and success metrics.
Focus Topics
Cross-Platform Considerations
If applicable, understanding differences between iOS and Android development, or experience with cross-platform frameworks (React Native, Flutter, Kotlin Multiplatform).
Practice Interview
Study Questions
Testing and Debugging Mobile Applications
Unit testing, integration testing, UI testing frameworks. Debugging device-specific issues, using debugging tools, and understanding performance profiling.
Practice Interview
Study Questions
State Management and Architecture Patterns
Understanding MVC, MVVM, Redux, Bloc, or other architectural patterns. Managing app state across screens and lifecycle events.
Practice Interview
Study Questions
Mobile UI/UX Implementation
Building responsive user interfaces that work across different device sizes and orientations. Understanding mobile-specific UI patterns and frameworks (SwiftUI, Jetpack Compose, or cross-platform solutions).
Practice Interview
Study Questions
Platform-Specific Features and APIs
Deep understanding of camera integration, location services, push notifications, file handling, permissions, sensors, and other device-specific capabilities.
Practice Interview
Study Questions
Mobile Network and Data Management
Efficient API integration, handling network failures gracefully, caching strategies, background data sync, and understanding different network conditions.
Practice Interview
Study Questions
System Design and Mobile Architecture (Onsite - Round 2)
What to Expect
This round assesses your ability to design large-scale mobile systems and make architectural decisions. You may be asked to design a complex mobile feature or system (e.g., a photo sharing app, real-time messaging, offline-first app, or scalable social feed). The focus is on how you structure code, choose appropriate libraries, think about scalability, handle edge cases, and justify design trade-offs. This is critical for senior-level candidates who are expected to influence architecture decisions.
Tips & Advice
Start by clarifying requirements and constraints before diving into design. Discuss trade-offs between different approaches (e.g., monolithic app vs modularized architecture, local databases vs cloud sync, native vs cross-platform). At senior level, interviewers expect you to think holistically: user experience, code maintainability, team scalability, and testability. Draw diagrams if helpful. Discuss how your design handles edge cases like network failures, app backgrounding, and concurrent operations. Be prepared to explain why you chose certain libraries or patterns over alternatives. Show awareness of common pitfalls in mobile architecture (tight coupling, poor state management, inefficient data fetching).
Focus Topics
Error Handling and Resilience
Designing systems to gracefully handle network errors, crashes, permissions denial, and other failure modes. User experience in error scenarios.
Practice Interview
Study Questions
Modular and Component-Based Design
Breaking down large apps into feature modules, creating reusable components, and managing dependencies between modules.
Practice Interview
Study Questions
Performance Optimization and Scalability
Designing for app startup speed, memory efficiency, battery consumption, smooth animations, and handling growing user base and data volume.
Practice Interview
Study Questions
Mobile App Architecture Patterns
Designing scalable, maintainable mobile app architectures. Understanding layering (presentation, business logic, data), dependency injection, and clean code principles.
Practice Interview
Study Questions
Data Persistence and Synchronization
Designing systems for offline-first apps, local databases (SQLite, Realm, etc.), cloud synchronization, conflict resolution, and data consistency.
Practice Interview
Study Questions
Mobile Performance, Optimization, and Security (Onsite - Round 3)
What to Expect
This round dives deep into mobile-specific performance challenges, optimization techniques, and security best practices. You may be asked to debug a slow app, optimize battery drain, improve startup time, handle memory leaks, implement secure data storage, or design for different device capabilities. This round evaluates your depth of knowledge in mobile-specific concerns and your ability to solve real production problems.
Tips & Advice
Be familiar with platform-specific profiling tools (Xcode Instruments, Android Profiler, etc.) and common performance bottlenecks in mobile apps. Discuss concrete examples from your experience: 'I reduced app startup time from X to Y by doing Z.' Understand mobile security best practices like secure storage, certificate pinning, encryption, and permission handling. Be prepared to discuss trade-offs between security and usability. At senior level, you should be able to mentor others on these practices. Ask clarifying questions about performance requirements (e.g., 'What is acceptable latency for this feature?'). Show systematic thinking about identifying and solving performance issues.
Focus Topics
App Store Deployment and Distribution
App signing, versioning, release management, handling app store review processes, crash reporting, and continuous deployment practices.
Practice Interview
Study Questions
Device Compatibility and Fragmentation
Handling different OS versions, screen sizes, hardware capabilities, and vendor-specific behaviors. Backward compatibility and feature detection.
Practice Interview
Study Questions
Mobile Performance Analysis and Profiling
Using profiling tools to identify bottlenecks. Understanding CPU usage, memory consumption, battery drain, and rendering performance metrics.
Practice Interview
Study Questions
Battery and Power Optimization
Techniques to reduce battery drain: efficient networking (batching requests, smart caching), location services optimization, background task management, and CPU/GPU efficiency.
Practice Interview
Study Questions
Memory Management and Leak Prevention
Understanding memory model on iOS (ARC) and Android (GC). Identifying and preventing memory leaks, managing large data structures, and handling bitmap memory.
Practice Interview
Study Questions
Mobile Security Best Practices
Secure data storage (keychain, encrypted preferences), API security, certificate pinning, secure communication, permissions management, and handling sensitive user data.
Practice Interview
Study Questions
Amazon Leadership Principles (Onsite - Round 4)
What to Expect
This behavioral round assesses alignment with Amazon Leadership Principles through structured interview questions. You'll discuss past experiences and how they demonstrate principles like Customer Obsession, Ownership, Invent and Simplify, and others. Expect questions in STAR format (Situation, Task, Action, Result). This round evaluates cultural fit and your ability to think about problems from Amazon's perspective. A behavioral interviewer will look for evidence of impact and the lessons you learned.
Tips & Advice
Prepare 5-7 strong stories from your career that demonstrate different leadership principles. Use the STAR method: clearly describe the Situation and Task, explain the specific Actions you took (with emphasis on your role), and articulate the Result with quantifiable impact. For a senior-level developer, focus on stories that show: mentoring others, making architectural decisions that benefited the team, customer impact, handling failure and learning, and driving innovation. Research Amazon's 16 Leadership Principles and map your stories to them. Practice out loud; you should be comfortable telling these stories concisely (2-3 minutes each). Be authentic and specific rather than generic. Connect your examples back to why they matter for the mobile development role at Amazon.
Focus Topics
Amazon Leadership Principle: Learn and Be Curious
Seeking knowledge, adapting to new technologies, learning from failure, and having a growth mindset even at senior level.
Practice Interview
Study Questions
Amazon Leadership Principle: Dive Deep
Understanding details deeply, investigating root causes, asking detailed questions, and not accepting surface-level explanations.
Practice Interview
Study Questions
Amazon Leadership Principle: Invent and Simplify
Proposing new ideas, simplifying processes, and doing more with less. Not resting on existing solutions; finding simpler approaches to complex problems.
Practice Interview
Study Questions
Amazon Leadership Principle: Earn Trust
Being trustworthy, following through on commitments, asking tough questions, and building credibility through consistent delivery.
Practice Interview
Study Questions
Amazon Leadership Principle: Customer Obsession
Demonstrating deep understanding of customer needs, putting customer experience first, and making decisions based on customer impact rather than internal convenience.
Practice Interview
Study Questions
Amazon Leadership Principle: Ownership
Taking accountability for outcomes, thinking long-term, not making excuses, and being willing to work on unglamorous tasks to solve problems.
Practice Interview
Study Questions
Bar Raiser Technical Deep Dive (Onsite - Round 5)
What to Expect
This round is conducted by a 'Bar Raiser'—an experienced senior engineer or architect who ensures the hiring bar remains high. This is typically the most challenging round. You'll be asked a complex technical problem, asked to explain a project in extreme detail, or solve an ambiguous problem from scratch. The bar raiser evaluates whether you're truly senior-level: can you think strategically, handle ambiguity, make sound architectural decisions, and raise the bar for the team? Expect deep probing into your technical expertise and decision-making.
Tips & Advice
This is the hardest round. The bar raiser will dig into nuances and edge cases. Prepare by deeply understanding one or two major projects you've led: be ready to explain architectural decisions, trade-offs considered, what you'd do differently, and the impact. If given a design problem, don't rush to a solution; think out loud, ask clarifying questions, consider multiple approaches, and be honest about trade-offs and limitations. Show that you can operate at a strategic level while remaining technically grounded. When stuck, explain your thinking and ask for hints rather than guessing. At senior level, the bar raiser is looking for someone who will make the team better. Demonstrate learning from mistakes, mentoring mindset, and ability to influence decisions through reasoning.
Focus Topics
System Design at Scale
Designing systems that work as user base and data volume grow. Understanding load, latency, and availability trade-offs at a deep level.
Practice Interview
Study Questions
Mentoring and Raising the Bar
Evidence that you've elevated others, driven improvements in code quality or processes, and influenced team decisions for the better.
Practice Interview
Study Questions
Ambiguity and Novel Problem-Solving
Ability to tackle ill-defined problems, ask the right clarifying questions, break down complex challenges, and propose reasonable solutions with limited information.
Practice Interview
Study Questions
Deep Technical Expertise in Mobile Development
Mastery of your platform(s): iOS or Android (or both). Ability to explain complex technical concepts, understand nuances, and solve novel problems using fundamental principles.
Practice Interview
Study Questions
Architectural Decision-Making and Trade-off Analysis
Ability to evaluate multiple approaches, understand trade-offs (performance vs maintainability, security vs convenience, etc.), and justify design choices with reasoning.
Practice Interview
Study Questions
Frequently Asked Mobile Developer Interview Questions
Compare the secure storage options available to mobile developers on iOS and Android: iOS Keychain, Android KeyStore, EncryptedSharedPreferences, and plain SharedPreferences/NSUserDefaults. For each, describe typical use cases (a short-lived access token, a long-lived refresh token, an API key), the platform threat model (backup behavior, hardware-backed keys, Secure Enclave/TEE), and the recommended pattern to persist and rotate credentials securely on the device.
Sample Answer
Direct answer
On iOS, the choice is between the Keychain (encrypted, potentially hardware-backed) and NSUserDefaults (plain, unencrypted); on Android, it is between the KeyStore plus EncryptedSharedPreferences (encrypted, potentially hardware-backed) and plain SharedPreferences (unencrypted). The rule of thumb is simple even though the platform details are not: anything that grants access to a user's account or funds (a refresh token, an Application Programming Interface, API, key) belongs in the encrypted, hardware-backed option; anything that is genuinely non-sensitive (a UI preference, a feature flag) is the only thing that belongs in the plain option.
Structured elaboration
The four options compared
| Storage option | Typical use case | Platform threat model | Recommended persist/rotate pattern |
|---|---|---|---|
| iOS Keychain | Long-lived refresh tokens, API keys, any credential that must survive app restarts. | Protected by the device passcode; can be hardware-backed via the Secure Enclave (a dedicated security chip separate from the main processor) for key operations. Items are included in encrypted iCloud backups by default unless explicitly marked device-only. | Store with an accessibility level matched to sensitivity (a device-only, unlock-required flag for the most sensitive items); rotate on logout or suspected compromise; keep short-lived access tokens in memory only, never persisted here. |
| Android KeyStore | Not a place to store token VALUES directly; it stores cryptographic KEYS used to protect data stored elsewhere (typically via EncryptedSharedPreferences, below). | System-managed key storage; can be hardware-backed via a Trusted Execution Environment (TEE, an isolated secure processing area) or, on supporting devices, StrongBox (a dedicated secure hardware module). Keys can be marked non-exportable so they never leave secure hardware in plaintext form. | Generate the wrapping key in KeyStore with setUserAuthenticationRequired for high-sensitivity data; use it to encrypt actual token values stored via EncryptedSharedPreferences; rotate the wrapping key on a defined schedule and re-encrypt dependent data. |
| EncryptedSharedPreferences (Android) | Long-lived refresh tokens and API keys, the practical Android equivalent of the iOS Keychain for this use case. | A SharedPreferences wrapper that encrypts both keys and values using a KeyStore-managed master key; backup behavior depends on whether that master key itself is excluded from backup (it should be, since a backed-up encrypted value is useless without the device-bound key that decrypted it). | Persist tokens here rather than in KeyStore directly; exclude this preference file from Android's auto-backup; rotate by writing a new encrypted value and discarding the old one, no separate migration step needed since the encryption is transparent to the caller. |
| Plain SharedPreferences / NSUserDefaults | Non-sensitive application settings only: UI theme, a feature flag, a "has seen onboarding" boolean. | Stored in the app's private sandbox but genuinely unencrypted; readable on a rooted (Android) or jailbroken (iOS) device, and readable from an unencrypted local or cloud backup depending on platform backup configuration. | Never store a credential here under any circumstance. If a short-lived access token needs somewhere to live briefly, in-memory only is the correct answer, not this. |
Why short-lived access tokens don't appear as a strong candidate for any persistent store above
A short-lived access token (an OAuth2 bearer token, typically valid for minutes to an hour) is deliberately designed to be cheap to lose; the standard pattern is to keep it in memory only (a variable in the running app process) and let it disappear when the app is killed, re-deriving a new one from the persisted refresh token on next launch. Persisting a short-lived token defeats the point of it being short-lived in the first place: the whole design assumes it is not worth protecting as carefully as the long-lived refresh token that can mint new ones.
Rotation pattern that applies across all four
Regardless of platform, the pattern for anything long-lived (refresh tokens, API keys) is: generate or receive a new value from the server, write it to the encrypted store, confirm the write succeeded, only then discard the old value; on any read failure or decryption failure (a device restore to different hardware, a corrupted keystore after an OS update), treat it as "credential unavailable" and force a fresh login rather than silently falling back to an unencrypted store, which would quietly reintroduce the exact risk the encrypted store exists to avoid.
Worked example
A finance app needs to persist a refresh token after login. On iOS: store it in the Keychain with kSecAttrAccessibleWhenUnlockedThisDeviceOnly (device-only, requires the device to be unlocked to read), which both excludes it from iCloud backup and requires a successful unlock to access, so a stolen but locked device does not expose it. On Android: generate a KeyStore-backed AES key with setUserAuthenticationRequired(true) if the app wants to require a recent biometric/PIN check before decryption, use that key to write the refresh token into EncryptedSharedPreferences, and exclude that preference file's backing file from Android's auto-backup configuration (android:allowBackup scoped, or an explicit backup-rules exclusion) so a cloud backup restored to a different device cannot yield a usable token even if the ciphertext were somehow extracted, since the wrapping key never leaves the original device's secure hardware.
Trade-offs and pitfalls
- Storing a refresh token in plain SharedPreferences/NSUserDefaults "temporarily, to be fixed later." This is the single most common real-world finding in a mobile security review; "temporary" code paths persisting credentials in plaintext routinely ship to production because the encrypted alternative feels like more setup work.
- Assuming hardware-backing is guaranteed. Not every device has a Secure Enclave equivalent or StrongBox; code should not assume hardware backing succeeded without checking, since silently falling back to software-only key storage changes the actual threat model without anyone deciding that on purpose.
- Letting sensitive data ride along in a cloud backup unintentionally. The default behavior for both platforms' encrypted stores is not automatically "excluded from backup"; that has to be configured explicitly, and skipping it means a token can end up recoverable from a backup on a completely different, possibly attacker-controlled, device.
- Treating KeyStore and EncryptedSharedPreferences as interchangeable on Android. KeyStore holds keys, not arbitrary token values; a common confusion is trying to store a token string directly in KeyStore, which is not what it is designed for, rather than using it to protect a value stored in EncryptedSharedPreferences.
Design how to share networking and retry logic between an iOS app using URLSession and an Android app using OkHttp. Identify which components (models, serialization, retry policy, backoff algorithms) can be shared via Kotlin Multiplatform or shared libraries, and which must remain platform-specific (background tasks, native push integration). Provide API boundaries and an example of the public interface.
Sample Answer
Approach (brief)
Share pure business logic, models, serialization and retry/backoff algorithms in a Kotlin Multiplatform (KMP) module. Keep native integration (URLSession, OkHttp, background scheduling, push) in thin platform adapters that implement KMP-defined interfaces.
What to share (KMP)
- Models / DTOs (data classes)
- Serialization (kotlinx.serialization) + canonical JSON schema
- Networking contract interfaces (HttpClient abstraction)
- Retry policy and backoff algorithms (exponential, jitter, circuit-breaker helpers)
- Common errors and mapping rules
- Unit-testable request/response validators
Platform-specific
- Concrete HTTP transport: OkHttp engine (Android), URLSession engine (iOS/Swift wrapper)
- Background fetch / WorkManager / BGTask scheduling
- Push notification registration & deep-link handling
- Platform credential/keychain storage (secure store wrappers)
API boundaries
- KMP exposes a small HttpClient interface and RetryPolicy types. Platform modules provide Engine implementations.
Example public interface (Kotlin Multiplatform)
// commonMain
interface HttpEngine {
suspend fun execute(request: HttpRequest): HttpResponse
}
data class HttpRequest(val method: HttpMethod, val url: String, val headers: Map<String,String>, val body: ByteArray? = null)
data class HttpResponse(val status: Int, val headers: Map<String,String>, val body: ByteArray?)
interface RetryPolicy {
fun shouldRetry(attempt: Int, response: HttpResponse?, error: Throwable?): Boolean
fun backoffMillis(attempt: Int): Long
}
class HttpClient(private val engine: HttpEngine, private val retry: RetryPolicy) {
suspend fun send(request: HttpRequest): HttpResponse {
var attempt = 0
while (true) {
try {
val resp = engine.execute(request)
if (!retry.shouldRetry(attempt, resp, null)) return resp
} catch (e: Throwable) {
if (!retry.shouldRetry(attempt, null, e)) throw e
}
attempt++
kotlinx.coroutines.delay(retry.backoffMillis(attempt))
}
}
}
Platform adapters implement HttpEngine:
- Android: OkHttpEngine (wraps OkHttp, configures timeouts, connection pooling)
- iOS: UrlSessionEngine (Swift/Objective-C wrapper around URLSession exposed to KMP via cinterop or Kotlin/Native)
Example retry/backoff strategies (shared)
- Exponential with full jitter: backoff = random_between(0, base * 2^attempt)
- Max attempts, idempotency check (only retry safe methods or explicit idempotent token)
Design notes / trade-offs
- Keep engine minimal to allow per-platform optimizations (connection pooling, HTTP/2).
- Use kotlinx.serialization to ensure identical wire format.
- Surface telemetry hooks (events/callbacks) in common API; platform provides native logging/tracing.
- For long-running background uploads use platform-native scheduling; expose resumable upload tokens via shared models.
This design keeps networking behavior consistent while allowing native best-practices on each OS.
Find the k-th largest element in an unsorted array. A full sort gets you there in O(n log n); explain how quickselect (partition-based, like quicksort but recursing into only one side) gets the expected time down to O(n), and when you would reach for a heap of size k instead.
Sample Answer
Direct answer
Quickselect adapts quicksort's partitioning to find just the k-th largest element without fully sorting: after one partition step around a pivot, the pivot's final position tells you whether the answer lies to its left or right, so you only ever recurse into one side instead of both. That halves (in expectation) the work at each level rather than branching into two recursive calls, which is what brings the expected time down from sorting's O(nlogn) to O(n). A heap of size k is the better choice instead when you cannot, or do not want to, mutate the input in place, or when the data arrives as a stream and you need the running top-k as you go rather than a single final answer.
Structured elaboration
Why quickselect is expected O(n)
A single partition around a random pivot costs O(n) and places the pivot at its correct sorted position, with everything smaller to its left and everything larger to its right. If that position is the one you are looking for, you are done; otherwise you recurse into only the one side that must contain the target index, discarding the other side's work entirely. With a reasonably balanced pivot (true on average for a random pivot), the total expected work follows the recurrence T(n)=T(2n)+O(n)=O(n) (expected), the same halving-geometric-series pattern that makes binary search O(logn), except here the per-level cost is O(n) rather than O(1), and only one recursive branch is taken rather than a binary search's implicit single branch. This is the key difference from quicksort, which must recurse into both sides to sort everything, giving O(nlogn).
Why a heap of size k instead
- Streaming input: if elements arrive one at a time and you must always be able to report the current top k, quickselect does not apply directly, since it needs the whole array in hand to partition; a size-k min-heap updates in O(logk) per new element and always reflects the current top k.
- Avoiding in-place mutation: quickselect partitions the input array in place; if the caller cannot have their array reordered, a heap that only reads elements avoids that side effect (at the cost of O(k) extra space).
- Worst-case guarantee: a naive quickselect has a worst case of O(n2) on an adversarial or unlucky pivot sequence (randomizing the pivot choice makes this astronomically unlikely, not impossible); a heap of size k guarantees O(nlogk) in every case.
- k close to n: when k is large relative to n, a heap of size k approaches O(k) extra space that is not much smaller than the array itself, and quickselect's in-place approach becomes the more memory-efficient option; when k is small, the heap's small extra space is a non-issue and its worst-case guarantee is attractive.
A related, absorbed framing: this is a selection-algorithm family, not a one-off trick
The same "avoid a full sort" idea generalizes. Finding the k-th smallest value in a matrix whose rows and columns are each sorted uses a min-heap over the smallest untried cell in each row (or a binary search directly over the value range, counting how many matrix entries are ≤ a candidate value in O(n) per probe) rather than flattening and sorting the whole matrix. And when memory, not just time, is the binding constraint (as in a memory-constrained k-smallest-elements variant), quickselect's in-place partitioning is preferable to a heap precisely because it needs no auxiliary structure beyond the input array itself.
Worked example
import heapq
import random
def kth_largest_quickselect(nums: list[int], k: int) -> int:
"""
Return the k-th largest value (k=1 is the maximum).
Expected O(n) time, O(1) extra space (in-place partition, iterative).
Worst case O(n^2) on adversarial pivots; randomized pivot makes that
astronomically unlikely rather than eliminating it.
"""
if not (1 <= k <= len(nums)):
raise ValueError("k out of range")
target = len(nums) - k # index of the k-th largest in sorted-ascending order
lo, hi = 0, len(nums) - 1
while True:
pivot_idx = random.randint(lo, hi)
nums[pivot_idx], nums[hi] = nums[hi], nums[pivot_idx]
pivot = nums[hi]
store = lo
for i in range(lo, hi):
if nums[i] < pivot:
nums[i], nums[store] = nums[store], nums[i]
store += 1
nums[store], nums[hi] = nums[hi], nums[store]
if store == target:
return nums[store]
elif store < target:
lo = store + 1
else:
hi = store - 1
def kth_largest_heap(nums: list[int], k: int) -> int:
"""Min-heap of size k. O(n log k) time, O(k) space."""
heap: list[int] = []
for x in nums:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]:
heapq.heapreplace(heap, x)
return heap[0]
if __name__ == "__main__":
random.seed(0)
data = [3, 2, 1, 5, 6, 4]
print("quickselect k=2:", kth_largest_quickselect(data.copy(), 2))
print("heap k=2:", kth_largest_heap(data, 2))
bigger = [7, 10, 4, 3, 20, 15]
print("quickselect k=3:", kth_largest_quickselect(bigger.copy(), 3))
print("heap k=3:", kth_largest_heap(bigger, 3))
Running this prints:
quickselect k=2: 5
heap k=2: 5
quickselect k=3: 10
heap k=3: 10
For [3, 2, 1, 5, 6, 4] sorted descending (6, 5, 4, 3, 2, 1), the 2nd largest is 5, and both methods agree. For [7, 10, 4, 3, 20, 15] sorted descending (20, 15, 10, 7, 4, 3), the 3rd largest is 10, and again both methods agree. The pivot choices inside quickselect are randomized but seeded (random.seed(0)), so this exact sequence of calls reproduces this exact output every time it is run.
Complexity
- Quickselect: expected time O(n), worst case O(n2); space O(1) extra (partitions in place, iteratively rather than recursively here).
- Heap of size k: time O(nlogk) in every case; space O(k) for the heap.
Edge cases
- k outside the range
[1, len(nums)]is invalid input and should raise rather than silently returning a wrong value. - Duplicate values are handled correctly by both methods, since partitioning and heap comparisons work on values, not identity.
- k equal to 1 (the maximum) or k equal to n (the minimum) are valid boundary cases worth checking by hand.
- An already-sorted or reverse-sorted array is exactly the input that most threatens a non-randomized quickselect's worst case; randomizing the pivot is what defends against it.
Trade-offs & pitfalls
The most common wrong turn is presenting quickselect as strictly superior because of its better expected time, without naming its O(n2) worst case or its requirement to mutate the input array in place; both are real costs that the heap approach avoids. A second common gap is forgetting that quickselect only gives you the k-th value itself, not the k values above it in order: if you also need the actual top-k list, you still need one more pass (or a heap) to collect everything on the correct side of the final partition. A third pitfall, specific to this absorbed question family, is treating "kth largest in an array" and "kth smallest in a sorted matrix" as needing the same algorithm: the matrix's extra structure (both rows and columns already sorted) is exactly what makes a heap-over-candidate-cells or binary-search-over-values approach effective there, and quickselect's partitioning does not directly apply to a two-dimensional sorted structure the same way.
Plan a migration strategy for an Android app that currently uses legacy external storage file paths to move to Scoped Storage (Android 10/11+). Explain how to migrate existing user media files, update stored file paths in databases, support third-party integrations that expect filesystem paths, handle content URIs, and maintain backward compatibility across API levels without data loss.
Sample Answer
Plan summary — goals
- Move user media to MediaStore / app-specific storage so files remain accessible under scoped storage.
- Preserve/accessibility: update app DB to map old absolute paths → content:// URIs, support third-party libs expecting file paths via FileProvider or temp copies.
- Maintain backward compatibility (API <29), avoid data loss.
Steps
-
Audit & requirements
- Enumerate file types (images, video, documents), count, total size.
- Decide targets: MediaStore (images/video/audio) vs SAF/app-specific for others.
-
Migration mechanics
- Run migration off-main-thread with progress + resumable checkpoints.
- For each legacy file:
- Insert into MediaStore (or SAF) and stream-copy bytes, verify checksum/size.
- On success, delete original.
- Record mapping old_path → new_content_uri in a migration table; update app DB atomically (transaction).
Kotlin example — insert image into MediaStore and copy:
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, file.name)
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/MyApp")
}
val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)!!
contentResolver.openOutputStream(uri).use { out ->
FileInputStream(file).use { input -> input.copyTo(out) }
}
- Handling content URIs & third-party integrations
- Prefer storing content:// URIs in DB. When consumer needs filesystem path:
- Use FileProvider to expose a streamed temporary file (create temp in cache, write contentResolver.openInputStream(uri), expose via FileProvider.getUriForFile). Grant URI permission intent flags for share.
- For libraries needing File object (not URI), create temp file and pass its File path; ensure deletion after use.
- Backward compatibility
- API 29: set requestLegacyExternalStorage=true temporarily to ease migration; ensure migration complete before removing.
- Use runtime branching:
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) use MediaStore/SAF/content URIs
- else continue using legacy paths.
- For devices <Q, keep original paths and sync mapping.
- Edge cases & safety
- Handle name collisions by appending suffix.
- Resume after interruption using migration table and checksum comparisons.
- Preserve EXIF/meta when copying.
- Ensure permissions: READ/WRITE_EXTERNAL_STORAGE where required; request MANAGE_EXTERNAL_STORAGE only if absolutely necessary and justify to Play.
- Rollout strategy
- Phased rollout with telemetry, small % first, validate migration success rates; provide in-app recovery (retry) and manual export.
Result: users keep their media intact, app uses modern APIs, third-party compatibility via FileProvider/temp files, and no data loss via verify-then-delete and mapping table.
Design a comprehensive testing strategy for mobile networked features: include unit tests with network mocking/stubbing, integration tests with a simulated backend, end-to-end tests on device farms with flaky networks, deterministic replay of server responses, and CI strategies to run these tests reliably. Mention tools and frameworks you'd use.
Sample Answer
Overview / goals
Design a test pyramid that gives fast feedback (unit), realistic behaviour (integration with simulated backend), and full-user validation (E2E on devices), while making tests deterministic and CI-reliable under flaky networks.
Unit tests (fast, deterministic)
- Tools: iOS XCTest + URLProtocol-based stubs or OHHTTPStubs; Android JUnit + Mockito + OkHttp MockWebServer.
- Strategy: isolate networking layer by injecting an HTTP client interface; mock network responses and clocks; assert request formation, retries, and error handling.
- Example: use MockWebServer to enqueue JSON and verify headers and retry counts.
Integration tests (simulated backend)
- Tools: WireMock standalone / Docker, MockWebServer for Android, local Swift/Vapor server for iOS.
- Strategy: run app build pointing to WireMock host in a test profile; test real serialization, persistence, and retry/backoff logic against scripted latency, 500s, auth flows.
- Use contract tests (Pact) to verify API expectations between mobile and backend teams.
Deterministic replay of server responses
- Tools: WireMock recordings, VCR-like recordings, or saved MockWebServer enqueues; Charles/mitmproxy session dumps for complex flows.
- Strategy: record golden interactions, store mappings in repo, run replay mode in CI to reproduce specific bugs. Pin timestamps/UUIDs via dependency injection to avoid nondeterminism.
End-to-end on device farms with flaky networks
- Tools: Firebase Test Lab, AWS Device Farm, BrowserStack App Automate; Espresso/XCUITest for automation.
- Network conditions: use Network Link Conditioner (iOS), tc/netem on device farm VMs, or device-farm network shaping to simulate latency, jitter, loss, and throttling.
- Strategy: run E2E suites under multiple profiles (good/3G/edge/packet-loss). Capture logs, videos, and HARs. Validate UX: offline flows, sync, resume-after-reconnect.
Flaky-test mitigation & observability
- Mark long-running flaky scenarios as nightly; for PRs run fast smoke E2E.
- Auto-rerun transient failures (1–2 retries) with strict logging; quarantine persistent flaky tests.
- Collect telemetry: screenshots, network traces, device logs, and deterministic seeds.
CI strategy
- Pipeline tiers:
- Pre-merge: unit tests + static analysis (Xcode Analyzer, detekt/ktlint), run in parallel on GitHub Actions / CircleCI / Bitrise.
- Merge gate: integration tests against WireMock in Docker, run in CI matrix (iOS/Android, API versions).
- Post-merge/nightly: E2E on device farms (Firebase/AWS/BrowserStack), network-shaping matrix, contract verification.
- Artifacts: store recordings, device logs, videos for debugging. Use caching for builds, and split tests to parallel device shards.
- Rollout tie-in: use staged rollouts and feature flags to limit blast radius; run canary E2E before full release.
Trade-offs
- Full device E2E is slow/costly; mitigate with targeted smoke tests on PRs and more exhaustive nightly runs.
- Recordings speed up reproducibility but may drift—maintain periodic re-recording and contract tests.
This strategy balances speed, realism, determinism, and CI reliability for mobile networked features.
Order status updates arrive over a WebSocket while the user is also editing the same orders in the UI. How do you merge incoming events into client state so duplicates, out-of-order messages and reconnects do not corrupt what is on screen?
Sample Answer
Direct answer
Picture an orders screen kept live by a WebSocket (a long-lived connection over which the server pushes messages) while the user is also editing orders. Messages can repeat, arrive late or out of order, and be lost while the connection is down. The answer is to treat the socket as an unreliable stream of facts and merge it with a pure reducer that relies on three pieces of data the server must supply: a per-order version that increases by one for each change, an event id, and (for user edits) an edit id that the client invents. Rules: ignore any event whose version is not newer than the state you hold (that removes duplicates and stale messages); hold back any event that skips a version and ask for a fresh snapshot (that handles out-of-order delivery and gaps); on every reconnect mark all orders for a refetch and let the version check discard the socket's replays; keep the user's unconfirmed edits in a separate layer drawn over the server state, so a server message cannot silently erase them; and keep toasts (momentary) separate from persisted notifications (stored by id).
Terms: an idempotent operation gives the same result when applied twice; optimistic means showing the user's change before the server confirms it; a reducer is a function from (state, action) to a new state with no side effects; a snapshot is a full copy of one order fetched from the REST API (a refetch is simply asking for a new snapshot). A gapless version means the numbers go 1, 2, 3 with none skipped, so a missing number proves an event was missed. An ack (acknowledgement) is the server's reply saying it accepted an edit; a rejection is its reply refusing it. A conflict flag marks a field the user edited and the server changed to a different value meanwhile. A toast is a short pop-up message that disappears by itself. Draining the buffer means applying held-back events one after another for as long as the next needed version is present. A replay is the server resending recent events after a reconnect, some of which the client already has.
State shape
| Slice | Holds | Changed by |
|---|---|---|
orders[id] | { version, fields }, the server's last word | in-order events, snapshots, acks |
buffer[id] | events that arrived ahead of a missing version | early events; drained when the gap closes |
resync[id] | true while a snapshot is needed | gap detected, reconnect |
pending[id][field] | the user's unconfirmed value, its edit id, a conflict flag | local edit, ack, rejection |
toasts | momentary messages, each with a key | events and failures; removed by expiry |
notifications[id] | persisted items, stored by id | notification messages (idempotent) |
A short trace shows how the slices move. Order o1 starts from a snapshot at version 1, then event version 3 arrives before event version 2:
| Step | orders.o1 version | status on screen | buffer.o1 | resync.o1 |
|---|---|---|---|---|
| Snapshot at version 1 | 1 | new | empty | false |
| Event version 3 arrives (version 2 missing) | 1 | new | holds version 3 | true |
| Event version 2 arrives | 3 | shipped | empty | false |
In step 2 the screen still shows version 1 because version 3 cannot be applied without version 2. In step 3, version 2 is applied and the same call drains version 3 from the buffer, so the order jumps to version 3 and resync goes back to false. A snapshot at version 2 arriving in step 2 would close the gap instead, and the buffered version 3 would then drain on top of it.
The screen reads view(state, id): the server fields with the pending values laid over them, plus the lists of fields that are being saved and that are in conflict.
The code
orders.js:
// Pure reducer: (state, action) -> new state. No timers, no sockets, so every case can be replayed in a test.
export const initialState = () => ({
orders: {}, // id -> { version, fields } (what the SERVER says)
buffer: {}, // id -> { [version]: event } (events that arrived ahead of a gap)
resync: {}, // id -> true while a snapshot must be fetched
pending: {}, // id -> { [field]: { value, editId, conflict } } (what the USER typed, unconfirmed)
toasts: [], // transient: { key, text }, removed by TOAST_EXPIRED, never persisted
notifications: {}, // persisted by id: { id, text, read }
});
const push = (toasts, key, text) => (toasts.some((t) => t.key === key) ? toasts : [...toasts, { key, text }]);
// Apply one event that is exactly the next version of its order.
function applyNext(state, ev) {
const cur = state.orders[ev.orderId];
const pend = { ...(state.pending[ev.orderId] ?? {}) };
for (const f of Object.keys(ev.patch)) {
if (pend[f] && pend[f].value !== ev.patch[f]) pend[f] = { ...pend[f], conflict: true }; // keep the user's value on screen, flag it
}
return {
...state,
orders: { ...state.orders, [ev.orderId]: { version: ev.version, fields: { ...cur.fields, ...ev.patch } } },
pending: { ...state.pending, [ev.orderId]: pend },
toasts: push(state.toasts, ev.eventId, `Order ${ev.orderId} updated`),
};
}
// Apply buffered events for as long as the next version is available.
function drain(state, id) {
let s = state;
for (;;) {
const cur = s.orders[id];
const next = cur && s.buffer[id]?.[cur.version + 1];
if (!next) break;
const { [next.version]: _gone, ...rest } = s.buffer[id];
s = applyNext({ ...s, buffer: { ...s.buffer, [id]: rest } }, next);
}
const left = Object.keys(s.buffer[id] ?? {}).length > 0;
return { ...s, resync: { ...s.resync, [id]: left } };
}
function onEvent(state, ev) {
const cur = state.orders[ev.orderId];
if (cur && ev.version <= cur.version) return state; // duplicate or older: ignore
if (cur && ev.version === cur.version + 1) return drain(applyNext(state, ev), ev.orderId);
return { // gap or unknown order: hold it, ask for a snapshot
...state,
buffer: { ...state.buffer, [ev.orderId]: { ...(state.buffer[ev.orderId] ?? {}), [ev.version]: ev } },
resync: { ...state.resync, [ev.orderId]: true },
};
}
export function reducer(state, a) {
switch (a.type) {
case 'EVENT': return onEvent(state, a.event);
case 'SNAPSHOT': {
const { id, version, fields } = a.order;
const cur = state.orders[id];
if (cur && cur.version > version) return state; // a newer state is already here
const kept = Object.fromEntries(Object.entries(state.buffer[id] ?? {}).filter(([v]) => Number(v) > version));
return drain({ ...state, orders: { ...state.orders, [id]: { version, fields } }, buffer: { ...state.buffer, [id]: kept } }, id);
}
case 'RECONNECTED':
return { ...state, resync: Object.fromEntries(Object.keys(state.orders).map((id) => [id, true])) };
case 'LOCAL_EDIT': {
const p = state.pending[a.orderId] ?? {};
return { ...state, pending: { ...state.pending, [a.orderId]: { ...p, [a.field]: { value: a.value, editId: a.editId, conflict: false } } } };
}
case 'EDIT_ACKED': { // the ack carries the resulting event, applied through the same path
let s = a.event ? onEvent(state, a.event) : state;
const p = { ...(s.pending[a.orderId] ?? {}) };
if (p[a.field]?.editId === a.editId) delete p[a.field];
return { ...s, pending: { ...s.pending, [a.orderId]: p } };
}
case 'EDIT_REJECTED': {
const p = { ...(state.pending[a.orderId] ?? {}) };
if (p[a.field]?.editId === a.editId) delete p[a.field]; // roll back: the screen falls back to the server value
return { ...state, pending: { ...state.pending, [a.orderId]: p }, toasts: push(state.toasts, `rej-${a.editId}`, 'Could not save your change') };
}
case 'NOTIFICATION':
if (state.notifications[a.id]) return state; // idempotent by id
return { ...state, notifications: { ...state.notifications, [a.id]: { id: a.id, text: a.text, read: false } }, toasts: push(state.toasts, a.id, a.text) };
case 'TOAST_EXPIRED':
return { ...state, toasts: state.toasts.filter((t) => t.key !== a.key) };
default: return state;
}
}
// What the screen shows: server fields with the user's unconfirmed edits laid over them.
export function view(state, id) {
const o = state.orders[id];
if (!o) return null;
const pend = state.pending[id] ?? {};
const fields = { ...o.fields };
for (const [f, p] of Object.entries(pend)) fields[f] = p.value;
return { ...fields, version: o.version, saving: Object.keys(pend), conflicts: Object.keys(pend).filter((f) => pend[f].conflict) };
}
Reading the reducer:
applyNextapplies an event that is exactly the next version: it lays the event'spatchover the stored fields, marksconflicton any pending field whose value differs from the patch, and adds a toast keyed by the event id (a key already present is not added twice).drainlooks forbuffer[id][version + 1]; when found it removes that event from the buffer and callsapplyNext, then repeats. It stops when the next version is absent and setsresyncto whether anything is still held back.onEventhas three branches: older or equal version (ignore), exactly the next version (apply, then drain), anything else (store in the buffer and setresync).
How each requirement is met:
- Duplicates.
onEventreturns the same state object whenevent.version <= current.version, so the second copy changes nothing and creates no second toast. - Out of order. Version 3 arriving while the order is at version 1 is stored in
bufferandresyncis set; the screen still shows version 1. When version 2 arrives it is applied anddrainimmediately applies the buffered version 3. - Reconnects.
RECONNECTEDmarks every order for refetch. A snapshot replaces the order only if it is not older than what is held, drops buffered events at or below its version, and then drains the rest. Events the socket replays afterwards are older than the state and are ignored by the same version rule. - Optimistic collisions. A user edit goes into
pending, not intoorders. If a server event changes a field the user has pending with a different value, the pending value stays on screen and the field is flaggedconflict, so the UI can say "changed elsewhere". The ack carries the resulting event and goes through the sameonEventpath, then clears the pending entry (matched by edit id, so an older ack cannot clear a newer edit). A rejection deletes the pending entry, so the screen falls back to the server value, and adds one toast "Could not save your change". Conflict policy is "the server decides per field": the user sees their value until the ack, then the server's. - Toast versus notification. A notification is stored by id, so redelivery is a no-op and does not toast again, even after the first toast has expired. The toast has its own key and is removed by
TOAST_EXPIRED(a timer in the UI layer dispatches it), while the notification stays until it is marked read.
Recommendation for the wiring around the reducer (not part of the tested code): open the socket, dispatch RECONNECTED on every successful open, fetch a snapshot for each id in resync through your server-state cache, and send edits over REST with the edit id, dispatching the ack or rejection from the response. This keeps the socket handler thin and the logic testable.
Proving it
The test replays ten scenarios against the reducer and against a "last message wins" version (naive.js) that writes every message straight into state, and asserts that the reducer passes all ten and the naive version fails all ten. Each scenario checks the rule it is named for and also the side effects the prose claims, for example that an ignored duplicate leaves nothing in the buffer and requests no refetch.
naive.js:
// "Last message wins": every message is written straight into state, edits overwrite server data.
export const initialState = () => ({ orders: {}, toasts: [], notifications: [], buffer: {}, resync: {}, pending: {} });
export function reducer(s, a) {
switch (a.type) {
case 'EVENT': {
const e = a.event;
const cur = s.orders[e.orderId] ?? { fields: {} };
return { ...s, orders: { ...s.orders, [e.orderId]: { version: e.version, fields: { ...cur.fields, ...e.patch } } },
toasts: [...s.toasts, { key: e.eventId, text: `Order ${e.orderId} updated` }] };
}
case 'SNAPSHOT': return { ...s, orders: { ...s.orders, [a.order.id]: { version: a.order.version, fields: a.order.fields } } };
case 'LOCAL_EDIT': {
const cur = s.orders[a.orderId];
return { ...s, orders: { ...s.orders, [a.orderId]: { ...cur, fields: { ...cur.fields, [a.field]: a.value } } } };
}
case 'EDIT_ACKED': return a.event ? reducer(s, { type: 'EVENT', event: a.event }) : s;
case 'NOTIFICATION': return { ...s, notifications: [...s.notifications, { id: a.id, text: a.text }], toasts: [...s.toasts, { key: a.id, text: a.text }] };
case 'TOAST_EXPIRED': return { ...s, toasts: s.toasts.filter((t) => t.key !== a.key) };
default: return s; // RECONNECTED and EDIT_REJECTED are not handled
}
}
export function view(s, id) { const o = s.orders[id]; return o ? { ...o.fields, version: o.version, saving: [], conflicts: [] } : null; }
orders.test.js:
import { describe, it, expect } from 'vitest';
import * as good from './orders.js';
import * as naive from './naive.js';
const run = (impl, actions) => actions.reduce(impl.reducer, impl.initialState());
const ev = (version, patch, orderId = 'o1') => ({ type: 'EVENT', event: { eventId: `e${orderId}-${version}`, orderId, version, patch } });
const snap = (version, fields, id = 'o1') => ({ type: 'SNAPSHOT', order: { id, version, fields } });
const nKeys = (x) => Object.keys(x).length;
// Each scenario returns whether the screen ended up correct, plus the facts behind that verdict.
const scenarios = {
'duplicate event shows once': (m) => {
const s = run(m, [snap(1, { status: 'new' }), ev(2, { status: 'paid' }), ev(2, { status: 'paid' })]);
const untouched = Object.keys(s.buffer.o1 ?? {}).length === 0 && !s.resync.o1; // the copy is ignored: nothing buffered, no refetch requested
return { ok: m.view(s, 'o1').status === 'paid' && s.toasts.length === 1 && untouched, status: m.view(s, 'o1').status, toasts: s.toasts.length, untouched };
},
'v3 arrives before v2': (m) => {
const early = run(m, [snap(1, { status: 'new' }), ev(3, { status: 'shipped' })]);
const s = run(m, [snap(1, { status: 'new' }), ev(3, { status: 'shipped' }), ev(2, { status: 'paid' })]);
const holds = m.view(early, 'o1').status === 'new' && early.resync.o1 === true; // the gap is held back and a refresh is requested
return { ok: holds && m.view(s, 'o1').status === 'shipped' && m.view(s, 'o1').version === 3, afterV3Only: m.view(early, 'o1').status, final: m.view(s, 'o1').status };
},
'older event after newer state': (m) => {
const s = run(m, [snap(2, { status: 'paid' }), ev(1, { status: 'new' })]);
return { ok: m.view(s, 'o1').status === 'paid', status: m.view(s, 'o1').status };
},
'reconnect replays events older than current state': (m) => {
const s = run(m, [snap(3, { status: 'paid' }), { type: 'RECONNECTED' }, snap(6, { status: 'delivered' }), ev(7, { status: 'returned' }), ev(4, { status: 'packed' }), ev(5, { status: 'shipped' })]);
const marked = run(m, [snap(3, { status: 'paid' }), { type: 'RECONNECTED' }]).resync.o1 === true; // every known order is marked for refetch
return { ok: marked && m.view(s, 'o1').status === 'returned' && m.view(s, 'o1').version === 7 && !s.resync.o1, status: m.view(s, 'o1').status, version: m.view(s, 'o1').version };
},
'server event hits a field the user is editing': (m) => {
const base = [snap(1, { status: 'new', note: '' }), { type: 'LOCAL_EDIT', orderId: 'o1', field: 'note', value: 'gift', editId: 'x1' }, ev(2, { note: 'rush', status: 'paid' })];
const mid = run(m, base);
const end = run(m, [...base, { type: 'EDIT_ACKED', orderId: 'o1', field: 'note', editId: 'x1', event: { eventId: 'ack', orderId: 'o1', version: 3, patch: { note: 'gift' } } }]);
return { ok: m.view(mid, 'o1').note === 'gift' && m.view(mid, 'o1').status === 'paid' && m.view(mid, 'o1').conflicts.join() === 'note' && m.view(end, 'o1').note === 'gift' && m.view(end, 'o1').saving.length === 0,
noteWhileEditing: m.view(mid, 'o1').note };
},
'save fails: roll back and tell the user once': (m) => {
const s = run(m, [snap(1, { status: 'new' }), { type: 'LOCAL_EDIT', orderId: 'o1', field: 'status', value: 'cancelled', editId: 'x2' }, { type: 'EDIT_REJECTED', orderId: 'o1', field: 'status', editId: 'x2' }]);
return { ok: m.view(s, 'o1').status === 'new' && s.toasts.length === 1, status: m.view(s, 'o1').status, toasts: s.toasts.length };
},
'snapshot closes a gap and clears stale buffer': (m) => {
const a = run(m, [snap(1, { status: 'new' }), ev(3, { status: 'shipped' }), snap(2, { status: 'paid' })]); // v3 then drains on top of the snapshot
const b = run(m, [snap(1, { status: 'new' }), ev(3, { status: 'shipped' }), snap(3, { status: 'shipped' })]); // v3 is now covered by the snapshot
const ok = m.view(a, 'o1').status === 'shipped' && m.view(a, 'o1').version === 3 && !a.resync.o1
&& m.view(b, 'o1').version === 3 && !b.resync.o1 && Object.keys(b.buffer.o1 ?? {}).length === 0;
return { ok, aStatus: m.view(a, 'o1').status, bResync: b.resync.o1 ?? null };
},
'older snapshot does not roll the screen back': (m) => {
const s = run(m, [snap(5, { status: 'delivered' }), snap(4, { status: 'packed' })]);
return { ok: m.view(s, 'o1').status === 'delivered' && m.view(s, 'o1').version === 5, status: m.view(s, 'o1').status };
},
'late ack of an older edit keeps the newer edit': (m) => {
const s = run(m, [snap(1, { note: '' }), { type: 'LOCAL_EDIT', orderId: 'o1', field: 'note', value: 'a', editId: 'x1' },
{ type: 'LOCAL_EDIT', orderId: 'o1', field: 'note', value: 'ab', editId: 'x2' },
{ type: 'EDIT_ACKED', orderId: 'o1', field: 'note', editId: 'x1', event: { eventId: 'ack1', orderId: 'o1', version: 2, patch: { note: 'a' } } }]);
return { ok: m.view(s, 'o1').note === 'ab' && m.view(s, 'o1').saving.join() === 'note', note: m.view(s, 'o1').note };
},
'notification redelivered after its toast expired': (m) => {
const note = { type: 'NOTIFICATION', id: 'n1', text: 'Refund issued' };
const s = run(m, [note, note]);
const after = m.reducer(s, { type: 'TOAST_EXPIRED', key: 'n1' });
const again = m.reducer(after, note); // the server resends it after a reconnect: no second toast
return { ok: nKeys(s.notifications) === 1 && s.toasts.length === 1 && after.toasts.length === 0 && nKeys(after.notifications) === 1 && again.toasts.length === 0 && nKeys(again.notifications) === 1,
persisted: nKeys(s.notifications), toasts: s.toasts.length, toastsAfterRedelivery: again.toasts.length };
},
};
describe('order events merged into client state', () => {
const table = [];
for (const [name, fn] of Object.entries(scenarios)) {
it(name, () => {
const g = fn(good);
const n = fn(naive);
table.push(`${name.padEnd(50)} reducer: ${g.ok ? 'pass' : 'FAIL'} last-message-wins: ${n.ok ? 'pass' : 'FAIL'}`);
expect(g.ok, JSON.stringify(g)).toBe(true);
expect(n.ok, 'the naive version must fail every scenario').toBe(false);
});
}
it('prints the comparison', () => { console.log('\n' + table.join('\n')); });
});
describe('reducer is pure', () => {
it('does not mutate earlier states', () => {
const s1 = run(good, [snap(1, { status: 'new' })]);
const frozen = JSON.stringify(s1);
good.reducer(s1, ev(2, { status: 'paid' }));
expect(JSON.stringify(s1)).toBe(frozen);
});
});
Run in a node:22 container (Node 22.23.3, Vitest 2.1.8, no browser needed because the reducer is pure), the comparison it prints and the result line are:
duplicate event shows once reducer: pass last-message-wins: FAIL
v3 arrives before v2 reducer: pass last-message-wins: FAIL
older event after newer state reducer: pass last-message-wins: FAIL
reconnect replays events older than current state reducer: pass last-message-wins: FAIL
server event hits a field the user is editing reducer: pass last-message-wins: FAIL
save fails: roll back and tell the user once reducer: pass last-message-wins: FAIL
snapshot closes a gap and clears stale buffer reducer: pass last-message-wins: FAIL
older snapshot does not roll the screen back reducer: pass last-message-wins: FAIL
late ack of an older edit keeps the newer edit reducer: pass last-message-wins: FAIL
notification redelivered after its toast expired reducer: pass last-message-wins: FAIL
Tests 12 passed (12)
The twelve tests are the ten scenarios, the comparison printout and a purity check (calling the reducer does not change an earlier state). Deleting any one of these lines from the reducer makes at least one scenario fail: the ev.version <= cur.version ignore, the stale-buffer filter in SNAPSHOT, the older-snapshot guard, the edit-id match in EDIT_ACKED, the RECONNECTED marking, and the state.notifications[a.id] check in NOTIFICATION (without it, a notification redelivered after its toast expired shows a second toast). Each failing row on the right is the technique removed: for instance, with last-message-wins the order in "v3 arrives before v2" ends on the older status, and the local edit disappears when a server event touches the same field.
Trade-offs and pitfalls
- This design depends on the server stamping a gapless per-order version. If it only has timestamps, ignoring "older" events is still possible but gaps cannot be detected; ask the backend for versions or a sequence number.
- A fixed buffer size (and a refetch when it overflows) bounds memory during long outages. Choose the limit from your event rate; it is a tuning value, not a derived one.
- Many orders: the snapshot refetch on reconnect is N requests. Prefer one "changes since" request if the API offers it, and update the cache once.
- Showing the user's value over a conflicting server value is a product choice. For fields where the server must win (status), skip the overlay and show the server value with a message.
Running the code
npm i vitest@2.1.8
Files: orders.js, naive.js, orders.test.js (package.json needs "type": "module")
npx vitest run
You have inherited a backlog of 150 user-reported issues and capacity to fix a fraction of them. How do you decide what gets fixed first, and how do you know your ranking reflects real customer pain rather than whoever complained loudest?
Sample Answer
Direct answer
Rank by estimated customer pain per unit of effort, and build pain from independent evidence: how many people hit the problem (reach), how badly (severity), and how much work the fix takes (effort). Loudness is controlled by counting distinct affected users from behaviour data instead of counting messages, and the ranking is checked against qualitative evidence from interviews, support transcripts and Net Promoter Score (NPS) comments. NPS is a survey asking customers how likely they are to recommend you on a 0 to 10 scale, with a free-text reason.
Step 1: deduplicate and tag
Cluster the 150 reports into distinct underlying problems, then tag each with the area, the symptom and a severity class: 3 = loses data or blocks a core task, 2 = slows a task but a workaround exists, 1 = annoyance or cosmetic.
Step 2: measure reach from behaviour, not volume
Use telemetry (usage data the product records automatically): error logs, funnel drop-offs (the share of users who quit at each step of a multi-step flow such as checkout), usage events. Tickets overcount persistent complainers and undercount quiet sufferers. One account sending nine emails is one account. Upvotes (votes from users on a public request) are volume too, so use them only as a hint, not as reach.
Step 3: score
priority = reach (% of active users) x severity (1 to 3) / effort (engineer-days)
Enter reach as a plain number of percentage points (12% goes in as 12, 0.4% as 0.4, never 0.12 or 0.004). Plain English: more people, hurt more, for less work, ranks higher. Treat scores in the same ballpark as ties and break them with judgement.
Step 4: let qualitative evidence change the ranking (illustrative numbers)
Tag each interview, NPS comment and transcript to the same issue clusters, with explicit rules: a transcript showing lost work or abandonment raises severity to 3; one showing a trivial workaround lowers it. Record the supporting quote so the change can be audited.
| Issue | Reach | Severity (tickets only) | Effort | Score | Severity after transcripts | Score after |
|---|---|---|---|---|---|---|
| A: dashboard colour bug (one account, nine emails) | 0.4% | 1 | 5 | 0.08 | 1 | 0.08 |
| B: export fails on large files | 12% | 2 | 8 | 3.0 | 3 | 4.5 |
| C: confusing sidebar label (30 upvotes) | 4% | 1 | 1 | 4.0 | 1 | 4.0 |
Before the transcripts, C outranks B. Reading five transcripts shows users redoing hours of work after failed exports, so B moves to severity 3 and overtakes C. The loudest report, A, is cosmetic (severity 1 on the Step 1 scale) and stays last.
Conflicting requests from strategic customers
Strategic customers are the accounts the company has named as most important to win or keep. Do not override the score silently. Reserve a small explicit quota, agreed in advance, for documented churn risk (a customer likely to cancel), and judge those items on evidence (renewal date, stated blocker). Everything else competes on the score.
Checking the ranking reflects real pain
- Spot-check with a few users from the top and the bottom of the list.
- After fixing the top items, confirm tickets and funnel drop-offs for those issues fell.
- Compare who is complaining with who is affected in the telemetry.
Variation: complaints about model quality (ML-powered features)
The same scoring still applies. For a feature powered by a machine learning model, add these checks in the first 24 hours: (1) did complaints start after a model, data or prompt release (a change to the instructions given to a language model)? (2) replay saved examples to tell a regression (something that used to work and now does not) from an old weakness; (3) compare today's inputs with the training period (data drift: real inputs shift away from what the model learned); (4) rule out the product around the model (truncated text, meaning input cut off before it reaches the model; timeouts; a stale cache, meaning an old saved answer served instead of a fresh one) before blaming the model; (5) check whether complaints cluster in a segment.
Example (illustrative): 40 tickets say "the assistant summaries are wrong since last week". Check 1 shows all 40 began within two days of a prompt release. Check 2 replays 50 saved inputs and finds the new prompt drops the last paragraph of long documents, so it is a regression. Check 4 shows the same truncation in a log. The fix is to roll back the prompt, and check 2 is what caught it.
Variation: player-value scoring (games)
Weight reach by player value, for example new players (whose retention, meaning whether they keep playing, decides the game's future) versus long-tenured or paying players, as a capped multiplier so it does not recreate a revenue-ranked skew.
Example (illustrative): a bug hits 3% of players, severity 2, effort 4, so the base score is 3 x 2 / 4 = 1.5. If most affected players are paying, apply a multiplier of 1.5 (the cap): 1.5 x 1.5 = 2.25. Uncapped, a spending-weighted multiplier of 5 would give 7.5 and let paying players outrank every other issue, which is the skew the cap prevents.
Tell me about a mentoring relationship that didn't go the way you hoped, one where your mentee didn't improve, or where things ended badly. What would you do differently now?
Sample Answer
Direct answer
A mentoring relationship going badly is rarely one big failure; it's usually a slow accumulation of choices, like taking on too much of the work yourself to protect the outcome, that quietly undercut the mentee's growth. The honest answer names a specific relationship, is candid about what you did (not just what the mentee did), and shows what changed in how you mentor afterward.
What "went badly" usually looks like
- Common patterns: being too directive and doing the hard parts yourself to protect delivery; giving feedback too infrequently or too late to be actionable; misjudging the mentee's actual gap (treating a confidence problem as a skill problem, or the reverse); or disengaging when the relationship got effortful.
- A strong answer picks one specific pattern and owns your part in it, rather than a vague "they weren't a good fit."
What separates a senior answer from a junior one
- Junior answers blame the mentee ("they just weren't receptive") or stay abstract ("communication could have been better"). Senior answers identify a decision you made and trace its actual effect: what you did, what it produced, and why it made sense to you at the time even though it was wrong.
- Senior answers also show what changed structurally afterward, not just an apology or a resolution to "communicate better." Concrete changes: an explicit mentoring agreement up front, checkpoints instead of open-ended availability, deliberately handing over ownership even when it's slower.
How to close it out
- End on what you'd do differently now, stated specifically enough that it's clear you'd actually behave differently in the next relationship, not just that you feel bad about the last one.
Worked example
During a stretch project with a hard deadline, I mentored a junior engineer by taking over the riskiest parts myself rather than coaching them through it, to keep the timeline safe. That worked in the short term, but it meant they never built confidence handling ambiguity or incidents on their own, and toward the end of the project they told me directly that they felt sidelined rather than developed. That was the moment it became clear the relationship hadn't done what I'd intended, even though the project itself shipped fine.
What I changed afterward: instead of stepping in when something got risky, I started requiring myself to narrate my reasoning out loud and have the mentee drive, only taking over if there was a genuine, immediate risk. I also set an explicit checkpoint (a short regular sync, not just "come find me") so growth stalls would surface early instead of only becoming visible at the end of a project. The relationship after that wasn't measured by how smoothly the project went; it was measured by whether the mentee could handle the next similar situation without me in the room, which is a slower thing to build but the actual point of mentoring.
Trade-offs and pitfalls
- The tempting failure mode is optimizing for the deliverable (visible and rewarded) at the expense of the mentee's growth (slower and less visible), especially under deadline pressure.
- Being self-critical is necessary but insufficient; an answer that's all remorse with no concrete process change reads as unreflective in a different way.
- Watch for over-correcting into never stepping in, which just replaces one failure mode (too directive) with another (abandoning someone to a mistake they can't yet recover from alone).
Explain the difference between an Android App Bundle and an APK, and between an IPA and App Store distribution for iOS. Describe the benefits of app bundles or app thinning, how they affect download size and device targeting, and list the basic steps to prepare and upload a release to Google Play and App Store Connect.
Sample Answer
Difference: Android App Bundle vs APK; IPA vs App Store distribution
- Android App Bundle (AAB): publishing artifact containing all compiled code/resources for every device/configuration. Google Play generates optimized APKs (split APKs / signed app bundles → Dynamic Delivery) per device. APK: a single installable package that may be universal or targeted; developer-built APKs can be larger and require more manual splits.
- iOS IPA vs App Store distribution: IPA is the packaged app binary (signed). For App Store distribution you upload an archive (IPA inside .xcarchive) to App Store Connect; Apple performs on-device thinning (slicing) and manages re-signing and distribution.
Benefits of bundles / app thinning
- Smaller download/install size (reduced network usage, faster installs)
- Device targeting: delivers only needed architectures, locales, screen assets, and modules
- Easier management of dynamic features (Android Dynamic Delivery) and on-demand resources (iOS)
How they affect size & targeting
- Reduce user-facing download by excluding unused ABIs, languages, and large assets
- Enable conditional delivery (Android) or on-demand resources (iOS) for feature modules
Basic steps to prepare & upload
Google Play:
- Build AAB (./gradlew bundleRelease)
- Ensure Play App Signing enabled, set versionCode/versionName, sign upload key
- Test with internal test track; generate release notes
- Upload to Play Console, configure device targeting, rollout percentage, submit
App Store Connect:
- Archive in Xcode (Product → Archive), export for App Store distribution or use Transporter/Xcode upload
- Increment CFBundleVersion/CFBundleShortVersionString, enable App Thinning/on-demand if used
- Create app record, add screenshots/metadata, choose build in TestFlight for testing
- Submit for review and release (manual or automatic)
What is a delta response, and how can an API expose only what changed since a client's last visit to cut data transfer and battery use? Explain how a client would bootstrap and resume, and how deletions get communicated.
Sample Answer
Direct answer
A delta response returns only the records that changed since a point the client remembers, instead of the full collection. The client stores an opaque cursor (the position in the server's ordered stream of changes) together with its local copy. Each sync is GET /changes?since=<cursor>; the server answers with upserts (create or update), deletions as tombstones (small records saying "id X was deleted"), and a new cursor. Because the cost scales with what changed rather than with the collection size, there is less transfer, less parsing and fewer radio wake-ups (each network request makes the phone's cellular modem leave its low-power idle state, so fewer requests mean less power spent on the radio).
Why it saves bytes and battery
Assume 5,000 rows of about 200 bytes each: a full refresh moves roughly 5,000 x 200 = 1,000,000 bytes. If 12 rows changed since last visit, the delta carries about 12 x 200 = 2,400 bytes of row data, about 0.24% of the full refresh (envelope and headers ignored). Fewer bytes keep the cellular radio active for less time, and a headers-only "nothing new" answer is cheaper still. That helps battery only if sync is not triggered more often than needed: avoid tight polling loops, and let the operating system batch deferrable background work (Android's connectivity guide points to WorkManager for tasks that should wait until the device has connectivity or is on an unmetered network, such as background downloads). WorkManager is Android's Jetpack library for scheduling background work that should run reliably later, surviving app restarts and device reboots; "deferrable" means the work can wait for a convenient time instead of running at once.
Protocol design
Bootstrap: GET /items?after=<last id>&limit=3 (keyset pages; response includes sync_cursor)
(keyset page = "the next 3 rows with id greater than the last id I got", not "page number N")
Resume: GET /changes?since=<cursor>&limit=3 -> { changes: [...], next_cursor, has_more }
Expired: 410 { "error": "cursor_expired", "action": "resnapshot" }
- Cursor, not timestamp. Use a monotonically increasing sequence number (one that only ever goes up: 1, 2, 3, never repeating or going back) from a server-side change log. A "modified since time T" query misses rows written with an earlier timestamp that commit later (clock skew means two servers' clocks disagree; transaction ordering means a write stamped earlier can become visible later) and mishandles rows sharing one timestamp. A timeline with illustrative times:
- 10:00:00.000: transaction A starts and stamps row X with
updated_at = 10:00:00.000, but has not committed. - 10:00:00.050: transaction B stamps row Y
10:00:00.050and commits. - 10:00:00.100: the client syncs, sees only Y, and remembers T =
10:00:00.050. - 10:00:00.200: transaction A commits. Row X now exists with a timestamp before T.
- Next sync asks for rows modified after
10:00:00.050. X's stamp is10:00:00.000, so X is never sent. A sequence number assigned in the change log at commit time cannot be skipped this way.
- 10:00:00.000: transaction A starts and stamps row X with
- Bootstrap. The client pages through a snapshot. The server returns
sync_cursor, the highest sequence number at the start of that read. The client records it from the first page, before reading the snapshot, so changes made during the snapshot read are replayed afterwards instead of lost. A timeline with six rows and three rows per page:- The first page response carries
sync_cursor = 6; the client stores 6 and reads rows 1 to 3. - The server edits row 2, which becomes change 7. The client's copy of row 2 is now stale.
- The client reads rows 4 to 6, finishing the snapshot, then calls
/changes?since=6. Change 7 comes back and the stale row 2 is corrected. - Had the client stored the cursor only at the end, after the edit, it would hold 7 and never ask for change 7, so row 2 would stay stale. If a change happens to land on a row the client read after it (say an edit to row 5 as change 7), the replay applies the same data again, which is harmless as the next step explains.
- The first page response carries
- Idempotent apply. An operation is idempotent when doing it twice leaves the same result as doing it once. Upsert and delete can be applied twice safely, so replaying an overlap is harmless. This is what makes step 2 correct and makes a crash mid-sync harmless.
- Resume. The client persists the new cursor only after the page's changes are applied (the store and the cursor in one local transaction). A crash then repeats a page, never skips one.
has_moretells the client to keep fetching with the new cursor. - Deletions. A deletion is a change record with
op: "delete"and the id (a tombstone). Without it the client cannot tell "unchanged" from "gone". The alternative, the client sending its list of ids and the server returning the missing ones, costs bytes proportional to the collection and so loses the delta advantage. - Coalescing (merging several changes to one row into one). If row 2 was edited twice, the server sends only its latest state. Order between different ids does not matter once upserts are idempotent.
- Retention and expiry. The change log and tombstones cannot grow forever. Purge old entries and remember the oldest sequence still kept. A cursor older than that cannot be served correctly, since deletions in the gap were purged, so the server answers
410, which MDN defines as "no longer available ... likely to be permanent", and the client discards local state and bootstraps again. The status code is a design choice; what matters is that clients treat it as "resnapshot", not "retry".
Runnable demonstration
In a Node 22 container with no dependencies: docker run --rm -v "$PWD":/w -w /w node:22 node delta.mjs. delta.mjs holds the server (rows, change log, retention floor) and a client (store, cursor, bootstrap, sync):
// Run: node delta.mjs (Node 22, no dependencies)
import http from 'node:http';
// ---- server: current rows + an append-only change log with a retention floor ----
const rows = new Map(); // id -> row (live rows only)
let seq = 0; // global change counter
let log = []; // {seq, op, id, row?}
let floor = 0; // changes with seq <= floor have been purged
const upsert = (id, title) => { const row = { id, title, rev: ++seq }; rows.set(id, row); log.push({ seq, op: 'upsert', id, row }); };
const del = id => { rows.delete(id); log.push({ seq: ++seq, op: 'delete', id }); }; // tombstone
const purgeTo = n => { log = log.filter(c => c.seq > n); floor = n; };
for (let i = 1; i <= 6; i++) upsert(i, `Task ${i}`);
const server = http.createServer((req, res) => {
const u = new URL(req.url, 'http://x'); const send = (s, o) => { res.writeHead(s, { 'content-type': 'application/json' }); res.end(JSON.stringify(o)); };
if (u.pathname === '/items') { // snapshot page, keyset by id
const after = Number(u.searchParams.get('after') || 0), lim = Number(u.searchParams.get('limit') || 3);
const page = [...rows.values()].filter(r => r.id > after).sort((a, b) => a.id - b.id).slice(0, lim);
return send(200, { items: page, next_after: page.length === lim ? page.at(-1).id : null, sync_cursor: seq });
}
if (u.pathname === '/changes') { // delta page
const since = Number(u.searchParams.get('since')), lim = Number(u.searchParams.get('limit') || 3);
if (since < floor) return send(410, { error: 'cursor_expired', action: 'resnapshot' });
const latest = new Map(); // coalesce: keep only the newest change per id
for (const c of log.filter(c => c.seq > since)) latest.set(c.id, c);
const all = [...latest.values()].sort((a, b) => a.seq - b.seq), page = all.slice(0, lim);
return send(200, { changes: page.map(c => c.op === 'delete' ? { op: 'delete', id: c.id } : { op: 'upsert', row: c.row }),
next_cursor: page.length ? page.at(-1).seq : since, has_more: all.length > lim });
}
send(404, {});
});
await new Promise(r => server.listen(0, r));
const base = `http://127.0.0.1:${server.address().port}`;
// ---- client: local store + cursor, persisted together after each applied page ----
const store = new Map(); let cursor = null; let bytes = 0, reqs = 0;
const get = async p => { const r = await fetch(base + p); const t = await r.text(); bytes += t.length; reqs++; return { status: r.status, body: JSON.parse(t) }; };
const stats = () => { const s = `${reqs} requests, ${bytes} bytes`; bytes = 0; reqs = 0; return s; };
async function bootstrap(afterFirstPage) {
store.clear(); let after = 0, first = true;
for (;;) {
const { body } = await get(`/items?after=${after}&limit=3`);
if (first) { cursor = body.sync_cursor; first = false; afterFirstPage?.(); } // cursor is taken BEFORE reading the snapshot; the hook lets a demo edit land right after page 1
for (const r of body.items) store.set(r.id, r);
if (body.next_after == null) break; after = body.next_after;
}
}
async function sync() {
for (;;) {
const { status, body } = await get(`/changes?since=${cursor}&limit=3`);
if (status === 410) { console.log(' 410 cursor_expired -> re-bootstrap'); return bootstrap().then(sync); }
for (const c of body.changes) c.op === 'delete' ? store.delete(c.id) : store.set(c.row.id, c.row); // upsert/delete are idempotent
cursor = body.next_cursor; // advance only after the page is applied
if (!body.has_more) return;
}
}
const show = l => console.log(l.padEnd(34), 'store=', JSON.stringify([...store.values()].map(r => `${r.id}:${r.title}`)), 'cursor=', cursor);
await bootstrap(); show('bootstrap (6 rows):'); console.log(' ', stats());
upsert(2, 'Task 2 edited'); del(4); upsert(7, 'Task 7'); upsert(2, 'Task 2 edited again');
await sync(); show('delta after 4 server events:'); console.log(' ', stats(), '(edit of 2 coalesced, delete of 4 sent as a tombstone)');
await sync(); show('delta with nothing new:'); console.log(' ', stats());
del(1); upsert(8, 'Task 8'); purgeTo(seq - 1); // retention purge removes history the client never saw
await sync(); show('after purge past client cursor:'); console.log(' ', stats());
await bootstrap(() => upsert(3, 'Task 3 changed mid-snapshot')); // an edit arrives after page 1 was served
show('bootstrap with a racing edit:'); console.log(' ', stats());
await sync(); show('sync replays the racing edit:'); console.log(' ', stats());
server.close();
Output:
bootstrap (6 rows): store= ["1:Task 1","2:Task 2","3:Task 3","4:Task 4","5:Task 5","6:Task 6"] cursor= 6
3 requests, 334 bytes
delta after 4 server events: store= ["1:Task 1","2:Task 2 edited again","3:Task 3","5:Task 5","6:Task 6","7:Task 7"] cursor= 10
1 requests, 196 bytes (edit of 2 coalesced, delete of 4 sent as a tombstone)
delta with nothing new: store= ["1:Task 1","2:Task 2 edited again","3:Task 3","5:Task 5","6:Task 6","7:Task 7"] cursor= 10
1 requests, 48 bytes
410 cursor_expired -> re-bootstrap
after purge past client cursor: store= ["2:Task 2 edited again","3:Task 3","5:Task 5","6:Task 6","7:Task 7","8:Task 8"] cursor= 12
5 requests, 448 bytes
bootstrap with a racing edit: store= ["2:Task 2 edited again","3:Task 3","5:Task 5","6:Task 6","7:Task 7","8:Task 8"] cursor= 12
3 requests, 352 bytes
sync replays the racing edit: store= ["2:Task 2 edited again","3:Task 3 changed mid-snapshot","5:Task 5","6:Task 6","7:Task 7","8:Task 8"] cursor= 13
1 requests, 125 bytes
Reading it: the bootstrap loads 6 rows in 3 requests (334 bytes). Four server events (edit of 2, delete of 4, add of 7, a second edit of 2) arrive as 3 changes in 1 request of 196 bytes: the two edits to row 2 were coalesced and row 4 arrived as a tombstone. A sync with nothing new costs one 48-byte reply. After the server purged history past the client's cursor, the client received 410, re-bootstrapped and ended with the correct rows (row 1, deleted while it was away, is gone; row 8 is present) in 5 requests, 448 bytes. In the last scenario an edit to row 3 lands right after the first snapshot page was served, so the client finishes the bootstrap holding the old Task 3; because the cursor was taken from that first page, the next sync fetches the edit (change 13) and repairs the row. A client that took its cursor from the last page would have skipped change 13 and kept the stale row. At this tiny size a snapshot is cheap; the saving appears when the collection is large and the change set is small.
Trade-offs and pitfalls
- The server must keep a change log (write cost and storage) and a retention policy. Choose retention to exceed how long a user typically stays away, and fall back to a snapshot beyond it.
- Clients must handle
410. A client that retries a stale cursor forever loops. - Multiple collections need their own cursors (or one global stream with a type tag).
- Delta covers server-to-client changes. Conflict resolution for offline edits made on the device is a different problem.
- Permission changes: if the user loses access to a row, emit a delete for them, or the row lingers on the device.
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