← All writing

Technical note · 2026-09-23

60 frontend and AI application interview questions: answers and pitfalls

A practical review of JavaScript, TypeScript, Vue and React, with an emphasis on RAG, agents, MCP, streaming interfaces, reliability, evaluation and explaining real project work.

Exploration · Principles and possible approaches inspired by a project context.

  • Interviews
  • Frontend
  • TypeScript
  • React
  • Vue
  • AI
  • RAG
  • Agents

This guide is for developers preparing for frontend or AI application roles. Questions 1–25 review frontend foundations, 26–55 focus on AI, and the final five connect them to system design, debugging, testing and project discussions.

“Common questions” describes an editorial selection, not a measured ranking of hiring data. The focus is application engineering, rather than the mathematics, distributed training and CUDA work expected in model research roles. Sources were checked on September 23, 2026; confirm APIs against the versions used in your project.

Practice a one-minute answer, then add an example and a limitation. Teaching scenarios are not personal accomplishments or evidence of production scale.

Contents

JavaScript and TypeScript

1. How do var, let and const differ?

var is primarily function-scoped and initialized to undefined during declaration instantiation. let and const are block-scoped and cannot be accessed in their temporal dead zone. const prevents reassignment of a binding; it does not recursively freeze an object.

Arguments are passed by value. For objects, that value is a reference: mutating a property can affect the shared object, but reassigning the parameter does not replace the caller’s variable. See MDN grammar and types.

2. What is a closure, and how does it relate to this?

A closure connects a function to its lexical environment, allowing access after the outer function returns. It does not automatically copy variables into an immutable snapshot. Closures are useful for factories and debounce; retaining unnecessary references can cause memory problems.

Ordinary functions usually get this from how they are called. Arrow functions use the enclosing lexical this. Passing an extracted method can lose its receiver; a wrapper or bind makes it explicit. See closures and this.

3. How do prototypes, class and new work?

Property lookup checks the object and then its prototype chain until null. Classes use this mechanism but add semantics such as strict mode and private fields.

Conceptually, new creates an object, connects its prototype, executes the constructor with that object as this, and selects the resulting instance. An explicitly returned object can replace the newly created one. Distinguish a constructor’s prototype property from an instance’s internal prototype. See MDN prototype chains.

4. How do tasks and microtasks determine execution order?

In a typical browser example, synchronous code finishes, the microtask checkpoint drains queued microtasks, and the event loop continues to subsequent tasks and rendering opportunities. Promise reactions and queueMicrotask use microtasks; timers schedule tasks.

console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
queueMicrotask(() => console.log('D'));
console.log('E');
// A E C D B

A zero-delay timer is not immediate. Continuously scheduling microtasks can delay rendering. Do not apply this simplified browser explanation to every Node.js phase. See MDN execution model.

5. How do async/await and Promise combinators work?

An async function returns a Promise. await suspends that function’s continuation, not the entire thread. A Promise executor runs synchronously; settlement handlers run asynchronously.

Method Result
all Needs every success; rejects when an input rejects
allSettled Collects each success or failure
race Adopts the first settlement, successful or not
any Takes the first fulfillment; rejects with AggregateError if all reject

They neither cancel remaining work nor limit already-started requests. Empty all and allSettled fulfill, empty any rejects, and empty race stays pending. See MDN Promise.

6. How do shallow copying, deep copying and immutable updates differ?

Spread and Object.assign copy one level. Nested references can remain shared. structuredClone supports many data structures and cycles, but not functions or DOM nodes, and does not preserve arbitrary custom prototype semantics. JSON round-tripping changes or loses some types.

For React updates, copy the changed path and retain unrelated references. Deep-cloning a large state tree for every edit adds work and destroys useful reference stability. See MDN structuredClone.

7. When should you debounce or throttle?

Debounce consolidates bursts after a quiet interval; throttle limits execution frequency. Specify leading/trailing behavior and cancellation. This trailing-only debounce keeps the receiver and latest arguments:

function debounce(fn, delay) {
  let timer;
  function wrapped(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      timer = undefined;
      fn.apply(this, args);
    }, delay);
  }
  wrapped.cancel = () => {
    clearTimeout(timer);
    timer = undefined;
  };
  return wrapped;
}

