Amazon Mobile Developer (Junior Level) Interview Preparation Guide
Amazon's mobile developer interview process follows a structured funnel approach starting with recruiter screening, followed by technical phone screens, and concluding with on-site interviews. The process emphasizes both technical depth (mobile-specific coding, platform knowledge) and Amazon's Leadership Principles. For junior-level candidates, interviews focus on core competency demonstration, hands-on coding ability, and learning potential rather than system design or architectural decisions.
Interview Rounds
Recruiter Screening
What to Expect
Initial conversation with Amazon recruiter to assess background, experience, and cultural fit. This round determines whether you proceed to technical interviews. The recruiter will discuss your mobile development experience, projects you've built, and motivation for joining Amazon. You will also receive information about the role, team structure, and Amazon's culture.
Tips & Advice
Be specific about your mobile development experience and projects. Clearly articulate why you're interested in Amazon and this specific role. Ask insightful questions about the team size, the charter of the team, whether this is a new role or backfill, and the hiring manager's leadership style. Be professional and personable with the recruiter as they are your main point of contact throughout the process. Have your resume and relevant work samples ready to reference.
Focus Topics
Understanding Amazon's Culture and Leadership Principles
Familiarize yourself with Amazon's 16 Leadership Principles, especially Customer Obsession, Ownership, and Learn and Be Curious which are frequently assessed.
Practice Interview
Study Questions
Motivation and Career Goals
Prepare a coherent narrative about why you want to work at Amazon and how this role aligns with your career trajectory in mobile development.
Practice Interview
Study Questions
Mobile Development Experience Overview
Clearly articulate your experience with iOS and/or Android development, specific projects you've shipped, technologies used, and measurable impact of your work.
Practice Interview
Study Questions
Technical Phone Screen
What to Expect
A 45-60 minute technical assessment conducted by a senior engineer or hiring manager. This round evaluates your core mobile development skills, problem-solving approach, and communication ability. You will be asked to solve a mobile-specific coding problem using your preferred language (Swift for iOS or Kotlin/Java for Android) while sharing your screen or writing code in a collaborative editor. The interviewer will assess your understanding of mobile fundamentals, ability to write clean code, and how you approach debugging.
Tips & Advice
Practice coding on actual mobile platforms, not just general coding. Be prepared to code in Swift or Kotlin/Java depending on your primary platform focus. Think out loud while solving problems; explain your approach before diving into code. For junior level, interviewers expect solid fundamentals but don't expect perfect solutions immediately—they value your ability to think through problems and communicate clearly. Test your code mentally and catch edge cases. Be ready to discuss trade-offs and optimization opportunities. Have your development environment ready if using a collaborative code editor.
Focus Topics
API Integration and Network Handling
Making HTTP requests, parsing JSON responses, handling network errors, managing concurrent requests, and implementing retry logic.
Practice Interview
Study Questions
Mobile App Lifecycle Management
Understanding activity/view controller lifecycle, app state management, handling background/foreground transitions, and managing resources appropriately.
Practice Interview
Study Questions
Swift Language Fundamentals (iOS)
Core Swift syntax, optionals, error handling, closures, higher-order functions, and common Swift patterns used in iOS development.
Practice Interview
Study Questions
Kotlin/Java Language Fundamentals (Android)
Core Kotlin and Java syntax, type system, functional programming concepts, generics, and common Android patterns.
Practice Interview
Study Questions
Mobile View and UI Component Implementation
Building custom views, understanding view hierarchies, implementing list/table views with reusable cells, handling view lifecycle, and managing layout constraints.
Practice Interview
Study Questions
Mobile Development Fundamentals Interview
What to Expect
This on-site round (typically conducted remotely for junior roles) dives deeper into mobile development fundamentals and practical problem-solving. You'll discuss your understanding of mobile-specific challenges including performance optimization, battery efficiency, memory management, and cross-platform considerations. The interviewer may ask you to build a small feature or debug existing code, combining coding challenges with architectural discussion appropriate to junior level.
Tips & Advice
Focus on practical, real-world mobile development concerns. Be specific about how you've handled performance issues, memory constraints, or device compatibility challenges in past projects. For junior level, demonstrate understanding of best practices even if you haven't implemented all of them yet. Be ready to discuss trade-offs between battery life, performance, and code complexity. Prepare to code incrementally—start with a basic solution, then discuss potential improvements. Show awareness of mobile-specific considerations like network latency and power consumption.
Focus Topics
Cross-Platform and Device Compatibility
Handling different screen sizes, orientations, and iOS/Android version differences. Understanding responsive design principles for mobile. Knowledge of cross-platform frameworks like React Native or Flutter basics.
Practice Interview
Study Questions
Debugging Mobile-Specific Issues
Using native debuggers and profiling tools, identifying device-specific bugs, reproducing and fixing issues across different device configurations.
Practice Interview
Study Questions
State Management and Data Persistence
Local data persistence using core data (iOS), room database (Android), or shared preferences. Managing app state, handling data synchronization, and recovering from network failures.
Practice Interview
Study Questions
Mobile Performance Optimization
App startup time optimization, frame rate maintenance (60fps), battery efficiency, network request optimization, and identifying performance bottlenecks using profiling tools.
Practice Interview
Study Questions
Memory Management and Garbage Collection
Understanding memory leaks, reference cycles, automatic memory management in Swift, and manual memory management patterns in Java/Kotlin. Know how to identify and prevent common memory issues.
Practice Interview
Study Questions
Mobile Platform-Specific Deep Dive
What to Expect
This on-site round focuses on deep knowledge of your primary platform (iOS or Android). You'll be asked about platform-specific APIs, frameworks, design patterns, and how you approach common mobile development challenges. The interviewer may present a feature requirement and ask you to design the implementation using native platform capabilities. This round assesses your practical experience and understanding of platform best practices.
Tips & Advice
Demonstrate genuine expertise in your primary platform. Be familiar with native APIs relevant to the job description: camera integration, location services, push notifications, app store deployment. Discuss real projects you've built and specific challenges you've solved. For junior level, you're not expected to know every API deeply, but should know how to find and learn new APIs quickly. Discuss design patterns you've used (MVC, MVVM, etc.) and explain why. Be ready to discuss trade-offs between native APIs and third-party libraries. Show enthusiasm for learning more about your platform.
Focus Topics
Camera and Media Integration
Using device camera, handling photo/video capture, managing permissions, image processing, and camera permission flows.
Practice Interview
Study Questions
Mobile Security Best Practices
Secure data storage, encryption, authentication handling, API security, permission management, and protecting against common mobile vulnerabilities.
Practice Interview
Study Questions
Push Notifications Implementation
Setting up push notification services, handling remote and local notifications, managing notification permissions, and testing notification delivery.
Practice Interview
Study Questions
Location Services Integration
Using GPS and location APIs, requesting location permissions, handling background location updates, and managing battery impact of location tracking.
Practice Interview
Study Questions
Native Platform APIs and Frameworks
For iOS: UIKit/SwiftUI, Core Location, AVFoundation, UserNotifications, StoreKit. For Android: Android Framework, Location Services, Camera API, Firebase Cloud Messaging, Google Play Services.
Practice Interview
Study Questions
API Integration and Backend Collaboration
What to Expect
This on-site round evaluates your ability to work with backend APIs, third-party integrations, and handle real-world data challenges. You may be given a system design problem (appropriate to junior level) where you design a mobile app's architecture for integrating with an external service. The focus is on practical considerations: API design from mobile perspective, handling network failures, managing data synchronization, and communicating technical constraints to backend teams.
Tips & Advice
Discuss real examples of API integrations you've implemented. Explain how you handle common network issues like timeouts, slow connections, and offline scenarios. For junior level, demonstrate understanding of request/response cycles, JSON parsing, and error handling. Be ready to discuss trade-offs between functionality and battery/data usage. Show ability to work collaboratively with backend teams. Discuss how you would communicate API requirements from mobile perspective (pagination, response size, retry policies). Mention tools and frameworks you've used for networking (URLSession, Alamofire, Retrofit, OkHttp).
Focus Topics
Testing Network Code
Mocking network responses, testing error scenarios, load testing APIs, and debugging network issues using tools like Charles Proxy or Fiddler.
Practice Interview
Study Questions
Third-Party Service Integration
Integrating external services like payment providers, analytics, social media SDKs, and handling OAuth/authentication flows.
Practice Interview
Study Questions
Data Synchronization Patterns
Keeping local data in sync with backend, handling conflicts, implementing efficient sync mechanisms, and managing bandwidth constraints.
Practice Interview
Study Questions
Network Error Handling and Resilience
Handling network timeouts, connection failures, retry logic with exponential backoff, offline-first patterns, and graceful degradation.
Practice Interview
Study Questions
RESTful API Design for Mobile
Understanding API design from mobile perspective, including pagination, filtering, field selection, response size optimization, and versioning strategies.
Practice Interview
Study Questions
Amazon Leadership Principles and Behavioral Interview
What to Expect
This on-site round assesses your alignment with Amazon's 16 Leadership Principles through structured behavioral questions. An interviewer (often a 'Bar Raiser') will ask about your past experiences to evaluate principles like Customer Obsession, Ownership, Learn and Be Curious, and Earn Trust. For junior-level candidates, Amazon looks for demonstrated examples of learning quickly, taking initiative on smaller tasks, collaborating effectively with teammates, and showing genuine care for customers/users.
Tips & Advice
Prepare 6-8 concrete examples from your past experiences (projects, internships, coursework, side projects) that demonstrate Amazon's Leadership Principles. Use the STAR method (Situation, Task, Action, Result) for each example. Focus on demonstrating learning ability, ownership within your scope, customer-focused thinking, and collaboration. For junior level, don't claim to have led large teams or made company-wide decisions—instead highlight specific contributions you've made, how you solved problems independently with minimal guidance, and how you've grown from challenges. Practice articulating your examples concisely. Research Amazon's business and products to show genuine interest in the company.
Focus Topics
Amazon Leadership Principle: Invent and Simplify
Share examples where you found simpler or more efficient ways to solve problems, improved existing processes, or experimented with new approaches.
Practice Interview
Study Questions
Amazon Leadership Principle: Earn Trust
Discuss times you built credibility, communicated transparently, admitted mistakes and learned from them, and delivered on commitments consistently.
Practice Interview
Study Questions
Amazon Leadership Principle: Customer Obsession
Demonstrate genuine concern for end users/customers. Prepare examples where you prioritized user needs, sought user feedback, or made decisions based on customer impact.
Practice Interview
Study Questions
Amazon Leadership Principle: Learn and Be Curious
Demonstrate eagerness to learn new technologies, skills, and approaches. Discuss how you've picked up new mobile frameworks, learned from failure, or explored new areas of development.
Practice Interview
Study Questions
Amazon Leadership Principle: Ownership
Show initiative and accountability for work within your scope. Prepare examples where you took responsibility for completing tasks, resolved issues independently, or followed up on commitments.
Practice Interview
Study Questions
Frequently Asked Mobile Developer Interview Questions
Can a memory leak happen in a garbage-collected language? Explain how, and how you would tell a real leak from normal heap growth.
Sample Answer
Short answer. Yes. A garbage collector frees objects the program can no longer reach; it cannot free objects the program still references but will never use again. A leak in a managed language is therefore unintended reachability: something with a long life (a static field, a global cache, a listener list, a thread) keeps a reference to something that should have been dropped.
How it happens
- Unbounded cache or map. Entries are added per request and never evicted.
- Registrations never removed. A long-lived publisher holds a listener, which holds a whole screen or request context (on mobile, a leaked screen object can pin its entire view tree: see the mobile section below).
- Pooled threads with thread-local data. The thread is a root and lives as long as the pool.
- Native resources. Memory behind a handle (direct buffers, which are Java byte buffers whose memory lives outside the garbage-collected heap, plus files and sockets) the GC does not see or only frees late.
CPython (the standard Python interpreter) frees mostly by reference counting: each object keeps a count of the references to it and is freed the moment the count reaches zero. The same rule applies: a reference held from a module-level object keeps the object alive, and reference cycles (objects that point at each other, so neither count reaches zero) wait for the cyclic collector, a separate periodic pass that finds and frees such groups.
Real leak versus normal growth
Normal growth: heap used climbs between collections and falls when one runs. Collectors take their time, so a process can look large and be healthy. The signal is the low point after collection:
- Real leak: the low points keep rising, with the same load, until collections thrash.
- Normal growth: low points settle on a plateau (a warm cache, a loaded dataset).
Then confirm by comparing two snapshots and reading which allocation site or class grows.
A Python demonstration of the compare-two-snapshots method with tracemalloc (standard library):
import tracemalloc
_cache = {} # module-level: reachable for the life of the process
def handle_request(i):
_cache[i] = bytearray(10_000) # added per request, never evicted
tracemalloc.start()
for i in range(1_000):
handle_request(i)
snap1 = tracemalloc.take_snapshot()
for i in range(1_000, 3_000):
handle_request(i)
snap2 = tracemalloc.take_snapshot()
top = snap2.compare_to(snap1, "lineno")[0]
print("biggest growth between snapshots:")
print(" ", top.traceback[0].filename.split("/")[-1], "line", top.traceback[0].lineno,
"size_diff_MB=%.1f" % (top.size_diff / 1e6))
Run with python -I leak_vs_growth.py on python:3.12-slim (Python 3.12.15). Output:
biggest growth between snapshots:
leak_vs_growth.py line 7 size_diff_MB=20.2
Two thousand more requests added 20.2 MB at line 7 of the listing (counting import tracemalloc as line 1), the _cache[i] = ... store. That line is the leak because nothing removes entries; the same code with an eviction limit would show a size_diff that stops growing. The size matches the arithmetic: 2,000 requests x 10,000 bytes is 20.0 MB, plus a little container overhead.
On the JVM the equivalent tools are jcmd <pid> GC.class_histogram and heap dumps (with -XX:+HeapDumpOnOutOfMemoryError), per the JDK troubleshooting guide.
The C++ contrast
C and C++ leak differently: an allocation with no matching free. new int[1000] with no delete[] loses the only pointer, and nothing ever reclaims it, even though the program can no longer reach it. A garbage collector would reclaim that case; the managed-language leak is the opposite case, where a pointer is still held.
#include <cstdio>
int main() {
int* buf = new int[1000]; // never deleted
buf[0] = 1;
std::printf("%d\n", buf[0]);
return 0;
}
Built with g++ -g -fsanitize=address in gcc:14 and run, AddressSanitizer's leak checker (LeakSanitizer) reports at exit:
==15==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 4000 byte(s) in 1 object(s) allocated from:
#0 0xffffb0c94b9c in operator new[](unsigned long) (/usr/local/lib64/libasan.so.8+0xd4b9c)
#1 0x400910 in main /w/cpp_missing_delete.cpp:4
(frames #2 to #4, in libc and the program entry point, omitted)
SUMMARY: AddressSanitizer: 4000 byte(s) leaked in 1 allocation(s).
The addresses and process id differ between runs and machines; the 4000 bytes (1000 ints of 4 bytes) and the file and line do not.
Valgrind's memcheck (a tool that runs the program on a simulated CPU and reports leaks) serves the same purpose. These are optional tools you can use instead of or alongside the compiler flag; both find unreachable-but-allocated memory, which is a different test from the heap-snapshot method for reachable growth. In modern C++ the usual fix is to stop calling new and delete by hand and use smart pointers (objects such as std::unique_ptr that call delete automatically when they go out of scope) and containers.
The same leak on a phone
Mobile apps follow the same rule: a long-lived object holds a reference to a short-lived screen.
- Android (Kotlin or Java). A destroyed
Activity(one screen) stays in memory if a static field, a singleton, a registered listener or a running background task still references it, and with it its entire view tree and bitmaps. LeakCanary, a library added as adebugImplementationdependency so it only exists in debug builds, watches destroyed Activities and Fragments and reports the reference chain that keeps one alive. Android Studio's Memory Profiler can capture a heap dump and its class filter "Show activity/fragment leaks" lists instances that should be gone. - iOS (Swift). Swift uses automatic reference counting, the same count-the-references idea as CPython. Two objects that hold strong references to each other, or a closure stored on an object that captures
selfstrongly, form a retain cycle and are never freed; the usual fix is a weak capture such as[weak self]. Xcode's Memory Graph Debugger shows live objects and the references between them and flags suspected leaks, so you can look for leaked instances in the object list and follow their reference arrows. - Without a production heap dump, reproduce the leak in a debug build: open and close the suspect screen about ten times, force a collection or take a heap snapshot, and count how many instances of that screen class are still alive. Zero or one is healthy; one per visit is the leak, and the reference chain from the tool names the holder.
Takeaway
GC removes the unreachable-leak class and keeps the reachable-leak class. Decide with post-collection heap over time, then name the retaining reference with a snapshot diff or heap dump.
Design an endpoint that lets a client receive only the changes since its last sync. Specify the request parameters, the ordering and idempotency guarantees you give, and the response format for creates, updates and deletes. What happens when the client's marker is missing or too old?
Sample Answer
Direct answer
Expose a read-only GET /changes endpoint driven by an opaque cursor (a bookmark the server hands back and the client returns unchanged). The server keeps an append-only change log with a monotonically increasing sequence number, returns the latest change per entity after the cursor in sequence order, and encodes deletes as tombstones (small records that say "this id is gone"). Delivery is at-least-once (a change may arrive more than once but never zero times; the alternative, exactly-once, is very hard to promise over a mobile network that can drop a reply after the server has already sent it), and the client makes that safe by being an idempotent consumer (a receiver that ends in the same state however many times it is handed the same item) that compares versions, so replays are harmless. No cursor means "send a snapshot", and a cursor older than the retained log gets 410 Gone with a machine-readable code that tells the client to throw away its marker and resync.
Request parameters
| Parameter | Meaning |
|---|---|
cursor | Opaque token from the previous response. Absent means first sync. The client never parses or builds it. |
limit | Page size, a positive integer: default 100, capped at 500 by the server so one request cannot be made arbitrarily large. Zero, negative or non-numeric values fall back to the default (parse it as an integer and check the range, because a limit of 0 makes a page that can never advance and a non-number silently becomes NaN). |
page | Snapshot paging token, only present while walking a snapshot. A token that does not decode to the expected shape gets 400 with invalid_page. |
types (optional) | Comma list of entity types, so a screen that only needs orders does not pull invoices. |
Response format
One envelope for both modes:
{
"mode": "delta",
"items": [
{ "op": "upsert", "id": "c", "version": 2, "data": { "title": "C2" } },
{ "op": "delete", "id": "b", "version": 2 }
],
"has_more": false,
"next_cursor": "eyJzIjoxMH0"
}
- Create and update are the same operation,
upsert: the item carries the full current representation plus a per-entityversion. The client does not need to know whether it has seen the id before, which removes a whole class of "update for a row I never got" bugs. - Delete is
{ "op": "delete", "id", "version" }with no body. has_moresays whether to call again immediately.next_cursoris always present; the client stores it only after the page has been applied to local storage.
Ordering and idempotency guarantees
-
Order: items inside a response, and across pages, are in ascending change-sequence order.
-
Compaction (keeping only the newest log entry per entity and dropping the older ones): if one entity changed three times since the cursor, only its latest state is returned. The client still converges to the right state and the payload shrinks. The cost is that intermediate states and cross-entity transaction boundaries are not observable, and the contract should say so.
-
Idempotency:
GETis safe to repeat. Replaying the same cursor returns the same changes or a superset that includes newer ones. (The cursor in the example above,eyJzIjoxMH0, is just the JSON{"s":10}encoded as base64url, a URL-safe text encoding; it means "sequence 10", and the client never needs to decode it.) The client applies an item only whenitem.versionis greater than the version it holds, so applying a page twice, or two overlapping pages, gives the same end state. Delivery is therefore at-least-once with an idempotent consumer, which is simpler and more robust than trying to promise exactly-once over a flaky mobile network. -
Cursor advance: the client replaces its stored cursor only after the page is durably applied. A crash between receiving and applying just replays the page.
-
Commit order caveat: if sequence numbers are assigned when a row is written but become visible when its transaction commits (a transaction is a group of writes that become visible together, at commit), a slow transaction can commit after a later one. A client that already moved past that sequence would skip the row. Assign the sequence at commit time, or only serve up to a safe watermark (a sequence number below which every change is known to be committed, so nothing can still appear under it) set just below the oldest in-flight transaction.
Worked timeline with real values: (t1) transaction A writes a row and is assigned sequence 41, but is still open. (t2) Transaction B writes a row, is assigned 42 and commits. (t3) The client syncs. Without a watermark the server sees only 42 as committed, returns it, and the client stores cursor 42. (t4) Transaction A commits; its row carries sequence 41, below the client's cursor, so no later call ever returns it and the row is lost to that client. With a watermark, at t3 the oldest open transaction is A (41), so the server serves only up to 40, returns nothing, and the client keeps cursor 40. After A commits, the next call returns 41 and 42 in order.
Missing marker and too-old marker
- Marker missing: serve a snapshot, a paged list of live rows only (no tombstones needed). The server pins the head sequence at the moment the snapshot starts and carries it inside the
pagetoken; the final page returnsnext_cursorfor that pinned head. Changes made while the client walks the snapshot are picked up by the first delta call. An entity may then arrive twice, which the version check absorbs. - Marker too old: the log cannot be kept forever, and purged tombstones mean a long-offline client can no longer be told what was deleted. Record the highest purged sequence; a cursor below it is rejected with
410 Goneand{ "error": "cursor_expired", "resync": "/changes" }. MDN describes 410 as a permanent "no longer available" condition, which fits: retrying that cursor will never work. SendCache-Control: no-store(a header telling caches not to keep the response) so no cache replays it. The client discards local synced data (or marks it stale) and runs the snapshot flow. - Marker malformed or forged:
400withinvalid_cursor. Keeping 400 and 410 distinct lets the client tell "my bookmark is bad" from "my bookmark is too old". - Choosing retention: keep tombstones longer than the longest gap you expect a real client to be offline (30 days is a common starting point, an assumption to tune against your own app-open data). Longer retention costs log storage; shorter retention means more full resyncs on the slowest, most expensive path.
Worked example
The program below implements the server and a client, then drives them through a first sync, a delta with compaction and a delete, a replay, an expired cursor and a forged cursor.
import http from 'node:http';
// ---- server: change log with compaction and tombstone retention ----
const log = []; // { seq, id, op, version, data?, at }
let seq = 0;
let purgedThrough = 0; // highest seq whose entries were discarded
const entities = new Map();
function write(id, data) {
const version = (entities.get(id)?.version ?? 0) + 1;
entities.set(id, { id, data, version, deleted: false });
log.push({ seq: ++seq, id, op: 'upsert', version, data });
}
function remove(id) {
const version = entities.get(id).version + 1;
entities.set(id, { id, version, deleted: true });
log.push({ seq: ++seq, id, op: 'delete', version });
}
function purgeUpTo(s) { // retention job: drop log entries up to seq s
for (let i = log.length - 1; i >= 0; i--) if (log[i].seq <= s) log.splice(i, 1);
purgedThrough = Math.max(purgedThrough, s);
}
const enc = (o) => Buffer.from(JSON.stringify(o)).toString('base64url');
const dec = (s) => { try { return JSON.parse(Buffer.from(s, 'base64url')); } catch { return null; } };
function changes(url) {
// limit: a positive integer, default 100, capped at 500; zero, negative or non-numeric values fall back to the default
const asked = Number.parseInt(url.searchParams.get('limit') ?? '', 10);
const limit = Number.isInteger(asked) && asked >= 1 ? Math.min(asked, 500) : 100;
const raw = url.searchParams.get('cursor');
let after, snapshotMode = false;
if (raw === null) { after = null; snapshotMode = true; }
else {
const c = dec(raw);
if (!c || typeof c.s !== 'number') return [400, { error: 'invalid_cursor' }];
if (c.s < purgedThrough) return [410, { error: 'cursor_expired', resync: '/changes' }];
after = c.s;
}
if (snapshotMode) {
// Snapshot: live rows only, paged by id; the cursor to resume deltas is pinned at the head seq
// read when the snapshot began (carried inside the page token) so nothing between pages is missed.
const pageRaw = url.searchParams.get('page');
const t = pageRaw ? dec(pageRaw) : { head: seq, last: '' };
if (!t || typeof t.head !== 'number' || typeof t.last !== 'string') return [400, { error: 'invalid_page' }];
const rows = [...entities.values()].filter((e) => !e.deleted && e.id > t.last).sort((a, b) => (a.id < b.id ? -1 : 1)).slice(0, limit + 1);
const more = rows.length > limit; const page = rows.slice(0, limit);
const items = page.map((e) => ({ op: 'upsert', id: e.id, version: e.version, data: e.data }));
return [200, { mode: 'snapshot', items, has_more: more,
page: more ? enc({ head: t.head, last: page.at(-1).id }) : null,
next_cursor: more ? null : enc({ s: t.head }) }];
}
// Delta: newest entry per entity only (compaction), ordered by seq ascending.
const latest = new Map();
for (const e of log) if (e.seq > after) latest.set(e.id, e);
const all = [...latest.values()].sort((a, b) => a.seq - b.seq);
const page = all.slice(0, limit);
const more = all.length > limit;
const cursorSeq = more ? page.at(-1).seq : seq; // when drained, jump to the head
return [200, { mode: 'delta', items: page.map(({ seq: s, ...r }) => r), has_more: more, next_cursor: enc({ s: cursorSeq }) }];
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://x');
const [code, body] = changes(url);
res.writeHead(code, { 'content-type': 'application/json' });
res.end(JSON.stringify(body));
}).listen(0);
const base = `http://127.0.0.1:${server.address().port}/changes`;
// ---- client: applies items idempotently, advances cursor only after applying ----
const local = new Map();
function apply(items) {
for (const it of items) {
const cur = local.get(it.id);
if (cur && cur.version >= it.version) continue; // replay or stale: ignore
if (it.op === 'delete') local.set(it.id, { version: it.version, deleted: true });
else local.set(it.id, { version: it.version, data: it.data });
}
}
const view = () => [...local].filter(([, v]) => !v.deleted).map(([k, v]) => `${k}=${v.data}`).sort().join(' ');
async function get(q) { const r = await fetch(`${base}?${q}`); return [r.status, await r.json()]; }
async function syncFromScratch() {
local.clear();
let q = 'limit=2', body;
do {
[, body] = await get(q); apply(body.items);
q = 'limit=2&page=' + body.page;
} while (body.has_more);
return body.next_cursor;
}
async function syncDelta(cursor) {
let c = cursor;
for (;;) {
const [status, body] = await get(`limit=2&cursor=${c}`);
if (status === 410) return { resync: true };
apply(body.items); c = body.next_cursor;
if (!body.has_more) return { cursor: c, last: body };
}
}
for (const id of ['a', 'b', 'c', 'd', 'e']) write(id, id.toUpperCase() + '1');
let cursor = await syncFromScratch();
console.log('1 snapshot :', view());
write('a', 'A2'); write('a', 'A3'); remove('b'); write('f', 'F1'); write('c', 'C2');
const r1 = await syncDelta(cursor);
console.log('2 delta :', view());
console.log(' last page items:', JSON.stringify(r1.last.items));
// Replay the same cursor: same result, nothing changes locally
const r2 = await syncDelta(cursor);
console.log('3 replay :', view(), '(unchanged)');
// A stale copy arriving late (version 1 of 'a' after the client holds version 3) must be ignored
apply([{ op: 'upsert', id: 'a', version: 1, data: 'A1' }]);
console.log('3b stale item:', view(), '(unchanged)');
// Retention purges everything up to seq 8 while this client was offline at its old cursor
remove('d'); write('g', 'G1');
purgeUpTo(8);
const r3 = await syncDelta(cursor);
console.log('4 old cursor:', JSON.stringify(r3));
const r4 = await syncDelta(r1.cursor);
console.log('5 fresh cursor still valid:', r4.resync ? 'resync' : 'ok', view());
console.log('6 garbage cursor status:', (await get('cursor=%%%'))[0]);
cursor = await syncFromScratch();
console.log('7 after resync:', view());
for (const q of ['limit=0', 'limit=-1', 'limit=abc', 'page=%%%']) console.log('8 bad input', q.padEnd(9), '->', (await get(q))[0]);
server.close();
It prints (the demo client passes limit=2 explicitly so pages stay small):
1 snapshot : a=A1 b=B1 c=C1 d=D1 e=E1
2 delta : a=A3 c=C2 d=D1 e=E1 f=F1
last page items: [{"id":"f","op":"upsert","version":1,"data":"F1"},{"id":"c","op":"upsert","version":2,"data":"C2"}]
3 replay : a=A3 c=C2 d=D1 e=E1 f=F1 (unchanged)
3b stale item: a=A3 c=C2 d=D1 e=E1 f=F1 (unchanged)
4 old cursor: {"resync":true}
5 fresh cursor still valid: ok a=A3 c=C2 e=E1 f=F1 g=G1
6 garbage cursor status: 400
7 after resync: a=A3 c=C2 e=E1 f=F1 g=G1
8 bad input limit=0 -> 200
8 bad input limit=-1 -> 200
8 bad input limit=abc -> 200
8 bad input page=%%% -> 400
Reading it: a was written three times but arrives once as A3 (compaction), b was deleted so it disappears from the view, replaying the same cursor changes nothing (idempotent), a stale copy of a (version 1, after the client holds version 3) is ignored by the version check (remove that check and line 3b prints a=A1), the cursor at sequence 5 is below the purge point and gets the resync signal, and the cursor at sequence 10 is above it, so it still works and also delivers the later delete of d, the forged cursor is a 400, and a limit of 0, -1 or abc falls back to the default page size instead of crashing the handler (with the naive Math.min(Number(limit), 100) a limit=0 throws inside the server on the first snapshot request), while a forged page token is a 400.
Reading the listing: write and remove append to log with the next seq; purgeUpTo is the retention job that discards old entries and records purgedThrough. changes decodes the cursor (bad cursor gives 400, a sequence below purgedThrough gives 410), serves a snapshot when there is no cursor, and otherwise builds a delta by keeping the newest entry per id (the latest map is the compaction) in seq order. The client's apply skips any item whose version is not newer than the one it holds, and syncDelta only moves its cursor to next_cursor after applying the page.
Tracing the output with the real sequence numbers: the five initial writes are seq 1 to 5, so the snapshot ends with cursor {"s":5}. Step 2 adds a (6), a (7), delete b (8), f (9), c (10). After compaction the entries after 5 are a@7, b@8, f@9 and c@10; with limit=2 page one is a and the delete of b (cursor {"s":8}, has_more true) and page two is f and c (cursor {"s":10}), which is why the last page printed holds f and c. Step 4 adds delete d (11) and g (12) and purges through 8: the old cursor 5 is below 8, so it gets 410, while cursor 10 is not, so it still works and delivers d and g.
Trade-offs and pitfalls
- Timestamps as cursors (
updated_since=2026-10-01T10:00:00Z) are tempting but fail on clock skew, equal timestamps at a page boundary, and rows committed late with an older timestamp. A sequence-based opaque cursor avoids all three and lets you change its internals later. - Hard-deleting rows with no tombstone makes deletes invisible to every client that was offline, so they keep showing deleted data until a manual refresh.
- Per-entity versions versus the global cursor: the cursor says where to resume; the version decides whether to apply an item. They solve different problems and both are needed.
- What flips the design: if clients must see every intermediate state (an audit feed), drop compaction and return the full log. If the dataset is small and changes constantly, a plain full fetch with an
ETagis cheaper than maintaining a log.
Running the code
docker run --rm --ulimit core=0 -v "$PWD":/w -w /w node:22 sh -c 'timeout 60 node changes.mjs'
Save the listing as changes.mjs (Node 22 ES module, no install step, uses the built-in fetch).
Design a Java logging helper that redacts common PII, such as email addresses, Social Security numbers, and credit-card numbers, from log messages before they are written. State your assumptions, show the use of compiled regular-expression patterns, discuss the performance considerations, explain how you would configure the helper to extend the redaction patterns, and describe how you would test and validate it at scale. Also cover what structured fields you would include (for example a correlation ID and a job or request identifier), what you would log at INFO versus DEBUG level, and how the approach differs for a nightly batch scoring job versus a real-time service.
Sample Answer
Direct answer
A PII-safe logging helper redacts common sensitive patterns (emails, Social Security numbers, credit card numbers) from a message before it is ever written to a log, using compiled regular expressions applied consistently across every log call, while also enforcing structured fields (a correlation ID, a job or request identifier), log-level discipline, and an extensibility point for adding new redaction patterns as new sensitive-data types are identified.
Structured elaboration
Redaction via compiled regex patterns. A small set of well-tested regular expressions, compiled once and reused (not recompiled on every log call, which would be wasteful), match common PII shapes: an email address pattern, a Social Security number pattern (\d{3}-\d{2}-\d{4}), and a credit-card-like sequence of 13 to 16 digits (allowing spaces or dashes as separators, since real card numbers are often written with them). Each match is replaced with a fixed [REDACTED] marker before the message is passed to the underlying logging framework.
Performance considerations. Compiling patterns once at startup (not per-call) and running them against every log message adds a small, roughly-constant regex-matching cost per log call; for a very high-throughput logging path this is measurable but usually acceptable, since the alternative (an actual PII leak into a log aggregation system with far broader read access than the original data source) is a materially worse outcome, and the specific cost can be validated by simply measuring log throughput with and without the redaction step in a realistic load test.
Configuration to extend redaction patterns. New PII patterns identified over time (an internal account-number format specific to the business, for instance) should be addable without modifying the core logging class, via a constructor parameter or configuration file accepting additional patterns, so the redaction logic can grow as new sensitive-data types are identified in practice, not require a code change and redeploy of the core logging utility itself for every new pattern.
Testing and validating at scale. Beyond unit tests confirming each pattern redacts correctly and that non-sensitive messages pass through unchanged, validating "at scale" means running the redaction logic against a genuinely large, realistic sample of actual (or realistically-synthetic) log messages and manually or statistically auditing a sample of the OUTPUT for anything that looks like it should have been redacted but wasn't, since regex patterns can have false negatives on real-world data that a small, hand-written unit test suite won't surface (an international phone number format, a differently-formatted SSN with no dashes).
Structured fields, log levels, and INFO versus DEBUG. Beyond redaction, the logging helper should ensure every log entry carries a correlation ID (tying related log lines from the same request or job together) and a job/run identifier where relevant (for a batch context specifically). INFO-level logging should capture what a normal operator needs to see to understand system behavior (a job started, a job completed, a summary count); DEBUG-level logging can include more granular detail useful only during active troubleshooting, but should still be redacted with exactly the same discipline as INFO, since a DEBUG log accidentally left enabled in production is a very common real-world path by which sensitive data actually ends up in logs.
Differences for a batch job versus a real-time service. A nightly batch scoring job's logging strategy centers on a per-run summary (start time, record count processed, error count, completion status) tagged with a job_id and run_id, since a human reviewing a batch job's logs the next morning wants an overview, not necessarily a line per record. A real-time service's logging centers on a per-REQUEST correlation ID and typically much higher log volume, and needs sampling strategies for very high-traffic endpoints (logging a representative fraction of successful requests at INFO, while still logging every failure) to keep log volume and cost manageable without losing visibility into failures specifically.
Worked example
public class PiiSafeLogger {
private static final Pattern EMAIL = Pattern.compile("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}");
private static final Pattern SSN = Pattern.compile("\\b\\d{3}-\\d{2}-\\d{4}\\b");
private static final Pattern CREDIT_CARD = Pattern.compile("\\b(?:\\d[ -]*?){13,16}\\b");
private final List<Pattern> patterns = new ArrayList<>(List.of(EMAIL, SSN, CREDIT_CARD));
public PiiSafeLogger(List<Pattern> extraPatterns) { patterns.addAll(extraPatterns); }
public String redact(String message) {
if (message == null) return null;
String result = message;
for (Pattern p : patterns) result = p.matcher(result).replaceAll("[REDACTED]");
return result;
}
}
Verification note: a Java Development Kit was not available in this execution sandbox, so the exact class above was not compiled directly; the identical regular-expression patterns and replacement logic were instead executed against an equivalent Python translation (Python's re module uses the same pattern syntax for these specific expressions) and confirmed: an email address embedded in a sentence is fully redacted; a dashed Social Security number is fully redacted; a spaced 16-digit credit-card-like number is fully redacted; a message containing no PII passes through completely unchanged; and a null input returns null rather than throwing. This confirms the REGEX LOGIC is correct; it does not confirm Java-specific behavior (for example, java.util.regex.Pattern's exact semantics versus Python's re), which is a disclosed limitation of this verification, not a claim of full Java execution.
Trade-offs and pitfalls
Regex-based redaction is a strong first line of defense but is not exhaustive: a credit card number with unusual formatting, a non-US identification number format, or a PII field that doesn't match any recognizable pattern at all (a person's name in a free-text field, which has no distinguishing shape a regex can reliably catch) can pass through unredacted; this is exactly why validating "at scale" against a realistic log sample, not just a handful of unit tests, matters, and why some organizations pair regex-based redaction with an explicit ALLOWLIST discipline (only log fields you've deliberately reviewed) for the highest-sensitivity data flows, rather than relying on a denylist-style redaction pattern to catch everything. The most common real-world failure mode is a DEBUG-level log statement, written during development and forgotten, that logs an entire request or record object directly (bypassing the redaction helper entirely, since it wasn't routed through it) rather than going through this centralized logging path, which is why enforcing that ALL logging goes through a single, redacting logger (not calling a raw print or an unwrapped logging framework call directly) is as important as the redaction logic itself.
Describe how to make a custom Android UI control (for example a custom slider) accessible to TalkBack and keyboard users. Detail which AccessibilityNodeInfo properties and AccessibilityActions to populate, how to expose the current value and range, how to support keyboard focus and arrow-key adjustments, and how to test the custom control with accessibility services.
Sample Answer
Approach (brief)
Implement accessibility by updating the view's AccessibilityNodeInfo and handling actions so TalkBack and keyboard users can discover, focus, and change the slider value.
Key AccessibilityNodeInfo properties & actions
- Populate in onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo):
- info.className = SeekBar::class.java.name (or "android.widget.SeekBar")
- info.contentDescription = label or null if children announce
- info.isClickable = true; info.isFocusable = true
- info.rangeInfo = AccessibilityNodeInfo.RangeInfo.obtain(AccessibilityNodeInfo.RangeInfo.RANGE_TYPE_FLOAT, min, max, current)
- info.isAccessibilityFocused when appropriate
- add custom actions: ACTION_SCROLL_FORWARD / ACTION_SCROLL_BACKWARD and ACTION_SET_PROGRESS (API 24+)
Keyboard and D-pad support
- Override performAccessibilityAction(action, args):
- Handle ACTION_SCROLL_FORWARD / BACKWARD: increment/decrement by step
- Handle ACTION_SET_PROGRESS (args?.getFloat(ARG_PROGRESS)) to set exact value
- Implement onKeyDown / onKeyUp:
- Left/Down = decrement; Right/Up = increment; Home/End jump to min/max
- Call sendAccessibilityEvent(TYPE_VIEW_TEXT_CHANGED) or TYPE_VIEW_ACCESSIBILITY_FOCUSED as appropriate
Expose current value & range
- Use RangeInfo (above). Also update contentDescription or announce via announceForAccessibility("Volume 40 percent") after changes.
Testing
- Manual: enable TalkBack, navigate to control, verify label, range, and actions; use hardware keyboard / emulator keyboard arrows
- Automated: use Accessibility Test Framework, Espresso with AccessibilityChecks, and UiAutomator to simulate TalkBack interactions
- Verify with Accessibility Scanner and Accessibility Insights for Android
Sample Kotlin snippets
override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo) {
super.onInitializeAccessibilityNodeInfo(info)
info.className = SeekBar::class.java.name
info.isClickable = true
info.rangeInfo = AccessibilityNodeInfo.RangeInfo.obtain(
AccessibilityNodeInfo.RangeInfo.RANGE_TYPE_FLOAT, min, max, value
)
info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD)
info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD)
}
This ensures TalkBack announces role + value/range, keyboard arrows change value, and automation/tests can validate behavior.
You are the lead for mobile QA at a social app and regulators require proof that location and contacts are only accessed when declared. Design automated and manual testing processes, CI checks, static analysis, runtime monitoring, and audit artifact generation to ensure permission usage descriptions, runtime prompts, and actual API calls comply with privacy policies before every release.
Sample Answer
Situation & goal
Design an end-to-end program (automated + manual) so regulators can verify location/contacts are accessed only when declared — before every release.
High-level approach
- Prevent: static checks to ensure declarations exist and code doesn’t call APIs anonymously.
- Detect: runtime instrumentation in CI and prod debug builds to record actual API calls and prompts.
- Prove: generate signed audit artifacts (reports, screenshots, logs, SBOM).
Automated CI checks
- Manifest/Info.plist rule: fail if required keys missing or extra keys present.
- Android: verify AndroidManifest.xml contains only declared uses-permission and rationale strings.
- iOS: verify Info.plist has NSLocation*UsageDescription and NSContactsUsageDescription matching policy.
- Source-scan: run static analyzer + custom grep/AST rules to flag direct calls to LocationManager, FusedLocationProvider, ContactsContract, CNContactStore, and popular libs. Example CI step: run a Kotlin/Swift AST script that errors on blacklisted API usage outside guarded wrappers.
- Lint rules: add Android Lint and SwiftLint custom checks to enforce use of permission-wrapper functions.
Static analysis & policy enforcement
- Implement single permission-wrapper APIs (e.g., RequestLocation(), RequestContacts()) — require annotation @PermissionGate.
- Static analyzer enforces that only annotated wrappers call OS permission APIs. Use tools:
- Android: ErrorProne or custom ASM/ktlint plugin.
- iOS: SourceKit/clang-tidy script to find un-wrapped calls.
- Check that runtime prompt strings equal approved compliance text (regex compare to approved list).
Runtime monitoring (CI + release)
- In CI:
- Instrumented UI tests (Espresso/XCUITest) that exercise flows and capture prompt screenshots and accessibility labels for consent.
- Inject debug wrappers that log: timestamp, caller stack, permission type, decision, and purpose tag. Store logs as artifact.
- In release/debug builds:
- Lightweight telemetry (privacy-preserving, hashed IDs) that records permission grants/uses and purpose tags, with user opt-out. Use local logs for auditable builds.
- Implement method interception:
- Android: ProGuard rules + wrapper around FusedLocationProvider and ContentResolver; prohibit reflection to bypass.
- iOS: Use function interposition in debug builds or method swizzling in Obj-C/Swift to log CNContactStore and CLLocationManager accesses.
Manual testing
- QA checklist and flows that must be executed: first-run flows, background access, denied-then-grant, edge OS versions.
- Capture:
- Screenshots of OS prompts on typical devices (iOS 14/15+, Android 11+).
- Screen recordings of full flows.
- Repro steps and device logs (adb logcat / Console) collected into the release folder.
Audit artifact generation
- For each build produce signed bundle with:
- Permission matrix CSV: declared permissions vs. code-flagged usages vs. runtime-use events.
- Prompt screenshots and hashes.
- Instrumented test results and logs (stack traces for each access).
- Static-analysis report listing files and line numbers for permission API calls.
- SBOM and third-party libs list.
- Automate packaging and GPG-sign artifact; upload to compliance storage with retention policy.
Verification & metrics
- Gate release by failing CI if:
- Any runtime log shows permission use without matching declaration/purpose.
- Static scan finds unwrapped API usage.
- Prompt strings differ from approved text.
- Track KPIs: number of flagged accesses, time-to-fix, coverage of instrumented flows.
Trade-offs & safeguards
- Minimize runtime overhead by enabling heavy instrumentation only in CI/debug; use sampling/aggregation in production.
- Ensure telemetry is privacy-preserving and regulator-approved.
This combination of enforced wrapper patterns, static/AST checks, CI instrumented tests, runtime interception, curated manual flows, and signed audit artifacts provides determinism and reproducible evidence that location and contacts are only accessed as declared.
Walk me through a decision you made in your work that you feel genuinely reflected one of your company's stated values or principles, not just technically satisfied it. Use a clear situation-task-action-result structure, name which value or principle it reflects, and explain how you knew it actually mattered rather than being a rationalization after the fact.
Sample Answer
Direct answer
A decision genuinely reflects a stated value, rather than merely being compatible with it, when the value actually changed what you chose to do, not just how you described it afterward. The strongest answers make that causal link explicit: what you would have done differently if the value hadn't been a factor.
Structured elaboration
- Situation and task: the decision point, described briefly.
- The counterfactual test: name what the default, easier choice would have been, and what specifically made you choose differently.
- Action: what you actually did, including who you had to convince or coordinate with.
- Result: the outcome, and ideally a signal that the choice was validated rather than merely feeling principled at the time.
Worked example
Faced with a choice between shipping a quick, directionally useful analysis in time for a decision meeting, or spending an additional two weeks on a more rigorous version, the default and professionally "safer" choice would have been to wait for rigor. Choosing to ship the quicker, clearly caveated version instead, because the business decision had a hard deadline and a rigorous-but-late analysis would have been useless, shows a genuine trade-off rather than a reflexive one. The decision was validated when the more rigorous follow-up analysis, completed afterward, confirmed the same direction, meaning the faster call hadn't cost the business a wrong decision.
Trade-offs and pitfalls
A story where the value and the easy choice happen to be the same thing doesn't actually demonstrate anything, since no real trade-off was made; choose a story with genuine tension in it. Naming the value first and building a story to fit it, rather than the reverse, tends to produce something that sounds rationalized rather than genuine; a genuinely reflective answer usually names the counterfactual without being asked. A result stated only as "and it felt right" is weaker than any concrete validation signal, even an imperfect one.
Design secure handling for deep links, universal links, and Android intent filters to prevent intent spoofing, unauthorized data exfiltration, and privilege escalation. Include verification strategies such as App Links and Associated Domains, server-side validation of link parameters, and safe fallback behavior when verification fails.
Sample Answer
Direct answer
The design has three independent layers, and skipping any one leaves a real gap: platform-level verified linking (Android App Links, iOS Universal Links) so only your genuine app can claim a given web URL instead of any app that declares the same custom scheme, minimal and non-exported app-side surface so an unverified intent cannot reach a sensitive component directly, and server-side validation of whatever the link actually carries, since a URL is attacker-controlled input no matter how it arrived. When verification fails, fall back to a safe, unauthenticated web view rather than either silently proceeding or performing a privileged action.
Structured elaboration
The three named risks, concretely.
- Intent spoofing (Android specifically): a malicious app registers an intent filter matching the same custom scheme or even the same web URL pattern your app uses, and either intercepts a link meant for your app or sends your app a crafted intent pretending to be a legitimate deep link.
- Unauthorized data exfiltration: a deep link that directly triggers an action exposing data (opening a screen that displays account details, or an intent that returns data to the calling app) without confirming the caller or the user's intent first.
- Privilege escalation: a deep link that triggers a sensitive action (changing an email address, approving a payment) as a side effect of merely opening the link, letting an attacker who gets a victim to tap a crafted link perform an action the victim never actually authorized.
Verification strategies: App Links and Associated Domains. Both mechanisms move link ownership out of the app's own unverified claim and into something the operating system checks against a file only the legitimate domain owner can publish, which is what actually prevents another app from successfully claiming your links.
- Android App Links: the app's intent filter declares
android:autoVerify="true", and the operating system checks aassetlinks.jsonfile served over HTTPS from/.well-known/assetlinks.jsonon your domain, listing the app's package name and signing-certificate fingerprint. Only if that file matches does the OS treat the link as verified and route it directly to your app without the usual disambiguation dialog; if it does not match (or the file is missing), the OS falls back to treating the scheme as an ordinary, unverified intent filter, which any app could have also declared. - iOS Universal Links (Associated Domains): the equivalent mechanism, an
apple-app-site-associationfile served from/.well-known/on your domain over HTTPS, listing your app's identifier. iOS checks this at app-install time (and re-checks periodically) and only routes matching links directly to your app if it validates. - In both cases, the security property comes from the fact that only someone who controls the actual domain (via HTTPS hosting access) can publish the verification file, which is a much stronger claim than "an app declared it wants this scheme," the thing a spoofing app can trivially also do.
App-side hardening, independent of link verification. Verification stops other apps from successfully claiming your links; it does not, by itself, make the component your app routes a verified link to safe against a malformed or malicious payload.
- Expose only what genuinely needs to be reachable externally (
android:exported="false"on Android for anything that does not need to receive intents from outside the app); every exported, unauthenticated entry point is attack surface. - Never let a deep link directly trigger a sensitive action without additional confirmation; a link should, at most, navigate to a screen where the user then explicitly confirms, not execute the sensitive action as a direct side effect of the link being opened.
- Use explicit intents for anything internal; only the externally-reachable entry point should be an implicit, deep-link-triggered one, and it should immediately hand off to internal, non-exported components using explicit intents.
Server-side validation of link parameters. A deep link's parameters are attacker-controlled input exactly like a query string on any web request, regardless of how convincing the verification badge on the link looked. Treat every parameter accordingly:
- Prefer opaque, single-use, short-lived server-issued tokens embedded in the link over directly meaningful parameters (
?token=<opaque>rather than?userId=1234&action=approve), so a link cannot simply be edited to target a different account or action by an attacker who observes the URL shape. - On the server side, when the app exchanges the token for the actual action, re-validate: token has not expired, has not already been used (single-use, checked and consumed atomically), belongs to the currently authenticated session or an explicitly allowed flow (a password-reset link, for example, should still require the user to be able to access the associated email or phone, not just possess the URL), and the requesting app's identity/signature matches what issued the token, where the platform can attest to that.
- Never trust a parameter's value for an authorization decision just because it arrived via a verified link; verification proves the link's origin claim, not that its contents are safe to act on.
Safe fallback behavior when verification fails. A link that fails App Links/Universal Links verification, or that the app receives through an unverified, implicit pathway, should degrade to the least-privileged reasonable behavior: open a normal web page on your domain requiring the user to authenticate through the standard web login flow, never silently perform a privileged action or reveal account information based on an unverified link's claims. This also covers the "app not installed" case gracefully by construction, since the fallback web page works regardless of whether the app exists on the device at all.
Verification flow.
sequenceDiagram
participant U as User
participant OS as Device OS
participant App as Your App
participant Web as Your domain (HTTPS)
U->>OS: Taps link https://example.com/reset?token=...
OS->>Web: Fetch /.well-known/assetlinks.json (or apple-app-site-association)
Web-->>OS: Signed association file
alt verification succeeds
OS->>App: Route directly to app with link data
App->>Web: Exchange token server-side (validate expiry, single-use, binding)
Web-->>App: Action result
else verification fails or app not installed
OS->>Web: Open link as a normal web page
Web-->>U: Standard authenticated web flow
end
Worked example
A password-reset deep link, https://example.com/reset?token=abc123, sent by email:
- User taps the link. The device checks
assetlinks.json/apple-app-site-associationonexample.com; suppose it validates, since this is your genuine domain and app. - The OS routes the link directly to your app (bypassing any spoofing app, since that app could not have published a matching, HTTPS-hosted association file for your domain).
- The app extracts
token=abc123and, rather than trusting it locally, calls your backend:POST /auth/reset-token/exchange {token: "abc123"}. - The server checks: does this token exist, has it expired (a short lifetime, minutes), has it already been consumed, and is it bound to a reset request actually initiated for this account. If all checks pass, it atomically marks the token used and returns a short-lived, scoped "you may now set a new password for this account" session, not a full login session.
- The app shows a "set new password" screen using that scoped session; it does not display any account information or perform any other action based solely on the token's presence.
- If instead the link had reached the app through an unverified path (say, a malicious app had somehow gotten it to launch your app via a raw, non-HTTPS-verified custom scheme with a manipulated token), the same server-side exchange in step 4 is what actually protects the user: the manipulated or reused token fails validation there regardless of how it arrived at the app.
Trade-offs and pitfalls
- Treating link verification as sufficient authorization on its own. App Links/Universal Links verification proves the link came from a domain you control; it says nothing about whether the specific token or parameters in that link are still valid, unused, or intended for the current user. The server-side exchange step is not optional even for a fully verified link.
- Falling back to a raw custom URL scheme "for compatibility." A bare custom scheme (
myapp://reset?token=...) with no HTTPS-hosted verification file can always be claimed by any other app that also declares it; if you must support one (older devices, a partner integration), treat anything arriving through it as fully untrusted input, identically to the unverified-fallback branch above, never as equivalent to a verified App Link/Universal Link. - Letting a deep link perform the sensitive action directly instead of just navigating to a confirmation step. This is the direct path to the privilege-escalation risk named in the question: a link that immediately approves a payment or changes account settings on open, rather than requiring an explicit in-app confirmation after navigation, turns "get a victim to tap a link" into "get a victim to authorize an action."
- Forgetting the exported-component surface. Verified linking controls which app the OS routes a link to, but any Android component still marked exported remains directly reachable by another app's crafted intent, independent of the App Links verification path entirely; the two defenses are complementary, not substitutes for each other.
Security wants a change that protects customers but adds friction or latency they will feel. How do you weigh the customer impact, and how would you roll it out?
Sample Answer
Direct answer
I weigh the security benefit against the friction a customer will actually feel, using numbers where I can. Then I look for the lowest-friction way to get most of the protection, and I roll it out in stages with measurements and an exit. Security wins when the risk is serious and not otherwise reducible, but how it ships is a customer-experience decision.
How I weigh it
- Risk removed. What attack or loss does the change prevent, how likely, and for whom? Ask security for a specific scenario, not "best practice."
- Friction added. Which customers feel it, how often, at what moment (signing in daily versus a rare admin action), and what do they do when annoyed (abandon, call support, work around it)?
- Cheaper routes to the same protection. Apply the strict control only where risk is high (risk-based or step-up checks: ask for an extra proof only when something looks unusual or the action is sensitive), remember trusted devices, or give a smoother factor.
- Who carries the cost. Friction on a signup flow costs conversion; friction in an enterprise admin flow costs support calls.
Three related cases
| Case | The tension | What I would do |
|---|---|---|
| Multi-factor authentication (MFA, a second proof of identity at sign-in) | Fewer account takeovers but setup drop-off and more lockout-related support contacts (people locked out of their account who then contact support) | Offer easier factors, remember trusted devices, ask for MFA on sensitive actions first, provide clear recovery, and plan support staffing for launch |
| Encryption that adds latency for latency-sensitive customers | Stronger protection versus slower responses for customers whose use depends on speed | Measure added delay at the 95th percentile (P95: the response time that 95% of requests beat, which shows the slow tail that averages hide) on their real paths, optimize before shipping, keep the protection that is required, and discuss any customer-specific option with security rather than silently weakening it |
| Social login (sign in with another provider's account) | Higher signup conversion versus sharing data with a third party and tying account recovery to it | Offer it next to email sign-in, request only needed data, state plainly what is shared, and test conversion against trust |
Worked example (illustrative): rolling out MFA to 100,000 accounts
- Stage 1: 5% of accounts (5,000), chosen to include small and large customers. Track setup completion, lockout-related support contacts, and sign-in success.
- Gate: advance only if the thresholds agreed beforehand with security and support are met. Illustrative thresholds: at least 80% of prompted accounts finish setup (4,000 of the 5,000), no more than 10 lockout-related support contacts a week (2 per 1,000 accounts), and sign-in success falls by no more than 1 percentage point. Miss any one and I pause, fix the cause, and rerun the stage.
- Stage 2 and 3: widen, with in-app explanation of why, then move from encouraged to required on a published date. Keep a rollback and an exception path for customers with real blockers.
Pitfalls
Do not frame it as security versus customers. Do not roll out to everyone at once. Do not set a "will not hurt conversion" bar with no measurement behind it.
In Kotlin, implement a thread-safe in-memory LRU cache class for Bitmaps with a configurable maximum size in bytes. API should include get(key), put(key, bitmap, sizeInBytes), and automatic eviction of least-recently-used entries until total size is below the limit. Operations must be O(1). Provide the class structure, key data structures used (LinkedHashMap or custom doubly-linked list + hashmap), and note concurrency considerations.
Sample Answer
Approach (brief)
Use a LinkedHashMap with accessOrder = true to maintain LRU ordering and a running total size. Keep O(1) get/put by map operations and update size on insert/remove. Ensure thread-safety with a single ReentrantLock (or synchronize) to avoid race conditions during reads/writes and eviction.
Kotlin implementation
import android.graphics.Bitmap
import java.util.LinkedHashMap
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
class LruBitmapCache(private val maxBytes: Long) {
private val lock = ReentrantLock()
// accessOrder=true -> iteration order is LRU -> MRU
private val map = object : LinkedHashMap<String, Bitmap>(16, 0.75f, true) {}
private var currentSize = 0L
fun get(key: String): Bitmap? = lock.withLock {
return map[key] // accessOrder ensures this marks it as recently used
}
fun put(key: String, bitmap: Bitmap, sizeInBytes: Int) = lock.withLock {
val prev = map.put(key, bitmap)
if (prev != null) {
currentSize -= sizeOf(prev)
}
currentSize += sizeInBytes
evictIfNeeded()
}
private fun evictIfNeeded() {
val iter = map.entries.iterator()
while (currentSize > maxBytes && iter.hasNext()) {
val entry = iter.next()
val removed = entry.value
currentSize -= sizeOf(removed)
iter.remove()
// optionally recycle bitmaps: removed.recycle()
}
}
private fun sizeOf(bitmap: Bitmap): Int {
// API-safe: bytes per row * height or bitmap.byteCount on newer APIs
return bitmap.byteCount
}
}
Key points & trade-offs
- Data structures: LinkedHashMap(accessOrder=true) + hashmap semantics -> O(1) lookup and ordering.
- Concurrency: ReentrantLock ensures atomic get/put/evict. For higher read concurrency, consider ReadWriteLock or lock striping, but must ensure consistent size accounting.
- Eviction: done inside put while holding lock to avoid races.
- Memory: track byte sizes precisely; handle large single items (if item > maxBytes decide to reject or clear cache first).
- Android notes: consider using Bitmap.recycle() if appropriate and watch for bitmap.byteCount availability across API levels.
List design differences and best practices between touch and pointer interactions. Cover affordances, hover states, target sizes, gestures, and feedback so a component works well on touch devices, trackpads, and mouse pointers.
Sample Answer
Answer (UI Designer perspective)
Affordances
- Use visible, touch-friendly affordances: raised buttons, clear outlines, large hit areas. Avoid relying solely on small text links for primary actions.
- Visual cues (shadows, depth, contrast) indicate tappability across devices.
Hover states
- Provide hover-only enhancements (tooltips, subtle elevation) but ensure primary cues don’t depend on hover: replicate important info on touch via persistent labels or focus states.
- Use focus styles for keyboard and accessibility.
Target sizes
- Minimum interactive target: 44–48 px (mobile) and 32 px acceptable on dense pointer UIs. Add spacing to prevent accidental taps.
- Expand hit area beyond visible control when needed.
Gestures
- Support simple, discoverable gestures (tap, double-tap sparingly, swipe with clear affordance). Don’t overload with complex gestures; provide alternative controls for critical actions.
- Distinguish drag vs. scroll with clear handles and threshold delays.
Feedback
- Immediate visual (pressed state), haptic (mobile), and audible feedback where appropriate. Debounce actions and show loading states to prevent repeated taps.
Design tokens: separate pointer and touch spacing, hover, pressed, focus states in the system so components adapt per input modality.
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