Interview Paths: Mobile, Backend, and AI Systems
This is a quick interview index, not a duplicate encyclopedia. Start with the short hit point, then follow the linked concept sheet for the detailed explanation, implementation, failure modes, security/performance implications, and alternatives. Add a specific story from your own work; do not claim experience you do not have.
Beginner — Name the contract
Can you create a value directly from a protocol?
Short answer: No. A protocol describes requirements, while a concrete type supplies an implementation that can be constructed. Create a value of a conforming type, then use the protocol to describe the capabilities that code needs from that value.
Detailed explanation:
🧠 Hit point: A protocol describes requirements; a concrete type conforms to it and is what you construct.
Example: Define protocol Store {} then create struct MemoryStore: Store {} and instantiate MemoryStore(). Avoid: writing Store() as if the protocol were a concrete type. Tradeoff/detail: Protocol construction and existential values.
🟦 Illustrative example:
protocol DraftStoring {
func title(for id: String) -> String?
}
struct PreviewDraftStore: DraftStoring {
func title(for id: String) -> String? { "Preview draft" }
}
let store: any DraftStoring = PreviewDraftStore()
let title = store.title(for: "draft-1")🧠 The concrete initializer constructs the value; the protocol-typed binding exposes only its promised operations. The preview implementation is deliberately fixed data, so contract tests must not mistake it for evidence of persistence.
Where should an HTTP API enforce access permissions?
Short answer: The server must check who made each request and whether that user may access the requested resource. Hiding a button or validating input in the app can improve the interface, but a caller can bypass the app and send the request directly.
Detailed explanation:
🧠 Hit point: A client sends a request to a server endpoint, but the server must authenticate the principal and authorize access to each requested resource.
Example: The iOS app can hide an account button, but the API still checks account ownership for every request. Avoid: treating client-side validation as a security control. Tradeoff/detail: Request lifecycle and mobile API auth.
🟦 Illustrative example:
SELECT id, display_name
FROM accounts
WHERE id = $1 AND owner_principal_id = $2;🧠 In this illustrative PostgreSQL authorization-scoped query, $1 is the requested resource and $2 comes from the authenticated server-side principal, not the body. Parameterization prevents value interpolation, while the ownership condition limits visibility. A complete handler also validates input and applies its chosen not-found/forbidden policy without leaking other users’ resources.
How does an AI agent differ from a tool?
Short answer: A tool performs a specific operation, such as searching documents. An agent uses a model to decide which permitted operations to try while pursuing a goal, but its goal or proposed action does not itself authorize access to tools or data.
Detailed explanation:
🧠 Hit point: A tool performs one bounded capability; an agent uses a model-driven loop to pursue a goal by choosing among permitted observations/actions.
Example: A search tool returns matches; a read-only coding agent can use search, inspect results, and report a diagnosis. Avoid: assuming an agent's goal or prompt authorizes a tool call. Tradeoff/detail: Agent, tool, skill, workflow, and orchestrator.
🟦 Illustrative example:
search_tool_contract:
input: authorized_query_and_collection_scope
output: bounded_matches_with_source_ids
effects: read_only
review_agent_contract:
goal: explain_a_build_failure
tools: [search_sources, read_allowed_files]
terminal_result: cited_diagnosis_or_insufficient_evidence
limits: host_enforced_time_and_usage_budget🧠 This illustrative contract gives the tool one bounded operation and the agent an observation-driven choice of permitted operations. The host must enforce scope and limits; writing them in a prompt or this YAML does not grant or enforce authorization.
Intermediate — Explain a boundary clearly
How do dependency injection and dependency inversion differ?
Short answer: Dependency inversion means that higher-level rules depend on suitable abstractions instead of concrete low-level details. Dependency injection means supplying a dependency from outside the object that uses it; it can support that design, but merely passing objects around does not establish the dependency direction.
Detailed explanation:
🧠 Hit point: Dependency inversion is a direction-of-dependency principle; dependency injection is one way to provide an implementation at a composition boundary.
Example: A payment use case depends on an any PaymentRepository, and the app root supplies live or test implementation. Avoid: creating protocols/containers for every type. Tradeoff and detail: Canonical Swift dependency inversion.
🟦 Illustrative example:
protocol ReceiptSaving {
func save(reference: String) throws
}
struct CompleteCheckout {
let receipts: any ReceiptSaving
func record(reference: String) throws {
try receipts.save(reference: reference)
}
}🧠 The use case depends on a receipt capability rather than a database implementation, showing dependency inversion. The composition root injects the conformer, showing injection. A global service locator would hide construction/lifetime and is not required to achieve either principle.
How should you choose REST, GraphQL, or gRPC for a mobile product?
Short answer: Choose the API style that fits the client's data needs, contract changes, caching, streaming, and the team's operational skills. REST, GraphQL, and gRPC offer different tradeoffs, but none removes the need for server authorization, compatibility planning, and reliable failure handling.
Detailed explanation:
🧠 Hit point: Start with client data needs, contract evolution, caching, streaming, tooling, and the team's operational ability—not fashion.
Example: REST may suit a stable resource API; GraphQL can help diverse clients compose reads; gRPC can suit internal typed service calls. Avoid: assuming GraphQL or gRPC removes authorization/versioning work. Detail: API styles and tradeoffs.
🟦 Illustrative example:
operation: account_overview
client_needs:
fields: [display_name, available_balance, recent_transactions]
offline_reads: bounded_stale_snapshot
options:
rest: resource_endpoint_with_http_cache_contract
graphql: client_selected_fields_with_query_cost_limits
grpc: typed_protobuf_contract_with_supported_mobile_transport
shared_obligations:
- resource_authorization
- compatible_schema_evolution
- cancellation_timeout_and_error_mapping🧠 This comparison contract starts from a real read shape and evaluates transport-specific benefits. GraphQL field selection still needs server-side authorization and complexity limits; gRPC typing still needs deployment/transport support. Choose against measured round trips and operational constraints, not the table alone.
Senior — Reason about correctness and production behavior
How should a mobile write be retried after a timeout?
Short answer: A timeout means the result is unknown, not that the server did nothing. Reuse the same operation identifier for retries and have the server remember the logical outcome, so repeating the request cannot accidentally perform the same business action twice.
Detailed explanation:
🧠 Hit point: A timeout leaves the outcome unknown; retry with the same idempotency key and let the server durably return the same logical result.
Example: Keep the payment UI in a pending/unknown state until a status query confirms the result. Avoid: generating a new operation ID on each retry. Detail: Distributed reliability.
🟦 Illustrative example:
{
"operationId": "persisted-before-first-send",
"accountId": "account-demo",
"payload": { "amountCents": 2500, "currency": "TRY" },
"state": "outcome-unknown",
"retry": { "reuseOperationId": true, "reconcileBeforeNewIntent": true }
}🧠 This illustrative durable intent survives a restart and preserves identity for a retry of the same purchase. The server must atomically bind account/key/payload to a stored result and define its retention window; the JSON alone does not deduplicate concurrent requests or prove the first attempt failed.
What does a modular monolith provide before splitting into microservices?
Short answer: It separates responsibilities and dependency boundaries while keeping the application in one deployable system. This can improve ownership and testing without immediately adding network failures, coordinated deployments, and the operational work that separate services require.
Detailed explanation:
🧠 Hit point: It creates enforceable ownership and dependency boundaries without immediately paying the network, deployment, and on-call cost of distributed services.
Example: Separate payment and account modules with explicit contracts and a shared database transaction while their consistency requirements remain coupled. Avoid: equating many packages with good architecture. Detail: Backend patterns.
🟦 Illustrative example:
deployment: one_service
modules:
orders:
public_api: place_order
owns: order_state_and_rules
inventory:
public_api: reserve_stock
owns: availability_rules
allowed_coordination: explicit_in_process_contract
consistency: database_transaction_when_shared_invariant_requires_it
forbidden: orders_reading_inventory_private_tables_directly🧠 The sketch separates ownership without adding network calls or independently deployed consistency boundaries. A shared deployment can still have enforceable interfaces; move to services only when independent scaling/ownership warrants the operational cost.
How can a backend migration keep old app versions working?
Short answer: Add the new capability in a compatible form, migrate clients and data gradually, and observe actual use before removing the old contract. Mobile users do not all update at once, so removal must follow the supported-version policy rather than the release date of the newest app.
Detailed explanation:
🧠 Hit point: Expand compatibly, observe adoption, migrate data/clients, then contract only after the supported-version window.
Example: Add an optional response field first; ship clients that tolerate its absence; later remove a legacy endpoint only after usage and release policy allow it. Avoid: assuming every mobile user upgrades immediately. Detail: Enterprise mobile architecture.
🟦 Illustrative example:
{
"legacyField": "pending",
"paymentState": {
"status": "pending",
"operationId": "operation-demo"
}
}🧠 This illustrative expanded response retains the old field while new clients adopt a richer state object. Define consistent mappings, let clients tolerate absent/unknown fields, and observe supported-client adoption before removing the legacy shape. Adding fields is not automatically behaviorally compatible if clients reject them or the fields disagree.
Tech Lead — Make a decision and align owners
How should you choose an architecture pattern for a new feature?
Short answer: Choose the smallest structure that gives the feature clear state, navigation, business-rule, and testing boundaries. A simple screen and a complex payment flow need different amounts of structure, so judge MVC, MVVM-C, VIPER, or Clean Architecture by the problems they solve for this team.
Detailed explanation:
🧠 Hit point: Match the boundary to state complexity, navigation, business rules, testing needs, and team ownership; use the smallest pattern that addresses observed change.
Example: A small static settings screen can remain simple; a multi-step payment flow merits explicit state and navigation ownership. Avoid: pitching a pattern as universally superior. Detail: Mobile architecture pattern comparison.
🟦 Illustrative example:
enum CheckoutScreenState {
case editing
case submitting
case awaitingConfirmation(operationID: String)
case confirmed(receiptID: String)
}
protocol CheckoutNavigating {
@MainActor func showReceipt(reference: String)
}🧠 The example makes presentation states and navigation ownership explicit without requiring a particular architecture acronym. Keep these boundaries if they enable independent tests/changes; a simple screen may need less layering, while money-movement rules belong outside view rendering.
When is modularizing an iOS app worth the cost?
Short answer: Modularize when clearer ownership, faster builds, stable interfaces, or safer changes provide a measurable benefit. Start with a useful boundary and evaluate the result, because extra modules also add API design, dependency management, and integration work.
Detailed explanation:
🧠 Hit point: When measurable build, parallel ownership, API stability, or change-isolation pain outweighs module and integration overhead.
Example: Pilot a high-conflict feature with an acyclic API and track build time and cross-team changes. Avoid: creating one shared “Core” module for every unrelated utility. Detail: Enterprise mobile architecture.
🟦 Illustrative example:
candidate: account_history
observed_pain: unrelated_feature_changes_force_shared_rebuild_and_review
pilot_contract:
input: account_id_and_session_scope
output: account_history_feature_entry_point
dependencies: [history_domain, session_api, design_system]
evaluate:
- incremental_build_cost
- feature_change_scope
- integration_and_review_wait🧠 This proposed pilot states the problem and what data determines whether extraction helped. Keep the dependency graph acyclic and compare actual before/after costs; the number of packages is not a success metric.
How should a team resolve a technical-design disagreement?
Short answer: Agree on the user goal, constraints, and criteria for choosing before arguing for a preferred solution. Compare evidence or a small experiment, assign a decision owner, and record the choice plus a reason to revisit it so the team can move forward together.
Detailed explanation:
🧠 Hit point: Agree on user goals and decision criteria, compare options against evidence, record a reversible decision and revisit trigger, then commit as a team.
Example: Prototype build-time impact before choosing a modularization strategy. Avoid: voting by seniority or prolonging debate without new evidence. Detail: Decision-making and ADRs.
🟦 Illustrative example:
proposal: local_cache_for_account_history
options:
- bounded_disk_snapshot
- memory_only_cache
agreed_constraints:
- account_isolation
- acceptable_staleness_visible_to_user
- logout_cleanup
experiment: exercise_offline_launch_and_account_switch
decision_owner: history_feature_lead
revisit_when: measured_recovery_or_privacy_requirements_change🧠 This decision record makes the disagreement testable and gives it an owner. A fair process includes objections before commitment and a revisit trigger; it does not require endless consensus or a vote weighted by seniority.
How can a technical lead avoid becoming the team's bottleneck?
Short answer: Give work clear owners, stable interfaces, sequencing, and an escalation path, then delegate decisions within those boundaries. The lead remains responsible for integration and quality without needing to make or approve every small implementation choice.
Detailed explanation:
🧠 Hit point: Define interfaces, owners, sequencing, quality gates, and escalation paths; delegate decisions at the lowest safe level.
Example: One engineer owns API contract, another feature UI, and a third tests a stable boundary, with a named integrator. Avoid: becoming the only reviewer/architect for every decision. Detail: Technical leadership responsibilities.
🟦 Illustrative example:
delivery_contract:
api_owner: backend_partner
ios_owner: ios_feature_engineer
android_owner: android_feature_engineer
integration_owner: rotating_mobile_engineer
shared_scenarios:
- request_timeout_after_server_commit
- session_switch_during_request
review_rule: boundary_owner_reviews_contract_changes
lead_role: resolve_cross_boundary_risk_and_enable_owners🧠 The illustrative delegation contract permits parallel implementation against agreed semantics and assigns integration accountability. Rotating ownership and recording decisions reduce dependence on one lead; contracts still need executable checks and clear escalation.
Backend architecture questions
What should guide database selection and scaling?
Short answer: Start with the data relationships, correctness rules, and queries the product needs. Measure and improve the real workload with appropriate indexes and query changes before adding replicas or splitting data, because each scaling technique introduces consistency and operational tradeoffs.
Detailed explanation:
🧠 Hit point: Model consistency and query patterns first; index and profile real workloads before replicas, partitioning, or sharding.
Example: PostgreSQL transaction for a balance invariant and a cache only for explicitly stale-tolerant reads. Avoid: putting all reads in Redis without an invalidation/freshness contract. Detail: Database choices.
🟦 Illustrative example:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at, total_cents
FROM orders
WHERE account_id = $1 AND created_at < $2
ORDER BY created_at DESC
LIMIT 50;🧠 This illustrative PostgreSQL query uses a bounded page and an execution plan to investigate the actual access pattern. Consider an appropriate (account_id, created_at) index after measuring; ANALYZE executes the query, so use an authorized safe environment and realistic data. Replicas or sharding do not repair an incorrect consistency model.
When is a queue or event bus useful?
Short answer: Use one when work needs to happen asynchronously, absorb bursts, or reach several consumers without making the original request wait for everything. Consumers may see changes later and messages may be retried, so reliable publication, duplicate handling, and operational ownership must be part of the design.
Detailed explanation:
🧠 Hit point: Use one when asynchronous decoupling, burst absorption, or fan-out justifies eventual consistency and operational burden.
Example: Transactional outbox publishes a notification after a payment commit. Avoid: a dual write where database commit succeeds but event publish silently fails. Detail: Distributed reliability and case patterns.
🟦 Illustrative example:
BEGIN;
INSERT INTO orders (id, account_id, status)
VALUES ($1, $2, 'accepted');
INSERT INTO outbox (event_id, aggregate_id, event_type)
VALUES ($3, $1, 'OrderAccepted');
COMMIT;🧠 The illustrative transaction records the order and publication intent together. A separate publisher can retry the outbox, so consumers must deduplicate stable event IDs and define ordering/backpressure. An outbox removes a database/broker dual-write gap; it does not create universal exactly-once delivery.
How should an iOS app authenticate to a backend?
Short answer: Use a native authorization flow through the system browser with PKCE, which binds the returned authorization code to the app's original request. Protect tokens with platform storage and let the server check resource permissions; a mobile app cannot safely keep a shared client secret.
Detailed explanation:
🧠 Hit point: Use a native authorization flow with PKCE, short-lived access, carefully handled refresh, and server-side resource authorization; the app is a public client.
Example: Use the system browser for identity, store refresh material using platform protection, and recheck object permissions on each API action. Avoid: shipping a client secret or trusting a signed JWT as universal authorization. Detail: Mobile API authentication.
🟦 Illustrative example:
native_oauth_contract:
client_kind: public
browser: platform_authorization_session
flow: authorization_code_with_pkce
callback: registered_and_validated
access_tokens: short_lived_under_provider_policy
refresh_material: platform_protected_storage
resource_api:
authenticate_token: required
authorize_requested_account: required
client_secret_in_app: forbidden🧠 This illustrative contract separates native sign-in from per-resource server authorization. Use a maintained platform/provider flow with callback/state validation; a shipped app cannot keep a client secret confidential. Token validity alone does not prove permission to every account.
AI engineering and orchestration questions
When should you retrieve documents instead of fine-tuning a model?
Short answer: Retrieve relevant documents when an answer depends on changing, private, or citable information. Fine-tuning trains the model on examples to change its behavior, but it does not automatically keep an external knowledge source current or enforce who may read each document.
Detailed explanation:
🧠 Hit point: Prefer retrieval when answers depend on changing/private/citable knowledge; fine-tuning changes model behavior rather than supplying a live, access-filtered source of truth.
Example: Search a versioned policy library and cite the authorized passage. Avoid: assuming embeddings enforce access. Detail: RAG architecture.
🟦 Illustrative example:
request: answer_current_leave_policy
retrieval:
scope: authenticated_user_authorized_policy_versions
return: passage_text_source_id_and_effective_date
answer_contract:
cite: retrieved_supporting_passages
insufficient_support: report_missing_evidence
fine_tuning_role: optional_behavior_or_format_adaptation
not_a_replacement: live_authorization_filtered_knowledge🧠 The illustrative contract retrieves changing policy evidence at request time and defines abstention when it is insufficient. Fine-tuning may adapt behavior but does not make private knowledge current or enforce access. Retrieved instructions remain untrusted source text, not authority to invoke tools.
When does a workflow benefit from an agent?
Short answer: Use fixed steps when the required path is already known. An agent helps when observations require judgment about the next action, and multiple agents help only when useful tasks can be separated with clear ownership and a result that can be checked.
Detailed explanation:
🧠 Hit point: Keep known transitions deterministic; add a model-driven loop only for observation-dependent judgment, and delegate only independent bounded tasks.
Example: Parallelize a read-only security review and API contract review; serialize implementation on the agreed contract. Avoid: spawning agents for each small step. Detail: Orchestration patterns.
🟦 Illustrative example:
workflow:
deterministic_steps: [validate_scope, collect_pinned_diff]
independent_reviews:
- api_contract_review
- security_boundary_review
shared_input: same_immutable_diff_and_project_rules
merge: deduplicate_evidence_backed_findings
implementation: one_owner_after_review
limits: host_enforced_deadline_and_total_usage🧠 This proposed DAG parallelizes independent observations and serializes the write phase. Delegate only when bounded task value exceeds context/coordination overhead; every worker needs scoped inputs and a clear result contract, and failed/canceled workers must not silently become successful results.
How should an agent protect tools from prompt injection?
Short answer: Treat retrieved instructions and model-proposed actions as untrusted input, then enforce access and action limits outside the model. Narrow tools, resource checks, isolation, budgets, and necessary approval reduce the damage a misleading document can cause; a warning in the prompt alone is insufficient.
Detailed explanation:
🧠 Hit point: Treat model/tool output as untrusted proposals; enforce identity, resource authorization, allowlists, sandboxing, budgets, and approval outside the model.
Example: A read-only search worker cannot invoke shell or network tools, even if a repository file instructs it to. Avoid: relying on a “do not follow injection” prompt alone. Detail: Agent security and trust boundaries.
🟦 Illustrative example:
tool_policy:
principal: authenticated_reviewer
allowed_tools: [search_sources, read_scoped_file]
allowed_root: reviewed_workspace
shell_execution: denied
outbound_write: denied
imported_instructions: treat_as_untrusted_data
enforcement: host_validates_tool_name_arguments_and_resource_scope🧠 This is an illustrative host policy, not a product command or executable permission file. Enforcement happens before a tool executes, including canonical-path/resource checks; a source file asking for shell access cannot widen the policy. Model output remains a proposal even when it is well-formed JSON.
How can you reduce AI token cost while preserving answer quality?
Short answer: Provide relevant source material, remove unnecessary duplication, and limit repeated tool calls and oversized output. Compare correctness and cost for accepted results after those changes, because a shorter prompt is not an improvement if it removes the evidence needed to answer reliably.
Detailed explanation:
🧠 Hit point: Retrieve targeted source, avoid duplicate context, bound output/tool loops, and measure cost per accepted result alongside correctness.
Example: Search Swift symbols then read five relevant files and tests rather than sending the full repository. Avoid: claiming fixed savings without tokenizer and task assumptions. Detail: Token budgets and estimates.
🟦 Illustrative example:
task: repair_one_swift_compile_error
context_plan:
- locate_symbol_and_diagnostic
- read_relevant_definition_and_callers
- include_applicable_instructions_and_test
- expand_only_if_evidence_is_missing
measure:
- accepted_fix_and_test_result
- total_input_cached_and_output_tokens
- retries_review_and_end_to_end_cost🧠 This proposed plan narrows context around a concrete repair while preserving rules and validation. Compare measured accepted-result cost and quality to a baseline; a smaller prompt that causes more retries or misses a caller can be more expensive overall.
How should an application choose and route between AI models?
Short answer: Choose routes using task difficulty, response time, privacy, tool reliability, and results from representative evaluations. A cheaper initial model may cost more after retries or review, so evaluate the whole route and define when to escalate or stop within the available budget.
Detailed explanation:
🧠 Hit point: Route by task complexity, latency, tool reliability, privacy, context need, and evaluated end-to-end success—not model hype.
Example: Use a fast extraction route only when schema/accuracy checks pass; escalate complex security review within budget. Avoid: assuming the cheapest model is cheapest after retries. Detail: Model selection and routing.
🟦 Illustrative example:
routing_contract:
policy_check: reject_routes_that_violate_data_scope
default: evaluated_extraction_candidate
acceptance: schema_valid_and_source_evidence_matches
on_failed_acceptance: one_bounded_repair_then_permitted_escalation
high_impact_review: named_human_owner
record:
- exact_model_and_configuration
- tool_permissions_and_fallback
- accepted_result_and_total_usage🧠 This policy sketch routes using observable acceptance and policy checks, not self-reported confidence. Candidate identities and budgets must be supplied from current permitted configuration; evaluate the full route, including repairs and fallback, before claiming savings or quality.
What evidence shows that an AI feature is ready for production?
Short answer: Test representative and adversarial cases against explicit quality, tool-use, safety, latency, and cost requirements. Add monitoring, a gradual rollout, and a way to reverse a bad change, because a convincing demonstration does not show how the feature behaves across real users and failures.
Detailed explanation:
🧠 Hit point: Use versioned evaluation cases, retrieval/tool/safety checks, traces and usage budgets, privacy review, rollout, and rollback criteria.
Example: Canary a prompt change on an adversarial eval set and monitor groundedness, tool correctness, latency, and repair rate. Avoid: validating only with a hand-picked demo. Detail: AI system quality.
🟦 Illustrative example:
release_contract:
version: prompt_retrieval_model_tools_and_policy_versions
held_out_cases:
- grounded_answer_with_citation
- missing_evidence
- unauthorized_document
- malicious_instruction_in_tool_result
- timeout_and_cancellation
owner: feature_release_owner
rollout: bounded_canary_with_review
rollback: restore_previous_verified_configuration🧠 This proposed release contract exercises failure and trust boundaries as well as a successful answer. Gates need measured thresholds chosen for the product and a tested rollback path; a valid schema or a convincing demo alone does not establish groundedness, authorization, or operational readiness.
Staff / Principal system design routes
Use the corresponding complete case study rather than memorizing a single architecture:
- Design a secure banking mobile application → Banking case
- Design an enterprise platform for several apps/teams → Enterprise platform case
- Design an AI chat backend → AI chat case
- Design an AI coding orchestrator → Coding orchestrator case
- Design a secure knowledge assistant → RAG case
- Design a scalable mobile API → Distributed backend case
Coding exercises — prompts only
Try these before looking at the separate solution section. State assumptions and edge cases before coding.
Exercise 1: Idempotent API command
Design a TypeScript handler contract for POST /payments. Two requests with the same principal and idempotency key must produce one logical payment result. Explain persistence, concurrent duplicates, validation, and timeout recovery.
Exercise 2: Bounded DAG scheduling
Given tasks with dependency IDs and a maximum worker count, describe how to run ready independent tasks, stop on cancellation, and prevent a dependent task from running after a prerequisite fails.
Exercise 3: Swift feature boundary
Define a Swift protocol for loading an account asynchronously, a domain model, and one test double. Explain which layer owns DTO mapping and how cancellation/errors reach presentation state.
Exercise 4: Code review challenge — unsafe debit endpoint
Review this sketch. Identify authorization, consistency, idempotency, validation, logging, and failure-handling risks. Give findings by severity before proposing a patch.
app.post("/accounts/:id/debit", async (request, reply) => {
const amount = Number(request.body.amount);
await db.query("UPDATE accounts SET balance = balance - " + amount
+ " WHERE id = '" + request.params.id + "'");
request.log.info({ request }, "debit completed");
return reply.send({ ok: true });
});Exercise 5: Architecture tradeoff exercise — three mobile teams
A single iOS application has three feature teams, a slow full build, frequent merge conflicts, and one shared API module. A proposal recommends immediate microservices and a new cross-platform UI. State the evidence and constraints you would gather, the smallest experiment, success measures, and the conditions that would justify either proposal.
Coding exercise solutions
Solution 1: Idempotent API command
This sketch is framework-neutral and omits payment-domain and PCI/regulatory concerns. Use a unique database constraint on (principal_id, idempotency_key) and store a request fingerprint plus durable status/result. Reject reuse of the same key with a different payload. Wrap the idempotency record and domain transaction in a consistency boundary; publish side effects with an outbox.
type PaymentInput = { accountId: string; amountCents: number; currency: string };
type PaymentResult = { paymentId: string; status: "accepted" | "rejected" };
async function createPayment(
principalId: string,
key: string,
input: PaymentInput,
): Promise<PaymentResult> {
validatePayment(input);
const fingerprint = hashCanonical(input);
return database.transaction(async tx => {
const existing = await tx.idempotency.findForUpdate(principalId, key);
if (existing) {
if (existing.fingerprint !== fingerprint) throw new Error("Key reused with different request");
return existing.result;
}
await authorizeAccount(tx, principalId, input.accountId);
const result = await ledger.acceptPayment(tx, input);
await tx.idempotency.insert({ principalId, key, fingerprint, result });
await tx.outbox.insert({ type: "PaymentAccepted", payload: { paymentId: result.paymentId } });
return result;
});
}Concurrency requires a unique constraint and a defined conflict/re-read path; application-level “check then insert” alone races. Retain records long enough for the retry window. Add status lookup, response schema validation, audit, rate limit, and tests for simultaneous duplicate requests and mismatched payloads.
Solution 2: Bounded DAG scheduling
Validate the graph first: unique IDs, known dependencies, no cycles. Keep states pending/running/succeeded/failed/cancelled, admit only nodes whose dependencies all succeeded, cap active work, and cancel/skip dependents after failure. The actual implementation needs durable state and race-safe transitions for multiple scheduler processes.
type WorkItem = { id: string; dependsOn: string[]; run: (signal: AbortSignal) => Promise<void> };
async function executeDag(items: WorkItem[], maxWorkers: number, signal: AbortSignal) {
type State = "pending" | "running" | "succeeded" | "failed" | "cancelled";
const state = new Map<string, State>(items.map(item => [item.id, "pending"]));
const byId = new Map(items.map(item => [item.id, item]));
validateAcyclicGraph(items, byId);
while ([...state.values()].some(value => value === "pending" || value === "running")) {
if (signal.aborted) throw new Error("Cancelled");
const active = [...state.values()].filter(value => value === "running").length;
const ready = items.filter(item => state.get(item.id) === "pending"
&& item.dependsOn.every(id => state.get(id) === "succeeded"));
const slots = Math.max(0, maxWorkers - active);
if (ready.length === 0 && active === 0) throw new Error("Blocked or cyclic graph");
await Promise.all(ready.slice(0, slots).map(async item => {
state.set(item.id, "running");
try { await item.run(signal); state.set(item.id, "succeeded"); }
catch (error) { state.set(item.id, "failed"); throw error; }
}));
}
}For production, capture individual failures instead of losing the state map when Promise.all rejects; mark descendants blocked, propagate cancellation to running work, persist state/audit, enforce per-task timeouts, and ensure every task is idempotent or can be reconciled before retry.
Solution 3: Swift feature boundary
struct Account: Equatable, Sendable {
let id: String
let balanceCents: Int
}
protocol AccountLoading: Sendable {
func load(id: String) async throws -> Account
}
struct AccountScreenModel {
let loader: any AccountLoading
func refresh(id: String) async throws -> Account {
try Task.checkCancellation()
return try await loader.load(id: id)
}
}
struct StubAccountLoader: AccountLoading {
let result: Account
func load(id: String) async throws -> Account { result }
}The API adapter owns transport decoding and maps its DTO into the domain Account; presentation maps loading/success/failure into view state. Propagate cancellation instead of converting it to an ordinary user error. Sendable constraints should be checked against the app's selected Swift concurrency mode and SDK declarations.
Solution 4: Code review challenge — findings
- Critical: no authentication or object-level authorization is visible. Verify the principal and that it may debit this specific account.
- Critical: string concatenation allows SQL injection. Use a parameterized query and schema-validated amount/currency.
- High: the client-supplied account ID and amount do not prove authority or sufficient funds. Enforce business invariants in one transaction and use integer minor units/explicit currency rules.
- High: retries may debit twice. Require a principal-scoped idempotency key with a unique durable record and defined duplicate behavior.
- High: the log serializes the request object, potentially recording credentials and personal data. Log a stable event name and non-sensitive trace ID only.
- High: the handler returns success without checking affected rows, committed transaction result, or downstream state. Map domain outcomes into explicit response states.
Architecture tradeoff: Keep this logic in the service/domain boundary with a repository transaction; do not move all logic into generic middleware. See API security and distributed reliability.
Solution 5: Architecture tradeoff — decision path
First measure clean/incremental build time, target graph, CI queue, ownership conflicts, API churn, release cadence, and runtime bottlenecks. Identify whether the issue is compile dependency fan-out, shared module changes, or service deployment coupling. Pilot an acyclic feature module with a narrow public API and one team owner; record build time, cross-team edits, defects, and integration delay. Keep the backend modular monolith unless independent deploy/scale or domain ownership demonstrably justifies service distribution. Compare native Swift UI, Kotlin Multiplatform domain sharing, Flutter, and React Native against UX/accessibility needs, platform API use, team expertise, release ownership, and exit/migration cost. Reverse the proposal only when measured value exceeds operational and migration cost; no framework is inherently correct.
Short answer framework
- Define the problem in one sentence.
- State ownership and main tradeoff.
- Give one concrete example.
- Name a failure mode and how you verify it.
- Say what evidence would change your decision.
Keep the first answer under a minute, then expand when the interviewer asks. For hands-on interview prep and existing Senior iOS questions, continue to Interview Paths.