Debouncing does not prevent stale search responses from overwriting new results; question 25 covers ownership. This example does not define Promise return semantics for consolidated calls.

8. How do any, unknown, never and generics differ?

any bypasses much checking; unknown requires narrowing before use; never represents an impossible value and supports exhaustive checks. Generics preserve relationships between types; constraints and keyof restrict valid operations.

Interfaces describe extensible object contracts and support declaration merging. Type aliases also directly express unions, tuples and mapped types. Both cover many object use cases.

Neither as User nor request<User>() validates network JSON. Parse untrusted data with runtime checks or a schema, including AI output. See narrowing and generics.

Vue and React

9. How does Vue 3 reactivity work?

Reactive objects primarily use Proxy-based interception to track reads and trigger relevant updates. Refs expose values through .value; they can wrap primitives or objects, with objects normally made deeply reactive. Vue 2 relied primarily on property getters/setters and had different limitations around additions and deletions.

Destructuring a primitive property from reactive disconnects that local binding from the property. Keep object access or use toRef/toRefs. See Vue reactivity fundamentals.

10. When should you use computed, watch or watchEffect?

Use computed properties for pure derived values, watchers for effects with explicit sources, and watchEffect for effects whose synchronous reads determine dependencies.

An async watchEffect tracks reads before its first await, not every later read. Tie request cancellation and subscriptions to cleanup, and consider the traversal cost of deeply watching large objects. Avoid fetching inside computed getters. See Vue watchers.

11. What does nextTick guarantee?

Vue batches DOM updates. await nextTick() waits for pending Vue DOM updates to flush, allowing subsequent DOM measurements. It does not guarantee that images loaded, the browser painted, or network requests finished.

On teardown, release manually created listeners, timers, subscriptions and requests. Distinguish framework-managed reactive effects from resources created outside that lifecycle. See Vue nextTick.

12. Why does a React setter not change the value I immediately read?

Each render has a state snapshot. A setter requests an update rather than rewriting variables inside the current closure. Use updater functions when updates depend on previous queued values.

// One event handler, using the same render snapshot:
setCount(count + 1);
setCount(count + 1); // Usually adds 1 in total.

// A separate alternative:
setCount(value => value + 1);
setCount(value => value + 1); // Adds 2.

Explain snapshots and queues instead of merely calling setters “asynchronous.” Avoid mutating an existing state object and returning the same reference. See React state snapshots.

13. What belongs in useEffect, and how do you avoid stale closures?

Effects synchronize with external systems. Derive display values during rendering; put actions tied to a specific user event in its handler. Dependencies should reflect reactive values actually read, and subscriptions need cleanup. Functional setters help when updating from previous state.

Development Strict Mode can run an extra setup/cleanup cycle. Make them symmetrical instead of hiding the issue with a “ran once” flag. See unnecessary effects and effect synchronization.

14. Should every component use memo, useMemo and useCallback?

No. They can avoid certain renders, repeated calculations or changing function identities. They are performance tools, not correctness guarantees. Profile first and check whether changing references defeat caching.

Comparison and maintenance also cost something; local state or consumed context can still cause updates. Projects using React Compiler should consider its automatic optimizations rather than adding manual caching mechanically. See React useMemo.

15. Why do lists need stable keys?

Keys identify siblings so the framework can match elements and component state. Inserting or reordering a list changes indices, potentially attaching an old input’s state to the wrong record.

Prefer stable business IDs. Index keys are less risky for static lists without identity-sensitive state. Random keys force recreation. Changing a React key can deliberately reset a subtree. See preserving and resetting state.

16. How do you separate local, global and server state?

Keep drafts and dialog state near their consumers. Share cross-area state when necessary. Treat remote records, pagination, invalidation and request deduplication as server-state concerns. Define ownership, update entry points and invalidation rules.

For an editable table, separate query parameters, server snapshots, selections and unsaved edits. Store edits by stable record ID so sorting and virtualization preserve ownership. One giant global store increases coupling.

Browsers, networking and engineering

17. What happens after entering a URL? What are layout and paint?

A typical navigation includes URL interpretation, cache checks, DNS, connection setup, HTTP exchange, parsing, script execution, layout, paint and compositing. Caches and reused connections change the path. HTTP/1.1 and HTTP/2 typically use TCP; HTTP/3 uses QUIC.

Layout computes geometry; paint creates visual content; compositing combines layers. Alternating style writes with geometry reads can force synchronous layout. Batch work and reduce unnecessary nodes; transforms are not universally free. See MDN browser internals.

18. How do Flexbox, Grid, BFC and responsive design fit together?

Flexbox mainly distributes space along one direction; Grid coordinates rows and columns. A block formatting context isolates certain block-layout interactions and can contain floats. display: flow-root establishes one explicitly without introducing clipping just to clear floats.

For overflowing flex/grid children, inspect automatic minimum sizes, min-width: 0, wrapping and local scrolling. Responsive verification also includes keyboard access, focus, semantic controls and touch targets. See MDN BFC.

19. How do freshness and cache revalidation differ?

Fresh responses can be reused according to directives such as max-age. Stale responses can be validated with ETag/If-None-Match or Last-Modified; an unchanged resource can yield 304.

no-cache allows storage but requires validation before reuse; no-store prohibits storage of that response. Hashed assets suit long caching, while entry HTML needs timely updates. Removing old chunks too early can break open pages. Separate public and identity-dependent cache policies. See MDN HTTP caching.

20. Is CORS authentication?

No. CORS controls browser cross-origin response access; origin includes scheme, host and port. Some methods, headers or content types require an OPTIONS preflight. Credentialed responses require appropriate credential and origin configuration, not a wildcard origin.

Non-browser clients do not enforce browser CORS rules. A blocked response does not always mean the server received no request. no-cors generally gives an unreadable opaque response, not a fix for a JSON API. See MDN CORS.

21. How do XSS, CSRF and credential storage relate?

XSS introduces untrusted content into executable contexts; use context-aware encoding, appropriate sanitization and layered defenses. CSRF exploits automatically attached credentials; consider SameSite, anti-CSRF tokens and origin checks.

HttpOnly restricts script access to a cookie, but malicious scripts may still issue requests. localStorage is readable by same-origin scripts and must not contain server-side model keys. Treat generated Markdown, HTML and links as untrusted too. See OWASP on XSS and CSRF.

22. Which performance metrics should guide optimization?

Separate loading, responsiveness and visual stability from API/model latency. Current Core Web Vitals are LCP, INP and CLS, with good thresholds of at most 2.5 seconds, 200 milliseconds and 0.1, assessed at the 75th percentile and segmented by device.

Investigate critical resources for LCP, long tasks for INP and unexpected layout changes for CLS. Lab tests help reproduce problems; field data verifies user impact. AI interfaces also need time to useful content and task completion. See Web Vitals.

23. What do Vite, lazy loading and tree shaking each solve?

Development transformation and module updates serve a different purpose from production bundling. Vite’s underlying tooling changes across versions, so identify the version actually used.

Dynamic imports introduce loading boundaries. Tree shaking removes statically identifiable unused code, subject to exports and side effects. Splitting adds requests and failure paths; not every critical dependency should be deferred. Legacy WebViews require separate checks for syntax, Web APIs and dependency compatibility. See Vite features.

24. How do CSR, SSR, SSG and hydration compare?

CSR primarily creates the UI in the browser, SSR produces HTML per request, and SSG produces it at build time. Hydration attaches client behavior to existing HTML and expects matching initial output.

Articles suit static generation, personalized pages may need SSR, and interactive regions may use client rendering. Random values, time and browser-only state can cause hydration mismatches. SSR still requires attention to script size and server cost. See React hydrateRoot.

25. How do you stop stale requests from overwriting current state?

Assign a generation to each load; only the current generation may update data, errors or loading. Abort supported operations to reduce wasted work, but retain ownership checks for ignored cancellation and later transformations.

A→B→A and repeated refreshes defeat ID-only checks. Stale finally handlers must not stop a newer loading indicator. Keep generations local to competing requests. Fetch usually fulfills on HTTP errors, so check response.ok. See MDN Fetch and the request-race article.

Models, RAG and context

26. What are tokens, attention and the KV cache?

A tokenizer converts text to tokens; the model predicts subsequent tokens from context. Tokens are not synonymous with words or characters. Attention connects positions by content, with positional information supplying sequence structure.

Common autoregressive inference has a prefill stage for input and a decode stage for generation. A KV cache reuses previous key/value computations while consuming memory. Longer context is not free, and this is different from caching complete answers. See the Transformer paper and Hugging Face inference optimization.

27. Do temperature and top_p control factual accuracy?

For generation modes that support them, temperature changes distribution sharpness, while top_p limits sampling to a cumulative probability mass. Support varies across models and modes.

Low temperature guarantees neither factual correctness nor identical responses. Better grounding, constrained inference, validation and evaluation address different causes of errors. Ask for clarification or acknowledge insufficient evidence when appropriate. Incorrect retrieval can still produce confident incorrect answers. See Hugging Face generation configuration.

28. What makes a prompt maintainable?

Specify the goal, permitted evidence, output format, success conditions and boundaries. Include representative examples when useful. Separate application instructions from user input and retrieved material, and identify sources explicitly.

Version prompts and compare changes on the same evaluation cases, including failure types, cost and latency. A few appealing responses are insufficient evidence. Prompts cannot replace authorization or input validation. See OpenAI prompting.

29. How do JSON mode, structured output and business validation differ?

JSON mode mainly constrains syntactic validity. Structured output constrains a supported schema on compatible models and interfaces. Neither proves that an order exists, an amount is correct or a user has permission.

Handle refusal, truncation and transport failure before consuming a result, then validate both structure and business rules. Supported schema subsets and request fields vary by API. See OpenAI Structured Outputs.

30. Does function calling mean the model executes code?

Usually the model proposes a tool and arguments; the application validates and executes code, correlates the result to the call, and returns it for further generation. A proposed call is not a successful action.

For order lookup, derive identity from the verified session and check access to the specific order. Model-generated identity or role fields cannot authorize access. Wait for complete arguments and distinguish timeouts, business failures and success. See OpenAI function calling.

31. What is the complete RAG pipeline?

Retrieval-augmented generation finds evidence before asking a model to answer. Ingestion includes collection, cleaning, chunking, indexing and versioning. Serving includes identity and scope checks, retrieval, optional reranking, context assembly, generation and citation validation.

Documents → clean/chunk → index with sources, versions and permissions
Question → authenticate → retrieve/rerank → evidence → generated answer

                                             check supporting citations

RAG does not require a vector database. Small collections with explicit names may work with keyword retrieval; evaluate against actual questions. See LangChain retrieval.

32. What is the right chunk size and overlap?

There is no universal number. Small chunks can separate a conclusion from its conditions; large chunks add noise and context cost. Prefer document structure, then enforce token budgets.

Overlap can preserve boundary context but increases storage and duplicate retrieval. Keep table headers, units, applicability and versions with relevant content. Choose settings using representative retrieval and answer evaluations. See LangChain text splitters.

33. How do embeddings, hybrid search and reranking differ?

Embeddings encode content as vectors; similarity retrieves candidates, not truth probabilities. Keywords often help with IDs, names and error codes. Hybrid retrieval combines complementary results; rank-based fusion such as RRF avoids assuming unrelated scores share a scale.

Reranking applies a more detailed relevance assessment to a smaller candidate set, adding latency. Query and document vectors must remain compatible when changing embedding models or dimensions, usually requiring reindexing. See OpenAI retrieval and Elasticsearch RRF.

34. How do you diagnose weak RAG answers and enforce access?

Trace the actual evidence: missing ingestion, failed retrieval, filtering/truncation, or incorrect generation despite sufficient context. Fix the stage responsible instead of repeatedly changing the prompt.

Filter unauthorized candidates before they reach the model, application logs or client; isolate caches by access scope. Citation IDs must refer to authorized evidence used in that run, and the cited passage must support the claim. A link alone proves little. These are application design checks informed by OWASP vector and embedding risks.

35. When should you use prompts, RAG, fine-tuning or LoRA?

Problem First option to evaluate
Unclear task or output format Instructions, examples and structured output
Fresh/private knowledge and traceable evidence RAG with permissions and updates
Stable task, good examples, desired behavior changes Fine-tuning
Reduce trainable parameters and training resource needs Suitable parameter-efficient methods such as LoRA

LoRA trains low-rank updates alongside frozen base weights. It is not lossless knowledge-base compression. Fine-tuning does not ensure fresh knowledge or enforce document permissions; it can complement RAG. See the LoRA paper.

36. How do context windows and memory differ?

The context window limits one inference input/output budget. Short-term memory tracks a conversation’s state; long-term memory retains useful information across conversations. Stored history need not all enter every prompt.

Combine recent messages, reliable summaries and selective retrieval. Summaries can lose conditions, so preserve important constraints, tool status and sources. Durable memories need ownership, correction, deletion and expiry policies. Do not promote model guesses into established facts. See LangGraph persistence.

Agents and MCP

37. How do workflows and agents differ?

A workflow primarily follows program-defined paths. An agent lets a model participate in choosing subsequent actions within tools, state and limits. A fixed retrieve-then-answer process need not be autonomous.

Prefer deterministic orchestration when steps are known or failures are expensive, adding models where interpretation is useful. Agents address less predictable paths but add cost and verification complexity. See LangGraph workflows and agents.

38. What are LangGraph state, nodes, edges and reducers?

State carries shared workflow data; nodes return updates; edges route execution; reducers determine how field updates merge. Parallel writers need explicit overwrite, append or ID-based merge semantics.

Checkpoints support continuation and recovery, but are not transaction logs for external services. Recovery can repeat a tool, so writes still require idempotency. An in-memory checkpointer does not survive process restart. See Graph API and persistence.

39. How do you prevent endless or expensive agent loops?

Enforce step, time, token/cost, tool-timeout and consecutive-failure budgets in the runtime. Define completed, partial, failed and awaiting-input outcomes. Verify actual results instead of accepting the model’s completion claim.

Detect repeated normalized calls that produce no new information, while giving legitimate polling its own limits. Share budgets across retries and child tasks. See the worked example in agent loop control.

40. Why are multiple agents not always better?

They help when work can be independently specified, executed and checked. Frequent coordination and shared mutable state can instead increase latency and misunderstandings.

Define inputs, output schemas, required evidence, budgets and the final integrator. Parallel reads are easier to coordinate than concurrent changes to the same record. Compare quality, cost and duration on the same evaluation set before assuming decomposition helps.

41. How does MCP differ from function calling?

Function calling concerns structured tool proposals from a model. MCP standardizes interoperability between AI applications and external context or tool services. A host manages the application, clients connect to servers, and servers expose tools, resources and prompts.

The application can discover MCP tools and offer selected capabilities to a model. MCP is neither model intelligence nor a requirement for autonomous agents. Common transports include local stdio and remote Streamable HTTP; version-specific discovery and authorization details must be checked. See MCP architecture.

42. Who secures an MCP integration?

Applications and servers retain their own responsibilities: validate service identity, restrict capabilities, verify token audience and scope, and bind calls to real user permissions. Tool descriptions and outputs are untrusted content.

A local stdio server is an executable process needing constrained file and system access. Remote integration also needs protection against incorrect token forwarding and arbitrary outbound destinations. Installing a server does not justify granting it all credentials. See MCP security practices.

Streaming AI interfaces

43. Why use SSE, and when use WebSocket?

SSE suits server-to-client event delivery; WebSocket suits persistent bidirectional communication. Text chat often works with an HTTP request and streaming response. Realtime audio and control require a separate latency and protocol assessment.

Native browser EventSource does not expose arbitrary POST bodies or custom request headers. Fetch can consume an SSE-formatted response when those are needed. SSE framing is not synonymous with using EventSource. See MDN SSE.

44. Why can’t each network chunk be parsed as JSON?

Transport chunks do not correspond to messages. UTF-8 characters and events may span chunks, while one chunk may contain several events.

Decode incrementally, retain incomplete data, assemble events according to SSE rules, then parse event payloads. Handle line-ending variants, multiline data, comments and termination. Prefer a maintained parser; test arbitrary byte splits rather than one-write-per-message fixtures. See SSE framing.

45. How should streaming UI state and rendering work?

Separate conversation, message and run IDs. Model waiting, streaming, tool execution, completion, failure and cancellation explicitly. This is an application-state sketch, not a vendor event schema:

idle → submitting → streaming ↔ tool-running → completed
                       ↓              ↓
                   cancelled        failed

Batch text updates, handle incomplete Markdown, and follow output only while the reader remains near the bottom. Retain partial text on failure and mark it incomplete. Distinguish deltas from terminal events; see OpenAI streaming and chat scroll anchors.

46. Does stopping or refreshing the browser stop backend work?

Not necessarily. Cancellation must propagate through the application and provider, and completed external effects do not roll back because a connection closes.

Recover using a run ID and authoritative status before resubscribing or starting another run. Replay requires persisted events and ordering information. Never automatically rerun a side-effecting tool chain just because the browser lost its stream. See stream event boundaries.

AI safety, cost and evaluation

47. What is prompt injection, and why isn’t a warning prompt enough?

Injection makes lower-trust input act like instructions, including malicious content in documents, web pages, images or tool results. It can redirect behavior or attempt data exfiltration.

Separate untrusted material, restrict tools and outbound destinations, validate arguments, isolate sensitive data and require appropriate confirmation for high-risk actions. Prompts and detectors are only layers; neither RAG nor fine-tuning eliminates this risk. See OWASP prompt injection.

48. What checks belong before persisting model output?

Check structure, field validity, business rules, ownership, permissions and current record state. A valid order ID need not belong to the user; a numeric amount need not have valid precision or totals.

Calculate critical amounts deterministically, use version checks against stale writes, and use parameterized or constrained queries rather than executing generated SQL. HTML, commands and paths need their own safe handling. See OWASP improper output handling.

49. Can a browser hold the model API key?

Do not ship long-lived server secrets in bundles, browser storage or public configuration. Normally an authenticated server applies quotas and calls the provider. Provider-supported short-lived, restricted client credentials are a separate mechanism for suitable realtime cases.

Derive identity from trusted sessions, not request-body roles. Keeping a key behind an unauthenticated public proxy does not prevent abuse. Credentials, user budgets, tool permissions and data visibility need separate controls.

50. How should retries, 429 responses and tool timeouts work?

Distinguish temporary failures from invalid inputs, access failures and exhausted quotas. Bound retries and total time, use jittered backoff, respect provider guidance, and avoid multiplying SDK and application retries.

A timeout does not prove non-execution. Writes need stable idempotency keys, uniqueness constraints and result lookup. Release database transactions and connections before model/external waits; persist results in short transactions and update related caches after commit. See OpenAI rate limits and tool retry contracts.

51. How do you reduce latency and cost? Is prompt caching answer caching?

Measure queueing, retrieval, first token, total generation, tools and rendering separately. Reduce unnecessary calls and output, parallelize independent work, and use code for deterministic tasks. Streaming improves perceived waiting without necessarily reducing total duration.

Prompt caching reuses prefix computation; answer caching reuses results and must respect permissions, versions and expiry. Measure total cost per successful task, including retries and infrastructure. See OpenAI latency optimization and prompt caching.

52. How do you prove an AI feature improved?

Define business success and version a representative evaluation set, including ordinary, edge, unanswerable, unauthorized and adversarial cases. Separate retrieval, groundedness, tool selection, argument validity and actual business outcomes from latency and cost.

Use deterministic assertions where possible. Calibrate model judges against human review and clear rubrics. Compare identical samples, inspect failures and tail latency, then validate through staged traffic. A fluent success message is not proof an order was created. See OpenAI evaluation practices.

53. How do you select cloud or open-weight models?

List quality, tool/schema support, modalities, context, latency, concurrency, data requirements and budget. Test candidates on your tasks; generic benchmarks only help form a shortlist.

Separate framework licensing, weight availability, commercial permissions, inference cost and operations. Self-hosting requires memory, throughput planning, monitoring and upgrades. Quantization tradeoffs need measurement on target hardware. Model routing and fallback must preserve tool permissions and output contracts.

54. What makes multimodal inputs difficult?

Validate file type, size, page count or duration and access before selecting text extraction, OCR or native multimodal processing. Scans, tables, rotation, low resolution and mixed languages can produce errors. Preserve page numbers or timestamps for verification.

Document instructions remain untrusted content. Offer correction for important extracted fields and bound resource use. Accepting a file does not prove every page was processed or correctly understood.

55. What should AI observability record?

Correlate retrieval, model calls, tools and business results using request/run IDs. Record relevant versions, timing, usage, errors, retries, cancellation and final status so failures can be localized.

Minimize and redact sensitive content, restrict access, and define retention. Never log API keys or token-bearing URLs. Do not send full private contexts to public analytics just for convenience. Verify provider and deployment data policies rather than inferring them from API usage.

System design, coding and project discussions

56. How would you design an enterprise knowledge assistant?

Clarify users, sources, update frequency, permissions, concurrency targets and success criteria, then describe the chain:

Browser: questions, attachments, streaming, cancellation, recovery

Application: authentication → quotas → conversation/run state

Retrieval: permission filtering → candidates → reranking → sources

Model adapter: context budget → generation → schema/citation checks

Tools: argument/access checks → idempotent execution → verification

Persistence and observability: state, evidence, outcomes, cost

These are logical boundaries, not a requirement for six services. Start with read-only answers and citations. Add writes when justified, and represent long tasks independently of the browser connection.

57. Where do you start when “the AI assistant is broken”?

Collect reproduction steps, timing and a request ID. Check assets, request dispatch, authentication, application receipt, provider response, proxy buffering, parsing and persisted outcome.

A missing dynamic chunk may prevent the request from reaching the model at all. HTTP 200 followed by a broken stream is not task success. Establish impact and recent changes, then verify the repaired path. A generic UI error cannot identify the failing layer.

58. Are prompt tests enough?

No. Test deterministic schemas, permissions, budgets, idempotency and transitions; protocol byte splits, ordering and missing terminal events; UI switching, cancellation, reconnection, scrolling, keyboard use and narrow screens; and model quality with evaluations.

Include lost responses after successful writes, stale requests, refusals, invalid citations and process recovery. Mocks verify local behavior, not real model quality, provider cancellation or production networking. Those need integration and deployment checks.

59. How would you write a concurrency pool?

Document processing and batch embeddings need bounded in-flight work. Specify failure, ordering and cancellation semantics first. This version collects every outcome in input order, without retries or cancellation:

export async function runPool<T>(
  tasks: Array<() => Promise<T>>,
  concurrency: number,
): Promise<PromiseSettledResult<T>[]> {
  if (!Number.isInteger(concurrency) || concurrency < 1) {
    throw new RangeError('concurrency must be a positive integer');
  }
  const results: PromiseSettledResult<T>[] = new Array(tasks.length);
  let next = 0;

  async function worker() {
    while (next < tasks.length) {
      const index = next++;
      try {
        results[index] = {
          status: 'fulfilled', value: await tasks[index](),
        };
      } catch (reason) {
        results[index] = { status: 'rejected', reason };
      }
    }
  }

  await Promise.all(Array.from(
    { length: Math.min(concurrency, tasks.length) },
    () => worker(),
  ));
  return results;
}

Pass task factories, not already-started Promises. The cursor relies on uninterrupted synchronous execution within one JavaScript agent; it is not a distributed lock. Test peak concurrency, reordered completion, synchronous throws, rejection, empty input and invalid limits. Request/token rates need separate limiting. Also practice Map/Set deduplication, tree traversal, LRU, subscriptions and cyclic copying, explaining complexity.

60. How should you describe project challenges and AI-assisted development?

Explain the problem, constraints, choice, implementation, evidence and remaining limits. For request races, explain why cancellation and generations have different jobs, then show controlled-order tests and actual observations.

Identify where AI helped and how you checked interfaces, reviewed authority boundaries, tested failures and verified delivery. Be ready to defend alternatives and scaling limits. Without measurements, explain validation rather than inventing gains. Local checks, staging and production evidence are distinct; tutorial designs are not personal production achievements.

A revision sequence

Start with questions 25, 29–31, 34, 37–39, 43–52 and 56–60, then revisit your main framework and JavaScript foundations. Practice connecting the whole chain:

User action → UI state → request and authorization → retrieval/model/tools → validation → persistence and feedback → evidence of success.

Use three passes: one-minute oral answers, small runnable examples for weak areas, and a real-project discussion with follow-up questions about failure, retries, cancellation and permissions. Official links support technical and version checks; linked project articles expand the short answers into implementation discussions.