No matching questions found.
HTML
135 questions
Q1beginnerWhat is semantic HTML and why does it matter in interviews?
Semantic HTML uses elements whose names describe meaning—`<header>`, `<nav>`, `<main>`, `<article>`, `<footer>`—instead of anonymous `<div>` wrappers. Screen readers traverse landmarks, search engines infer structure, and teams read intent directly from markup. In React SPAs, semantic tags inside components prevent inaccessible 'div soup' and reduce reliance on ARIA patches.
Q2intermediateWhen would you choose `<article>` over `<section>`?
Use `<article>` for self-contained, independently distributable content—a blog post, product card, or comment that could appear in an RSS feed alone. Use `<section>` for thematic groupings within a page, such as a 'Features' block or 'Comments' wrapper that only makes sense in page context. If the content could be syndicated on its own, it is an article; if it is a chapter of a larger document, it is a section.
Q3beginner`<button>` vs `<a href>`: how do you decide?
`<a href>` navigates to a URL or in-page anchor—it has a destination. `<button>` triggers an action on the current page: submit a form, open a modal, toggle a menu. Screen readers announce them differently, and mixing them breaks keyboard expectations. Never use `<div onclick>` for either; it lacks focus management, default keyboard behavior, and a proper role.
Q4intermediateHow do you make a form accessible beyond adding labels?
Associate every control with a `<label>` via `for`/`id` or by wrapping the input. Group related fields in `<fieldset>` with `<legend>`. Use correct `type` attributes, `required` with a visible indicator, and link hints or errors through `aria-describedby`. Ensure tab order is logical, focus states are visible, and submission uses `<button type="submit">`. Custom widgets need keyboard support and ARIA only when native elements cannot express the behavior.
Q5intermediateWhat is ARIA's 'first rule' and what does it mean in practice?
The first rule of ARIA: do not use ARIA if a native HTML element already provides the needed semantics. A real `<button>` beats `<div role="button" tabindex="0">`. Reach for ARIA when building non-native patterns—tabs, comboboxes, live regions—but prefer upgrading markup first. Over-ARIA creates noisy, inconsistent experiences for assistive technology users.
Q6beginnerWhat does `<!DOCTYPE html>` do?
It is not an HTML element—it is a declaration that tells the browser to render in standards mode using the HTML5 parsing algorithm. Without a doctype, browsers may enter quirks mode, emulating legacy layout bugs. Always include it as the first line of every HTML document.
Q7intermediateWhat happens when the DOCTYPE is omitted?
The browser falls back to quirks mode, where box model calculations, percentage heights, and table layout may differ from standards mode. Cross-browser bugs become harder to reproduce. Always include `<!DOCTYPE html>` even in SPA shells served as a single `index.html`.
Q8advancedHTML4 transitional vs HTML5 doctype—what changed?
HTML5 uses the short `<!DOCTYPE html>` with no DTD URL. It triggers standards mode while simplifying authoring. Legacy XHTML or transitional doctypes are obsolete for new projects unless you maintain ancient CMS templates.
Q9beginnerName the key landmark elements and their roles.
`<header>` (banner), `<nav>` (navigation), `<main>` (primary content—one per page), `<aside>` (complementary), and `<footer>` (page or section footer). Landmarks let screen reader users jump directly to regions. Using them correctly is often the highest-impact accessibility win.
Q10intermediateWhy should `<main>` appear only once per page?
The main landmark identifies the primary content unique to the page. Multiple `<main>` elements confuse assistive tech about where primary reading should begin. Secondary repeated UI belongs in `<header>`, `<nav>`, or `<aside>`.
Q11intermediateHow do skip links improve accessibility?
A skip link is an early focusable anchor—often visually hidden until focused—that jumps keyboard users past repetitive navigation to `#main`. Without it, tabbing through large headers on every route change is painful. Implement with `<a href="#main" class="skip-link">Skip to content</a>`.
Q12intermediateWhich `<head>` tags matter for SEO and social sharing?
`<title>` (unique per route), `<meta name="description">`, canonical link, Open Graph tags (`og:title`, `og:image`), and structured data (JSON-LD). While SPAs hydrate content client-side, crawlers still consume the initial HTML shell—do not leave a generic title on every route.
Q13beginnerWhat is the purpose of `<meta charset="UTF-8">`?
It declares UTF-8 character encoding so the browser interprets multibyte characters correctly from the first bytes parsed. Place it early in `<head>`—within the first 1024 bytes—to avoid encoding sniffing errors that garble international text.
Q14beginnerExplain `<meta name="viewport" content="width=device-width, initial-scale=1">`.
It tells mobile browsers to use the device width as the layout viewport and sets initial zoom to 1. Without it, mobile browsers assume a ~980px desktop width and shrink the page. Essential for responsive design on phones and tablets.
Q15beginnerWhy is `name` required on form controls?
On submit, only controls with a `name` attribute appear in the form data payload (URL-encoded or multipart). Inputs without `name` are ignored. In React controlled components you still need `name` for native submission, autofill heuristics, and progressive enhancement.
Q16intermediateCompare HTML5 constraint validation vs JavaScript validation.
Built-in validation (`required`, `type="email"`, `pattern`, `min`, `max`) gives immediate browser UI and works without JS—good for progressive enhancement. JS validation adds async checks (username taken), custom messages, and UX polish. Best practice: use both—HTML for basics, JS for business rules—with accessible error announcements.
Q17advancedWhat is `novalidate` on a form and when use it?
It disables native browser validation UI so you can implement fully custom validation—common in design systems. You must then replicate accessibility: associate errors with fields, manage focus on failure, and do not rely on color alone.
Q18intermediateHow do you make `<video>` accessible?
Provide captions via `<track kind="captions">`, a transcript link, and keyboard-operable controls. Autoplay with sound harms accessibility and UX—prefer muted autoplay only when essential. Include `poster` for preview and textual alternatives describing non-decorative content.
Q19beginner`<img>` alt text best practices?
Decorative images: `alt=""` so screen readers skip them. Informative images: concise description of content/function. Functional images (icon buttons): describe the action, not the image. Never omit `alt` on meaningful images—that forces assistive tech to read filenames.
Q20advancedResponsive images: explain `srcset` and `sizes`.
`srcset` lists image URLs with width or density descriptors; `sizes` tells the browser how wide the image renders at each breakpoint. The browser picks an appropriate file, saving bandwidth. Example: `<img srcset="small.jpg 400w, large.jpg 800w" sizes="(max-width:600px) 100vw, 50vw">`.
Q21beginnerWhen is a `<table>` appropriate vs CSS grid?
Use `<table>` for tabular data with row/column relationships—financial reports, comparison matrices. Use CSS grid or flexbox for page layout. Misusing tables for layout breaks screen reader table navigation and harms responsive behavior.
Q22intermediateHow do `<thead>`, `<tbody>`, and `<th scope>` help accessibility?
They expose header/data relationships to assistive technology. `<th scope="col">` labels columns; `scope="row"` labels rows. Complex tables may need `headers`/`id` associations. Without proper headers, a screen reader user hears numbers without context.
Q23beginnerWhat makes a link accessible?
Descriptive link text ('View March invoice') rather than 'click here'. Sufficient color contrast, visible focus ring, and a real `href` (not `#` with click handler only). Opening new tabs should be indicated and avoided unless necessary.
Q24intermediate`rel="noopener noreferrer"` on `target="_blank"`—why?
External tabs opened with `target="_blank"` grant the new page `window.opener` access—a tab-nabbing security risk. `noopener` removes that access; `noreferrer` also omits the Referer header. Always add both for external links in user-generated content.
Q25intermediateDifference between `defer` and `async` on `<script>`?
`defer` downloads in parallel but executes after HTML parsing, preserving document order—ideal for app bundles depending on DOM. `async` downloads and executes as soon as ready, out of order—good for independent analytics. Neither attribute: parser-blocking download and execution.
Q26beginnerWhere should scripts go—head or end of body?
Classic advice: before `</body>` to avoid blocking render. Modern practice: `<script defer src="app.js">` in `<head>` is fine—the defer attribute preserves order without blocking paint. Inline critical scripts should be minimal.
Q27advancedWhat is the `sandbox` attribute on iframes?
It applies a restrictive permission set—no forms, no scripts, no same-origin access unless explicitly re-enabled via tokens like `allow-scripts`. Use when embedding untrusted third-party widgets to limit damage from compromised embeds.
Q28advancedHow does CSP interact with inline scripts?
Content Security Policy headers can block inline `<script>` and `onclick` handlers unless nonces or hashes allow specific snippets. SPAs often use nonces per request or avoid inline JS entirely. Interview tip: mention CSP when discussing XSS mitigation alongside output encoding.
Q29advancedWhat problem do Web Components solve?
They encapsulate markup, style, and behavior in reusable custom tags via Custom Elements, Shadow DOM, and HTML templates. Framework-agnostic design systems (e.g., Shoelace) ship as Web Components consumable from React via wrappers.
Q30advancedShadow DOM vs regular DOM for styling?
Shadow DOM creates a scoped subtree—external CSS does not leak in unless using `::part` or CSS variables. That prevents accidental style overrides but complicates global theming unless you design token hooks deliberately.
Q31intermediateExplain progressive enhancement in HTML context.
Start with semantic HTML that works without JavaScript—forms submit, links navigate, content is readable. Layer CSS for presentation and JS for interactivity. If JS fails or loads slowly, core tasks still succeed. Interviewers value this for reliability and accessibility.
Q32intermediateHow does `<noscript>` fit into a SPA?
It displays fallback content when JS is disabled or blocked—e.g., 'Enable JavaScript to use this app' plus contact info. It does not run in the JS-enabled case. For public sites, consider server-rendered fallbacks beyond a bare message.
Q33beginnerWhy use specific input types like `email`, `tel`, `url`?
Browsers show appropriate keyboards on mobile, apply built-in validation, and improve autofill accuracy. `type="number"` can harm UX for codes and IDs (spinners)—sometimes `type="text" inputmode="numeric"` is better.
Q34intermediateWhat is `inputmode` and when prefer it over `type="number"`?
`inputmode` hints the virtual keyboard layout without changing validation semantics. Credit cards, OTP codes, and leading-zero IDs should not use `type="number"` because '0123' becomes 123. Prefer `type="text" inputmode="numeric" pattern="[0-9]*"`.
Q35intermediateHow does `<datalist>` differ from `<select>`?
`<datalist>` offers suggestions while allowing free text—good for 'city name' fields with common options but custom entries. `<select>` restricts to predefined values. Datalist has inconsistent styling and limited accessibility—test with screen readers before relying on it.
Q36beginnerAutofill attributes: `autocomplete="email"` purpose?
It helps password managers and browsers map fields to stored credentials or addresses, reducing friction and typos. Use spec-compliant tokens on login, shipping, and payment forms. Incorrect tokens break autofill heuristics.
Q37intermediateNative `<details>/<summary>` vs JS accordion—tradeoffs?
Native disclosure requires no JS, works with keyboard, and exposes built-in semantics. JS accordions allow exclusive open state, animations, and deep linking—but need ARIA (`aria-expanded`, `aria-controls`) and keyboard handlers. Prefer native for FAQ sections when design allows.
Q38beginnerCan you nest `<details>` elements?
Yes—nested disclosures work natively for hierarchical FAQs. Ensure summary text remains descriptive at each level so users know what will expand.
Q39advancedWhat is JSON-LD and why use it over microdata attributes?
JSON-LD embeds structured data as a `<script type="application/ld+json">` block, separate from visible markup—easier to maintain in SPAs and CMS templates. Search engines consume it for rich results (recipes, events, products) without polluting HTML attributes.
Q40intermediateGive an example where structured data helps SEO.
A job posting with `JobPosting` schema can show salary range and location in Google results. An article with `Article` schema may show publish date and author. It does not guarantee rich results but enables eligibility.
Q41beginnerWhen must you escape `<`, `>`, `&` in HTML text?
Always in text nodes and attribute values unless inserting trusted HTML intentionally. User-supplied content must be encoded server-side to prevent XSS. In JSX/React, `{userInput}` auto-escapes text; `dangerouslySetInnerHTML` does not.
Q42beginnerDifference between ` ` and regular space?
Non-breaking space prevents line breaks between tokens—use sparingly for '10 MB' or brand names. Overuse causes awkward wrapping. Prefer CSS `white-space` for layout control instead of entity abuse.
Q43beginnerBlock vs inline vs inline-block—layout impact?
Block elements (`div`, `p`) start on a new line and stretch full width by default. Inline (`span`, `a`) flow within text and ignore width/height. Inline-block participates in inline flow but accepts box model sizing—useful for buttons in text lines.
Q44intermediateCan you put a `<div>` inside a `<p>`?
No—`<p>` cannot contain block-level elements; the browser implicitly closes the `<p>` when it sees a `<div>`, producing invalid DOM repair. Use `<div>` wrappers or multiple `<p>` tags instead.
Q45intermediateWhat is the `<canvas>` element used for?
A bitmap drawing surface manipulated via JavaScript—charts, games, image filters. It is not accessible by default; provide text alternatives or duplicate data in accessible tables. For declarative graphics, SVG is often better for accessibility and scaling.
Q46advanced`<template>` element purpose?
Holds inert HTML fragments cloned by JS when needed—used in Web Components and client-side templating before render. Content inside `<template>` is not rendered or executed until instantiated.
Q47beginnerWhy set `lang` on `<html>`?
It tells assistive tech which pronunciation rules and voice to use, helps search engines identify language, and enables browser translation offers. Subsections in another language should use `lang` on a wrapping element.
Q48intermediate`dir="rtl"` considerations?
Right-to-left languages (Arabic, Hebrew) need `dir="rtl"` on `<html>` or containers. Logical CSS properties (`margin-inline-start`) adapt better than hard-coded left/right margins when supporting RTL.
Q49advancedHow does HTML contribute to XSS attack surface?
Injecting unescaped user input into HTML creates script execution vectors—attribute breakout, event handlers, `javascript:` URLs. Mitigate with contextual encoding, CSP, HTTPOnly cookies, and frameworks that escape by default. Never concatenate user input into HTML strings server-side.
Q50intermediateIs `target="_blank"` alone a security issue?
Combined with missing `rel="noopener"`, the opened page can access `window.opener` and redirect the parent—tab nabbing. Always pair external blank targets with `noopener noreferrer`.
Q51advancedWhat is critical rendering path related to HTML?
Browser parses HTML into DOM, fetches CSS/JS, builds CSSOM, layout, paint. Blocking scripts and unoptimized head resources delay first paint. Minimize render-blocking resources, inline tiny critical CSS, defer non-critical JS.
Q52advancedPreload vs prefetch vs preconnect?
`preload` fetches high-priority current-page assets (hero font, critical JS). `prefetch` hints low-priority future navigation resources. `preconnect` opens early connections to origins (CDN, API)—reduces TLS latency on first request.
Q53intermediateHow does native `<dialog>` improve modals?
Provides `showModal()` with top-layer stacking, backdrop, focus trapping, and Escape to close in supporting browsers. Still add accessible titles (`aria-labelledby`) and return focus on close. Polyfill or library needed for consistent older browser support.
Q54advanced`<dialog open>` vs `showModal()`?
`open` attribute displays non-modal dialog; `showModal()` presents modal with backdrop and focus trap. Choose based on whether interaction with background should be blocked.
Q55intermediateScenario: A designer wants every heading styled as `<h3>` for visual consistency. What's wrong?
Heading levels convey document outline, not appearance—style with CSS instead. Skipping levels or flattening hierarchy confuses screen reader users navigating by headings and hurts SEO structure. One `<h1>` per page for primary title, then nested levels without gaps.
Q56advancedScenario: Marketing inserts `<iframe>` analytics without sandbox. Risk?
Third-party iframes run with full capabilities in your origin context unless restricted. A compromised vendor script could phish users or read cookies if same-site policies are weak. Use sandbox, strict CSP, and vendor trust reviews.
Q57beginnerCompare `<b>` vs `<strong>` and `<i>` vs `<em>`.
Historically `<b>`/`<i>` were purely visual; HTML5 redefined them: `<strong>` indicates importance, `<em>` stress emphasis—both carry semantic weight. `<b>`/`<i>` are for stylistically offset text without extra emphasis meaning. Prefer semantic tags when meaning matters.
Q58intermediateWhat happens when you nest interactive elements—a link inside a button?
HTML forbids interactive content nesting; browsers repair DOM unpredictably. Screen readers may announce both roles, and clicks may double-fire. Structure as sibling elements or choose one interactive element with clear purpose.
Q59intermediateHow would you structure a blog index page semantically?
`<header>` with site title/nav, `<main>` containing a list of `<article>` elements (each with its own `<header>`, heading link, summary, `<time datetime>`), plus `<nav aria-label="Pagination">`. Footer with site links. One `<main>`, descriptive headings inside each article.
Q60beginnerExplain `loading="lazy"` on images.
Native lazy loading defers off-screen image fetches until the user scrolls near them, improving initial load. Do not lazy-load above-the-fold hero images—that delays LCP. Combine with explicit width/height to prevent layout shift.
Q61advancedWhat is the `hidden` attribute vs `aria-hidden="true"`?
`hidden` removes element from rendering and accessibility tree in supporting browsers—good for fully inactive panels. `aria-hidden="true"` hides from assistive tech but element may still be focusable if visible—dangerous if focus can land on 'hidden' content. Never hide focusable controls from AT while keeping them tabbable.
Q62beginnerWhy avoid multiple `<h1>` on one page?
While HTML5 allows sectioning outlines, best practice is one primary `<h1>` describing page purpose; subsection titles use lower levels. Multiple h1s dilute document summary for SEO and some assistive tech navigation modes.
Q63intermediateHow do you implement a accessible toggle switch in plain HTML?
Prefer `<button type="button" aria-pressed="true|false">` with visible label text. If using checkbox visually styled, keep native `<input type="checkbox">` associated with label—do not rely on div-only toggles without roles and keyboard support.
Q64advancedWhat is `contenteditable` and its accessibility pitfalls?
It makes elements editable like a text field but lacks form semantics, labels, and validation integration. Rich text editors need ARIA roles, keyboard shortcuts documentation, and sanitization on paste to avoid XSS.
Q65advancedHTML concept #65: Explain HTML parsing.
The browser tokenizer converts bytes to tokens, builds the DOM tree, and executes scripts that may mutate the tree. Parser-blocking scripts pause HTML parsing—use defer/async strategically. In interviews, tie the concept to accessibility, security, or performance impact—not just definition.
Q66intermediateWhat interview follow-up might an interviewer ask about HTML parsing?
Expect 'give an example' or 'what breaks if misused.' For HTML parsing: The browser tokenizer converts bytes to tokens, builds the DOM tree, and executes scripts that may mutate the tree. Prepare a concrete bug story or code snippet demonstrating correct usage.
Q67beginnerHTML concept #66: Explain Void elements.
Elements like `<img>`, `<br>`, `<input>` have no closing tag and cannot contain children. XHTML-style self-closing (`<img/>`) is optional in HTML5 but valid. In interviews, tie the concept to accessibility, security, or performance impact—not just definition.
Q68intermediateWhat interview follow-up might an interviewer ask about Void elements?
Expect 'give an example' or 'what breaks if misused.' For Void elements: Elements like `<img>`, `<br>`, `<input>` have no closing tag and cannot contain children. Prepare a concrete bug story or code snippet demonstrating correct usage.
Q69beginnerHTML concept #67: Explain Global attributes.
`id`, `class`, `data-*`, `hidden`, `tabindex`, `title`, `lang` apply to most elements. `data-*` stores custom JS hooks without non-standard attributes. In interviews, tie the concept to accessibility, security, or performance impact—not just definition.
Q70intermediateWhat interview follow-up might an interviewer ask about Global attributes?
Expect 'give an example' or 'what breaks if misused.' For Global attributes: `id`, `class`, `data-*`, `hidden`, `tabindex`, `title`, `lang` apply to most elements. Prepare a concrete bug story or code snippet demonstrating correct usage.
Q71beginnerHTML concept #68: Explain Anchor links.
Fragment identifiers (`href="#section"`) scroll to elements with matching `id`. Ensure target exists and consider `scroll-margin-top` for fixed headers. In interviews, tie the concept to accessibility, security, or performance impact—not just definition.
Q72intermediateWhat interview follow-up might an interviewer ask about Anchor links?
Expect 'give an example' or 'what breaks if misused.' For Anchor links: Fragment identifiers (`href="#section"`) scroll to elements with matching `id`. Prepare a concrete bug story or code snippet demonstrating correct usage.
Q73intermediateHTML concept #69: Explain Picture element.
`<picture>` wraps `<source>` elements for art direction or format negotiation (WebP/AVIF fallbacks) before a default `<img>`. In interviews, tie the concept to accessibility, security, or performance impact—not just definition.
Q74intermediateWhat interview follow-up might an interviewer ask about Picture element?
Expect 'give an example' or 'what breaks if misused.' For Picture element: `<picture>` wraps `<source>` elements for art direction or format negotiation (WebP/AVIF fallbacks) before a default `<img>`. Prepare a concrete bug story or code snippet demonstrating correct usage.
Q75beginnerHTML concept #70: Explain Meter and progress.
`<progress>` shows task completion; `<meter>` shows gauge within known range—they have implicit ARIA roles but need labels for context. In interviews, tie the concept to accessibility, security, or performance impact—not just definition.
Q76intermediateWhat interview follow-up might an interviewer ask about Meter and progress?
Expect 'give an example' or 'what breaks if misused.' For Meter and progress: `<progress>` shows task completion; `<meter>` shows gauge within known range—they have implicit ARIA roles but need labels for context. Prepare a concrete bug story or code snippet demonstrating correct usage.
Q77intermediateHTML concept #71: Explain Output element.
`<output>` associates calculated results with form inputs via `for` attribute referencing input ids—useful for live calculators with accessibility. In interviews, tie the concept to accessibility, security, or performance impact—not just definition.
Q78intermediateWhat interview follow-up might an interviewer ask about Output element?
Expect 'give an example' or 'what breaks if misused.' For Output element: `<output>` associates calculated results with form inputs via `for` attribute referencing input ids—useful for live calculators with accessibility. Prepare a concrete bug story or code snippet demonstrating correct usage.
Q79intermediateHTML concept #72: Explain Fieldset disabled.
Setting `disabled` on `<fieldset>` disables all nested controls—cleaner than disabling each input individually for conditional form sections. In interviews, tie the concept to accessibility, security, or performance impact—not just definition.
Q80intermediateWhat interview follow-up might an interviewer ask about Fieldset disabled?
Expect 'give an example' or 'what breaks if misused.' For Fieldset disabled: Setting `disabled` on `<fieldset>` disables all nested controls—cleaner than disabling each input individually for conditional form sections. Prepare a concrete bug story or code snippet demonstrating correct usage.
Q81intermediateHTML concept #73: Explain Accept attribute.
On file inputs, `accept="image/*,.pdf"` filters picker options—client-side hint only; always validate MIME type and size server-side. In interviews, tie the concept to accessibility, security, or performance impact—not just definition.
Q82intermediateWhat interview follow-up might an interviewer ask about Accept attribute?
Expect 'give an example' or 'what breaks if misused.' For Accept attribute: On file inputs, `accept="image/*,. Prepare a concrete bug story or code snippet demonstrating correct usage.
Q83intermediateHTML concept #74: Explain Download attribute.
On same-origin links, `download` suggests filename for saving resource—does not work cross-origin due to security restrictions. In interviews, tie the concept to accessibility, security, or performance impact—not just definition.
Q84intermediateWhat interview follow-up might an interviewer ask about Download attribute?
Expect 'give an example' or 'what breaks if misused.' For Download attribute: On same-origin links, `download` suggests filename for saving resource—does not work cross-origin due to security restrictions. Prepare a concrete bug story or code snippet demonstrating correct usage.
Q85advancedHow does HTML support offline-first PWAs at markup level?
The web app manifest link (`<link rel="manifest">`), theme-color meta, apple-touch-icon, and service worker registration script in HTML bootstrap installability. Markup alone does not offline-cache—SW does—but missing manifest link breaks add-to-homescreen.
Q86advancedRole of `<base href>`—caution?
Sets default URL for relative links and forms on the page. Wrong base breaks routing in SPAs deployed to subpaths; can also enable open redirect bugs if attacker controls base. Rarely needed in modern apps with absolute asset paths.
Q87advancedCompare semantic nav in multi-page app vs React Router app.
MPA: each route is a full document with own `<title>` and landmarks. SPA: shell is static—update `document.title`, focus management on route change, and announce page changes via aria-live region because browser does not fire full navigation events.
Q88beginnerHTML best practice drill #88: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q89intermediateHTML best practice drill #89: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q90beginnerHTML best practice drill #90: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q91intermediateHTML best practice drill #91: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q92beginnerHTML best practice drill #92: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q93intermediateHTML best practice drill #93: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q94beginnerHTML best practice drill #94: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q95intermediateHTML best practice drill #95: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q96beginnerHTML best practice drill #96: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q97intermediateHTML best practice drill #97: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q98beginnerHTML best practice drill #98: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q99intermediateHTML best practice drill #99: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q100beginnerHTML best practice drill #100: Why validate markup?
Validators catch unclosed tags, duplicate ids, and invalid nesting that cause inconsistent DOM repair across browsers. CI HTML linting prevents accessibility regressions—duplicate ids break label associations and aria-labelledby references.
Q101intermediateSVG vs Canvas — when do you choose which?
SVG is a retained-mode DOM of vector shapes: great for icons, charts needing accessibility/CSS/events per element, and crisp scaling. Canvas is immediate-mode pixels: better for games, particle effects, and dense visualizations where updating thousands of DOM nodes would be slow. SVG scales resolution-independently; Canvas needs redraws (and often devicePixelRatio handling) for HiDPI. Prefer SVG for interactive diagrams; Canvas when you own the paint loop.
Q102advancedHow do you make Canvas content accessible?
Canvas pixels are opaque to assistive tech. Provide a textual fallback inside the `<canvas>` element, expose an adjacent live region or ARIA description summarizing state, and mirror key interactions with keyboard-accessible controls outside the canvas. For charts, prefer SVG or a data table alternative. Never rely on canvas alone for critical UI text.
Q103intermediateExplain `<picture>` vs `srcset` on `<img>`.
`srcset`/`sizes` on `<img>` lets the browser pick among same-art variants by width or density. `<picture>` adds art direction: different crops/formats via `<source media="...">` or `type="image/avif"`. Use `srcset` for resolution switching; use `<picture>` when layout needs a different image composition or format negotiation with a fallback `<img>`.
Q104intermediateWalk through a responsive image with width descriptors.
Example: `<img src="hero-800.jpg" srcset="hero-400.jpg 400w, hero-800.jpg 800w, hero-1600.jpg 1600w" sizes="(max-width:600px) 100vw, 50vw" alt="...">`. `sizes` tells the browser the rendered CSS width; it picks the smallest file that covers that slot × DPR. Always include `src` + `alt` fallback.
Q105intermediateWhat are Web Components? Name the three specs.
Custom Elements (define new HTML tags), Shadow DOM (encapsulated DOM/CSS), and HTML Templates (`<template>`/`<slot>`). Together they let you ship reusable widgets without a framework. Register with `customElements.define('x-card', class extends HTMLElement {...})`. Frameworks can wrap them; they also work in plain HTML.
Q106advancedExplain Shadow DOM encapsulation and slots.
Open shadow roots isolate internal markup/styles from the light DOM (and vice versa for selectors). Light DOM children project into `<slot>` placeholders. Modes: `open` (accessible via `el.shadowRoot`) vs `closed`. Styles don't leak in/out unless using parts/`::part` or CSS variables. Great for design-system primitives.
Q107intermediateHow do SEO meta tags and Open Graph work together?
`<title>` and `<meta name="description">` feed search snippets. Open Graph (`og:title`, `og:description`, `og:image`, `og:url`, `og:type`) drives social previews on Facebook/LinkedIn/Slack. Twitter uses `twitter:card` similarly. SPAs need server-rendered or prerendered head tags per route—crawlers and scrapers often won't execute your client router for share cards.
Q108beginnerWhich Open Graph tags are most important for sharing?
Minimum viable: `og:title`, `og:description`, `og:image` (absolute HTTPS URL, ~1200×630), and `og:url` canonical. Add `og:type` (`website`/`article`). Validate with platform debuggers; caches are sticky—update image URLs or use cache busting when assets change.
Q109advancedWhat does the iframe `sandbox` attribute do?
`sandbox` applies a strict default: no scripts, forms, popups, same-origin access, etc. You opt back in with tokens: `allow-scripts`, `allow-same-origin`, `allow-forms`, `allow-popups`, `allow-downloads`. Never combine `allow-scripts` + `allow-same-origin` on untrusted content—that can escape the sandbox. Use for third-party embeds and user HTML.
Q110intermediate`contenteditable` — uses and pitfalls?
`contenteditable="true"` makes an element a rich-text surface. Pitfalls: inconsistent browser HTML serialization, XSS if you persist unsanitized HTML, messy caret/IME behavior, and accessibility complexity. Prefer constrained editors (ProseMirror/TipTap) or plain `<textarea>` when rich text isn't required. Sanitize on input and output.
Q111intermediateExplain the HTML `<dialog>` element.
`<dialog>` provides a native modal/non-modal dialog with `showModal()` / `show()` / `close()`. Modal dialogs use the top layer, trap focus, and dim via `::backdrop`. Handle `close` event and form method="dialog". Prefer it over DIY modals for accessibility baseline—still label with `aria-labelledby` and ensure Esc/focus restore UX.
Q112advancedWhat is the Popover API (`popover` attribute)?
Elements with `popover` can be shown in the top layer without dialog modality—ideal for menus, tooltips, teaching bubbles. Toggle via `popovertarget` on buttons or `showPopover()`. Light dismiss (click outside) is built-in. Complements `<dialog>`: popovers don't block the page; dialogs do when modal.
Q113intermediateName useful `autocomplete` tokens for forms.
Use specific tokens so password managers and browsers fill correctly: `name`, `email`, `username`, `new-password`, `current-password`, `tel`, `street-address`, `address-line1`, `country`, `cc-number`, `cc-exp`. Prefer granular tokens over `on`. Wrong tokens break autofill and hurt conversion/accessibility.
Q114advanced`preload` vs `prefetch` vs `preconnect` vs `dns-prefetch`?
`preconnect` warms TCP/TLS to an origin; `dns-prefetch` is DNS-only. `preload` is a high-priority fetch for a resource needed for the current navigation (font, critical CSS, hero image) with `as=`. `prefetch` is low-priority speculative fetch for a likely next navigation. Misusing `preload` wastes bandwidth—only preload what you will use soon.
Q115intermediateWhat is Subresource Integrity (SRI)?
SRI uses `integrity="sha384-..."` (and usually `crossorigin`) on `<script>`/`<link>` so the browser verifies the file hash before executing/applying it. Protects against compromised CDNs. Generate hashes with openssl dgst; update hashes when you bump library versions.
Q116intermediateExplain `referrerpolicy` on links and documents.
Controls how much referrer is sent: `no-referrer`, `origin`, `strict-origin-when-cross-origin` (common default), `unsafe-url`, etc. Set via `<meta name="referrer">`, `Referrer-Policy` header, or per-element `referrerpolicy`. Tighten to reduce leaking path/query to third parties while keeping analytics usable.
Q117intermediateHow does `loading="lazy"` on images interact with `fetchpriority`?
`loading="lazy"` defers offscreen images. `fetchpriority="high"` hints urgency for LCP candidates (usually the hero—don't lazy-load it). Use lazy for below-the-fold; eager/high priority for the LCP image. Wrong combo tanks Core Web Vitals.
Q118advancedWhat is `crossorigin` used for with fonts and SRI?
Anonymous CORS mode (`crossorigin` or `crossorigin="anonymous"`) is required for canvas pixel access, SRI checks, and many font loads from other origins. Without it, CORS-restricted responses may still display but fail integrity/canvas read. CDNs must send `Access-Control-Allow-Origin`.
Q119beginner`<template>` element — what is it for?
`<template>` holds inert DOM that isn't rendered until cloned with `template.content.cloneNode(true)`. Used by Web Components and vanilla UI to stamp repeated structures without string HTML. Scripts inside templates don't run until attached after clone.
Q120advancedHow do you declare a custom element that reacts to attributes?
Extend `HTMLElement`, observe attrs via `static get observedAttributes()` and `attributeChangedCallback`. In `connectedCallback`, render into shadow DOM. Reflect properties to attributes when that matches platform conventions. Define before the element appears or handle upgrade timing carefully.
Q121beginner`rel="noopener noreferrer"` on `target="_blank"` — why?
Historically `window.opener` let the new page reverse-tabnab the opener. `noopener` nulls opener; `noreferrer` also omits referrer. Modern browsers imply noopener for `target=_blank`, but explicit `rel` remains a safe interview answer and strips referrer when needed.
Q122intermediateWhat is `decoding="async"` on images?
Hints that image decode may happen off the main thread, reducing jank during scroll. Combine with proper dimensions (`width`/`height` or aspect-ratio CSS) to avoid CLS. It is a hint, not a guarantee.
Q123beginnerExplain `<meta name="robots" content="noindex,nofollow">`.
`noindex` asks crawlers not to index the page; `nofollow` asks them not to follow links. Useful for thank-you pages, internal tools, staging (better: auth + robots.txt). Robots meta is advisory—combine with authentication for private apps.
Q124intermediateHow do JSON-LD structured data and HTML relate?
JSON-LD in `<script type="application/ld+json">` describes entities (Article, FAQ, Product) for rich results without changing visible DOM. Keep it consistent with on-page content—mismatch risks manual actions. Prefer server-rendered JSON-LD for reliability.
Q125intermediate`inputmode` vs `type` on inputs?
`type` sets semantics/validation (`email`, `tel`, `number`). `inputmode` only hints the virtual keyboard (`decimal`, `numeric`, `tel`, `email`) without changing validation. Use `inputmode="decimal"` with `type="text"` when you need flexible parsing but a numeric keypad.
Q126beginnerWhat does `enterkeyhint` do?
Hints the mobile Enter key label: `search`, `done`, `go`, `next`, `send`. Improves form UX on multi-field flows. It doesn't change submit behavior by itself—still handle key events/form submit.
Q127advancedSandbox + CSP for untrusted HTML embeds — pattern?
Serve user HTML in an iframe with tight `sandbox` (avoid scripts+same-origin), restrictive CSP (`default-src 'none'`), and ideally a separate origin. Sanitize server-side too. Defense in depth: sandbox is not a sanitizer replacement alone if you allow scripts.
Q128advanced`<link rel="modulepreload">` — when?
Preloads ES modules and their dependency graph for faster startup of module-based apps. Use for critical entry chunks discovered late otherwise. Pair with HTTP/2/3 and correct CORS attributes as required.
Q129intermediateDifference between `hidden`, `display:none`, and `aria-hidden`?
`hidden` HTML attribute maps to `display:none` and removes from a11y tree/interaction. `aria-hidden="true"` hides from assistive tech but may leave focusable children—dangerous if focusable. Prefer `hidden` or `inert` for fully inactive UI; don't leave focusable nodes under `aria-hidden`.
Q130advancedWhat is the `inert` attribute?
`inert` makes a subtree unfocusable, non-editable, and hidden from assistive tech—ideal for background content behind a modal. Prefer with `<dialog showModal()>` patterns. Broader and safer than manually toggling `tabindex`/`aria-hidden` on every node.
Q131intermediateCanonical link tag — why?
`<link rel="canonical" href="https://example.com/page">` tells search engines the preferred URL when duplicates exist (query params, trailing slash, HTTP mirrors). Prevents split ranking signals. Self-canonical on clean URLs is common; avoid pointing canonical at redirected/error URLs.
Q132intermediateHow do you mark up a FAQ for accessibility and SEO?
Use headings + content regions; ensure keyboard expandable panels use buttons and `aria-expanded`. Optionally add FAQPage JSON-LD matching visible Q&A. Don't hide critical answers only in images.
Q133intermediate`<form>` `method="dialog"` inside `<dialog>`?
Submitting a button in a form with `method="dialog"` closes the dialog and sets `returnValue` from the button's value—native confirm/cancel without custom JS close wiring. Still listen for `close` to read the result.
Q134advancedExplain `fetchpriority` on `<link>` and `<img>`.
`fetchpriority="high|low|auto"` influences resource scheduling among peers. Raise the LCP image/font; lower non-critical images. Over-marking everything high cancels the benefit. Use with LCP debugging in the field.
Q135beginnerWhy set width and height attributes on images?
They let the browser reserve aspect-ratio space before the file loads, preventing Cumulative Layout Shift. Modern CSS `aspect-ratio` helps too. Still provide responsive CSS (`max-width:100%; height:auto`) so attributes don't force oversized layout on small screens.
CSS
156 questions
Q1beginnerExplain the CSS box model and what `box-sizing: border-box` changes.
Every element is a rectangle with content, padding, border, and margin layers. By default (`content-box`), width/height apply only to content—padding and border add to total size. `border-box` includes padding and border in the declared width, making layout math predictable: `width: 100%` truly fills the parent. Most CSS resets set `*, *::before, *::after { box-sizing: border-box; }` for this reason.
Q2intermediateScenario: A card has `width: 300px`, `padding: 20px`, and `border: 2px solid` under default box-sizing. What is its rendered width?
Under `content-box`, total width = 300 + 40 (padding) + 4 (border) = 344px. This surprises developers when columns overflow flex containers. Switching to `border-box` keeps the outer width at 300px by shrinking the content area. Always clarify box-sizing when debugging horizontal overflow.
Q3intermediateHow do margin collapse and padding differ in vertical spacing between siblings?
Adjacent vertical margins collapse to the larger value—two `margin-bottom: 20px` and `margin-top: 30px` yield 30px gap, not 50px. Padding never collapses; it always adds inside the element box. Flex and grid containers often suppress margin collapse between children. Use padding or gap when you need guaranteed spacing.
Q4beginnerWhen would you use `outline` instead of `border`?
`outline` draws outside the border without affecting layout—ideal for focus rings that must not shift content. Unlike border, outline doesn't participate in box size. Example: `button:focus-visible { outline: 2px solid #0066cc; outline-offset: 2px; }`. Never remove focus outlines without replacing them—keyboard users depend on them.
Q5advancedCompare `min-height: 100vh` vs `min-height: 100dvh` for full-screen layouts.
`100vh` on mobile includes the browser chrome area, often causing content to sit under the address bar or require extra scroll. `100dvh` (dynamic viewport height) adjusts as mobile UI shows/hides. For sticky footers on phones, prefer `dvh` with `vh` fallback: `min-height: 100vh; min-height: 100dvh`.
Q6intermediateWhat causes unexpected horizontal scroll on a responsive page?
Common culprits: fixed-width children wider than viewport, negative margins, `100vw` including scrollbar width, absolutely positioned elements extending past edges, and non-wrapping text. Debug with DevTools or temporarily set `outline: 1px solid red` on suspects. Fix with `max-width: 100%`, `min-width: 0` on flex children, or remove fixed widths.
Q7intermediateExplain `margin: auto` centering in block layout vs flexbox.
A block element with explicit width and `margin-left: auto; margin-right: auto` centers horizontally in its containing block. In flexbox, `margin: auto` on a flex item absorbs extra space along that axis—useful for pushing one item to the far end (`margin-left: auto` on the last nav link). Grid supports similar auto-margin behavior.
Q8intermediateHow does `aspect-ratio` help prevent layout shift?
Reserving space before media loads prevents Cumulative Layout Shift (CLS). Example: `img { aspect-ratio: 16/9; width: 100%; height: auto; }` keeps a placeholder box. Pair with explicit width/height attributes in HTML for best Core Web Vitals scores.
Q9beginnerWhat problem does Flexbox solve compared to float-based layouts?
Flexbox distributes space along a single axis, aligns items, and handles variable content heights without clearfix hacks. A navbar with `display: flex; justify-content: space-between; align-items: center` replaces fragile float + vertical-align patterns. Flex items shrink/grow via `flex` shorthand—floats cannot do that natively.
Q10intermediateExplain `flex: 1` vs `flex: 1 1 0` vs `flex: 1 1 auto`.
`flex: 1` expands to `flex: 1 1 0%`—items share space from a zero base, often equal columns. `flex: 1 1 auto` bases size on content before growing. Misusing `flex: 1` on text inputs can make them shrink below readable width—set `min-width: 0` on flex children that must truncate or scroll.
Q11beginner`justify-content` vs `align-items`—which axis does each control?
In default `flex-direction: row`, `justify-content` aligns along the main (horizontal) axis; `align-items` along the cross (vertical) axis. They swap when direction is column. Interview tip: draw the main axis arrow first, then map properties.
Q12intermediateScenario: Three columns should be equal width but the middle one is wider due to content. Fix?
Flex items default `min-width: auto`, preventing shrink below content size. Apply `min-width: 0` to flex children and optionally `overflow: hidden; text-overflow: ellipsis`. For strict equal columns use `flex: 1 1 0` on each child with `min-width: 0`.
Q13intermediateWhen use `align-self` vs wrapping items in nested flex containers?
`align-self` overrides `align-items` for one item—e.g., stretch all buttons but pin one to `flex-start`. Nested flex is clearer when a whole subgroup needs different alignment. Overusing `align-self` scatters layout logic; prefer consistent container rules.
Q14beginnerHow does `flex-wrap` interact with `align-content`?
Without wrap, `align-content` has no effect. With `flex-wrap: wrap` and multiple lines, `align-content` distributes lines along the cross axis (like `justify-content` for rows of items). Use `gap` for consistent spacing between wrapped items—cleaner than margins on each child.
Q15advancedBuild a holy-grail layout with Flexbox only—high-level approach?
Column flex on `body`: header/footer fixed height, middle `flex: 1` row flex with sidebar + main both `flex: 1` or sidebar fixed width. Modern alternative: CSS Grid `grid-template-rows: auto 1fr auto` is often simpler, but flex holy-grail remains a classic interview exercise.
Q16advancedWhy might `order` property harm accessibility?
Visual reorder via `order` does not change DOM/tab order—keyboard users tab through DOM sequence, not visual layout. Screen readers follow DOM too. Only use `order` for purely visual shuffles with no focusable elements involved, or duplicate navigation for mobile carefully with matching tab order.
Q17beginnerWhen choose CSS Grid over Flexbox?
Grid excels at two-dimensional layouts—rows and columns simultaneously—like dashboards, photo galleries, or page shells. Flexbox excels at one-dimensional distribution (nav bars, toolbars). They compose: grid for page structure, flex inside cells for component internals. 'Grid for layout, flex for alignment' is a solid rule of thumb.
Q18beginnerExplain `fr` unit in `grid-template-columns: 1fr 2fr 1fr`.
`fr` distributes leftover space proportionally after fixed tracks resolve. Here the center column gets twice the flexible space of each side. Unlike percentages, `fr` accounts for gaps automatically. Mix fixed and flexible: `grid-template-columns: 200px 1fr 200px` for sidebars.
Q19intermediateWhat does `grid-template-areas` buy you?
Named areas make layouts readable and responsive without renumbering lines. Example: `'header header' 'sidebar main' 'footer footer'`. Media queries swap the template string for mobile. Interviewers like seeing semantic area names (`sidebar`, `main`) instead of magic line numbers.
Q20intermediate`minmax(200px, 1fr)` in `repeat(auto-fit, minmax(200px, 1fr))`—behavior?
Creates as many columns as fit at minimum 200px, expanding equally to fill the row—responsive card grids without media queries. `auto-fit` collapses empty tracks; `auto-fill` keeps ghost columns. Essential pattern for responsive product grids.
Q21intermediateScenario: Item should span two columns on desktop, one on mobile. Approach?
Define areas or use `grid-column: span 2` at desktop breakpoint; reset to `span 1` in mobile query. With areas, change the entire template string. Prefer areas when multiple elements reposition together.
Q22advancedSubgrid: what problem does it solve?
Nested grids can align child items to parent grid lines using `grid-template-columns: subgrid` (growing browser support). Without subgrid, card internals misalign across rows. Fallback: shared CSS variables for column tracks or flat grid on parent with `display: contents` on wrappers.
Q23beginner`place-items: center` vs flexbox centering inside a grid cell?
Both center content within a cell. Grid's `place-items` is shorthand for align + justify on the grid container's items. Flex inside the cell offers finer control when content wraps or needs gap between multiple children. Pick one centering strategy per component to avoid fighting.
Q24advancedHow does `grid-auto-flow: dense` affect layout?
Fills holes left by spanning items by packing smaller items backward—useful for masonry-like dashboards. Order becomes visual-only; accessibility order still follows DOM. Can confuse users if focus order jumps visually—document tradeoffs.
Q25intermediateCalculate specificity for `#nav .item a.active`.
IDs: 1 (`#nav`), classes/attributes/pseudo-classes: 2 (`.item`, `.active`), elements: 1 (`a`) → (1, 2, 1). Inline styles beat IDs; `!important` overrides normal cascade unless competing `!important`. Specificity is per property, not whole rulesets.
Q26beginnerWhy avoid deep selector chains like `div ul li a span`?
They increase specificity, couple styles to DOM structure, and break when markup refactors. A utility class or BEM block element survives HTML changes. Performance impact is usually minor; maintainability is the real cost.
Q27advanced`:is()` and `:where()`—how do they affect specificity?
`:is()` takes the specificity of its most specific argument. `:where()` has zero specificity—ideal for reset rules that should lose to component styles. Example: `:where(h1, h2, h3) { margin: 0; }` yields to `.card h2 { margin: 1rem; }`.
Q28intermediateExplain `:not()` practical use in component styling.
`:not(.disabled):hover` applies hover only when disabled class absent—cleaner than overriding styles. Complex `:not()` chains can still be hard to read; sometimes a data attribute `[data-state='active']` is clearer for state machines.
Q29beginnerAttribute selectors: `[href^='https']` vs `[href*='example']`?
`^=` matches prefix (external links styling), `$=` suffix, `*=` substring anywhere. Useful for icon hints on file links (`[href$='.pdf']`). Not a substitute for server validation—purely presentational.
Q30intermediateScenario: Styles don't apply despite correct class name. Debug steps?
Check DevTools Computed panel for overridden rules, typos in HTML class, specificity losers, shadow DOM encapsulation, and CSS modules hashed names. Verify stylesheet load order and whether a reset strips properties. `!important` in third-party CSS is a frequent culprit.
Q31advancedWhat is the cascade layer `@layer` feature for?
`@layer base, components, utilities;` lets you control precedence independent of specificity order within layers. Later-declared layers win; inside a layer, normal specificity applies. Design systems use layers to prevent utility classes losing to accidental component specificity.
Q32intermediateCompare BEM, CSS Modules, and utility-first (Tailwind) approaches.
BEM encodes structure in class names (`.card__title--highlighted`) with global CSS. CSS Modules scope locally via build-time hashes. Tailwind applies atomic utilities in markup—fast prototyping, HTML verbosity. All valid; teams pick based on colocation, bundle size, and designer workflow.
Q33beginnerSummarize `static`, `relative`, `absolute`, `fixed`, and `sticky`.
`static` is default document flow. `relative` offsets from normal position without leaving flow—anchors for absolute children. `absolute` removes from flow, positioned to nearest non-static ancestor. `fixed` relative to viewport. `sticky` toggles between relative and fixed when crossing threshold within scroll container.
Q34intermediateWhy must a positioned ancestor exist for `absolute` centering?
Absolute children use the padding edge of the nearest ancestor with position not `static`. Without it, they anchor to the viewport or initial containing block. Pattern: `.modal-overlay { position: relative }` wrapping `.modal { position: absolute; inset: 0; margin: auto; }`.
Q35intermediate`sticky` header fails to stick—common causes?
Any ancestor with `overflow: hidden/auto/scroll` creates a containing block that traps sticky. Missing `top` value. Parent shorter than sticky element. Flex/grid item may need `align-self: start` to prevent stretch breaking sticky. Test scroll container in DevTools.
Q36advancedStacking context basics: what creates one?
Positioned elements with z-index, opacity < 1, transforms, filters, `isolation: isolate`, flex/grid items with z-index, and more. Children compete within parent's context—`z-index: 9999` cannot escape a low parent context. Fix layering by restructuring contexts, not inflating z-index.
Q37advancedScenario: Tooltip clipped by parent `overflow: hidden`. Solutions?
Render tooltip in a portal (React DOM outside hierarchy), move tooltip to body with fixed positioning, or remove overflow on ancestor (often unacceptable). Popper/Floating UI libraries handle flip/shift to stay visible. CSS-only tooltips struggle here.
Q38advancedHow does `transform` affect `position: fixed` elements?
A transform on an ancestor creates a containing block—fixed elements position relative to that ancestor, not the viewport. This breaks modals inside transformed animations. Use portal to document body or avoid transform on modal wrappers.
Q39intermediateCenter an unknown-size modal with modern CSS.
`.modal { position: fixed; inset: 0; margin: auto; width: fit-content; height: fit-content; max-width: 90vw; max-height: 90dvh; }` or flex/grid on overlay: `display: grid; place-items: center`. Avoid hard-coded negative margins from half width/height.
Q40beginner`inset: 0` vs `top/right/bottom/left: 0`?
`inset` is logical shorthand setting all offsets—supports RTL via `inset-inline` variants in modern CSS. Equivalent to TRBL zeros for absolute/fixed fill. Cleaner for full-bleed overlays.
Q41beginnerMobile-first vs desktop-first media queries—tradeoffs?
Mobile-first writes base styles for small screens, adds `min-width` breakpoints—encourages progressive enhancement and smaller default CSS. Desktop-first uses `max-width` to subtract—legacy sites often start here. Mobile-first aligns with performance: fewer overrides on phones.
Q42intermediateExplain `clamp()` for fluid typography.
`font-size: clamp(1rem, 2.5vw + 0.5rem, 2rem)` sets min, preferred, max in one line—smooth scaling without many breakpoints. Apply to spacing and container widths too. More maintainable than calc chains per breakpoint.
Q43advancedWhat are container queries and when prefer over media queries?
`@container (min-width: 400px)` responds to parent container size, not viewport—cards reflow inside sidebar vs main column independently. Requires `container-type: inline-size` on ancestor. Use when component layout depends on available space, not device class.
Q44intermediateScenario: Image looks blurry on retina displays. Fix?
Serve higher-resolution assets via `srcset` with `2x` or width descriptors, or SVG for icons/logos. CSS `image-rendering` rarely fixes raster blur—source pixels matter. Background images need media queries or `image-set()` for DPR variants.
Q45beginner`rem` vs `em` vs `px` for responsive design?
`rem` scales with root font size—consistent for typography/spacing. `em` compounds with nesting—good for component-relative padding. `px` is absolute; fine for borders/hairlines. Prefer relative units for accessibility—users who bump root font size expect layout to adapt.
Q46intermediateHow do logical properties (`margin-inline-start`) help i18n?
They map to physical left/right based on `dir` attribute—RTL layouts mirror without duplicate rules. `margin-left` becomes wrong in Arabic interfaces. Adopt logical properties in new code; provide physical fallbacks only if supporting very old browsers.
Q47intermediateBreakpoint selection: content-based vs device-based?
Content-based breaks when layout breaks—often 480px, 768px, 1024px empirically but should come from your design. Device-based (iPhone width) ages poorly. Use DevTools responsive mode to find where flex/grid wraps awkwardly.
Q48advancedPrint stylesheet essentials for reports?
@media print { hide nav, use black text, `page-break-inside: avoid` on tables. Test print preview—background colors may not print unless `-webkit-print-color-adjust: exact`. Optionally expand links with `a[href]::after { content: ' (' attr(href) ')'; }`.
Q49beginner`transition` vs `@keyframes` animation—when use each?
Transitions interpolate between start/end states on property changes—hover, class toggles. Keyframes define multi-step sequences—loaders, entrances, looping. Transitions need trigger; animations run on their own with `animation-name`. Both should respect `prefers-reduced-motion`.
Q50advancedWhat is `will-change` and when is it dangerous?
Hints browser to optimize upcoming changes (often promoting layers). Overuse causes excessive memory and slower initial paint. Apply shortly before animation, remove after. Don't blanket `will-change: transform` on everything—profile first.
Q51intermediateImplement accessible motion reduction.
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; } } or disable nonessential motion selectively. Never block essential feedback—focus rings must remain visible.
Q52intermediateExplain `transform` and `opacity` as animation-friendly properties.
They typically composite on GPU without triggering layout/paint—smooth 60fps when animating. Animating `width`, `height`, `top`, `left` triggers layout and janks. Use `transform: translateX()` instead of `left` for slides.
Q53advancedScenario: Accordion height animation without JavaScript?
Pure CSS: `grid-template-rows: 0fr` to `1fr` transition with inner `overflow: hidden`, or `max-height` hack (less precise). Modern approach: `@starting-style` for entry animations. Ensure content remains accessible when collapsed—use `hidden` attribute or `aria-expanded`.
Q54intermediate`animation-fill-mode: forwards` purpose?
Retains styles from last keyframe after animation ends—e.g., fade-in stays opaque. Without it, element snaps back to pre-animation state. Pair with `animation-iteration-count: 1` for one-shot entrances.
Q55intermediateHow does `cubic-bezier` easing affect UX?
Easing conveys weight and urgency—`ease-out` for entrances (fast start), `ease-in` for exits. Custom beziers mimic Material motion. Linear feels robotic for UI. Match duration to distance: small moves 150–200ms, large modals 250–350ms.
Q56advancedView Transitions API role in SPA page changes?
Document API captures old/new snapshots for cross-fade or shared-element morphs between DOM updates. Frameworks integrate for route transitions. Progressive enhancement—fallback is instant navigation without animation.
Q57intermediateCSS custom properties vs Sass variables—key runtime difference?
CSS variables (`--color: blue`) live in the cascade, inherit, and change via JS or media queries at runtime. Sass variables compile away—static per build. Theme switching on the client needs CSS variables; build-time theming can use either.
Q58intermediateScope theme tokens on `:root` vs component level.
Global design tokens on `:root` (`--color-primary`) enable consistency. Component-scoped overrides on `.dark-theme { --color-primary: ... }` localize variants. Avoid deep nesting that obscures token source—document in design system.
Q59advanced`:has()` selector—real-world use cases?
Parent selector: `form:has(:invalid) { border-color: red }` styles form when any child invalid—previously impossible in CSS alone. Card with image: `.card:has(img) { padding-top: 0 }`. Check browser support and performance on large DOMs.
Q60intermediateNative CSS nesting—benefits and pitfalls?
Nesting mirrors Sass ergonomics without preprocessor—`&` references parent. Risk: overly deep nesting raises specificity like old Sass habits. Flatten where possible; nest for pseudo-states (`&:hover`) not entire DOM paths.
Q61advanced`color-mix()` practical example.
`color: color-mix(in srgb, var(--brand) 70%, white)` tints brand for backgrounds without manual hex math. Supports accessible hover states derived from base token. Growing support—provide fallback hex for older browsers.
Q62intermediateCompare `light-dark()` and `prefers-color-scheme` theming.
`light-dark(light-val, dark-val)` picks based on user color scheme in supported browsers—concise token definition. Classic approach: separate blocks under `@media (prefers-color-scheme: dark)`. Also support manual toggle via `[data-theme=dark]` class overriding variables.
Q63advanced`@property` for animating custom properties?
Registers typed custom properties with syntax and inheritance—enables interpolating `--progress` in animations. Useful for gradient loaders and ring charts. Requires explicit `@property` registration block.
Q64advancedCascade layers with design tokens—pattern?
@layer tokens, base, components; import tokens first, reset in base, components last. Utilities layer can trump components without `!important` wars. Document layer order in team style guide.
Q65beginnerEstablish a type scale with `rem`—example setup.
Set `html { font-size: 100%; }` respecting user prefs, then `body { font-size: 1rem; line-height: 1.5; }`, headings `h1 { font-size: 2.25rem; }` stepping down. Use modular scale (1.25 ratio) for harmony. Avoid px-only typography that ignores user zoom.
Q66intermediate`line-height` unitless vs em—why prefer unitless?
Unitless `line-height: 1.5` multiplies element's font-size and inherits as multiplier—children scale correctly. `em`/`px` values inherit computed length and compound oddly in nested elements. Use unitless for body copy defaults.
Q67beginnerFont stack best practice for system UI.
`font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;` avoids FOIT/FOUT from webfonts while matching OS feel. Add explicit webfont with `font-display: swap` only when brand requires custom type.
Q68intermediateScenario: Long words break layout in narrow column.
`overflow-wrap: break-word` or `word-break: break-word` allows breaks inside long URLs/tokens. `hyphens: auto` with `lang` attribute improves prose. Combine with `min-width: 0` on flex/grid children.
Q69advancedOpenType features in CSS—`font-variant-numeric`.
`font-variant-numeric: tabular-nums` aligns digits in tables; `oldstyle-nums` for prose. Financial dashboards benefit from tabular lining figures. Check font file supports feature.
Q70intermediateVertical rhythm with margin collapsing on headings.
Headings often have large top/bottom margins that collapse with adjacent paragraphs—use consistent spacing scale (`margin-block: 0 1rem`) and `:where()` resets. Component libraries sometimes zero heading margins and apply spacing on containers.
Q71advanced`text-wrap: balance` for headlines?
Balances line lengths on multi-line headings—reduces orphans on marketing hero text. Progressive enhancement; unsupported browsers ignore. Not for long paragraphs—use `pretty` variant where supported for body.
Q72intermediateContrast and font weight at small sizes.
Thin weights (300) fail WCAG on light backgrounds at 12–14px—bump weight or size. Anti-aliasing differs macOS vs Windows; test real devices. Variable fonts allow fine weight tuning per breakpoint.
Q73beginner`::before` vs `::after`—constraints?
Both generate pseudo-elements requiring `content` (even `content: ''` for decorative boxes). Element may have one each—they're ordered before/after inner content. Cannot add extra pseudo-elements without real DOM nodes.
Q74beginnerCreate decorative divider with `::after`.
`.section-title::after { content: ''; display: block; width: 3rem; height: 3px; background: var(--accent); margin-top: 0.5rem; }` adds visual flair without extra markup. Ensure title text remains in accessibility tree—not replaced by pseudo content alone.
Q75intermediate`::placeholder` styling caveats.
Vendor prefixes historically needed; low contrast placeholders fail a11y if too faint—keep readable but distinguish from input text. Placeholder is not a label—always use `<label>` or `aria-label`.
Q76intermediateCustom list bullets with `::marker`.
`li::marker { color: var(--accent); font-weight: bold; }` styles native markers without losing list semantics. Prefer over fake bullets in `<span>` that break screen reader list announcements.
Q77intermediateScenario: Icon before link using CSS only.
`.external::after { content: '↗'; margin-inline-start: 0.25em; }` supplements text—add `aria-label` if icon conveys meaning alone. Decorative icons should be `aria-hidden` in markup approach; pseudo-elements aren't easily hidden from AT.
Q78beginner`::selection` styling.
`::selection { background: var(--highlight); color: var(--on-highlight); }` brands text highlight. Ensure sufficient contrast for selected text. Some browsers limit which properties apply.
Q79intermediateOverlay gradient on image with pseudo-element.
`.hero::after { content: ''; position: absolute; inset: 0; background: linear-gradient(transparent, rgba(0,0,0,.6)); }` with positioned parent improves text contrast over photos. Parent needs `position: relative`.
Q80beginnerDouble colon vs single colon legacy?
CSS3 pseudo-elements use `::`; pseudo-classes use `:`. Old IE accepted single colon for `:before`—modern validators prefer `::`. Browsers accept both for compatibility on pseudo-elements.
Q81advancedCritical CSS strategy for fast first paint.
Inline above-the-fold CSS in `<head>`, defer full stylesheet, eliminate render-blocking unused rules. Tools: Critters, coverage analysis. Measure LCP element—hero image and its CSS matter most.
Q82advancedHow does `content-visibility: auto` improve scroll performance?
Skips rendering off-screen subtrees until near viewport—big lists and feeds benefit. Pair with `contain-intrinsic-size` to preserve scroll height placeholder. Test accessibility—hidden content may delay find-in-page until scrolled into view.
Q83intermediateFocus visible styling best practice.
Use `:focus-visible` not bare `:focus`—mouse clicks won't show ring, keyboard will. Never `outline: none` without replacement. Example matches brand color with 3:1 contrast against background.
Q84beginnerColor contrast checking for WCAG AA.
Normal text needs 4.5:1 contrast ratio; large text 3:1. UI components and graphics 3:1. Don't rely on color alone for errors—add icon and text. Tools: DevTools contrast panel, axe.
Q85intermediateScenario: Custom checkbox styling—accessibility requirements?
Hide native input visually but keep focusable, style label/`::after`, maintain `:focus-visible` on input. Prefer native `<input type=checkbox>` styled over div-only toggles without roles and keyboard support.
Q86intermediateFont loading: `font-display: swap` tradeoffs?
Shows fallback immediately, swaps when webfont loads—avoids invisible text (FOIT) but causes FOUT/layout shift. Mitigate with size-adjust fallback fonts. Preload critical fonts: `<link rel=preload as=font crossorigin>`.
Q87intermediateReduce CSS bundle size techniques.
Purge unused utilities (Tailwind JIT), split per route, avoid duplicate resets, use native features over polyfill CSS, analyze with coverage tab. Component libraries: import modules not whole package where possible.
Q88beginnerScreen reader only text pattern `.sr-only`.
Visually hide but keep accessible: clip or modern utility with `position: absolute; width: 1px; height: 1px; overflow: hidden`. Use for supplementary labels, not to hide required visible text—that violates WCAG.
Q89intermediateScenario: Two-column layout collapses to one on mobile without duplicate HTML.
CSS Grid: `grid-template-columns: 1fr 1fr` base, `@media (max-width: 768px) { grid-template-columns: 1fr }`. Or flex `flex-wrap: wrap` with `flex: 1 1 300px` min basis. Order via `order` only if tab order still logical.
Q90intermediateScenario: Fixed navbar overlaps anchor link targets.
Set `scroll-margin-top` on heading anchors equal to nav height: `h2[id] { scroll-margin-top: 80px; }`. HTML `scroll-padding-top` on `html` element also works globally for all fragment navigation.
Q91advancedScenario: Dark mode flash on page load in SPA.
Inline script in head reads `localStorage`/prefers-color-scheme and sets `data-theme` before paint; CSS variables switch immediately. Avoid async theme CSS fetch for initial mode. SSR should emit correct class on html element.
Q92intermediateScenario: Truncate multi-line text to 3 lines with ellipsis.
`-webkit-line-clamp: 3; display: -webkit-box; -webkit-box-orient: vertical; overflow: hidden;` with standard `line-clamp` emerging. Provide expand control or link to full text—clamped content is hidden from AT unless exposed.
Q93beginnerScenario: Equal-height cards with variable content.
Flex/grid stretch: parent `align-items: stretch` (default in grid), cards `display: flex; flex-direction: column`, push footer with `margin-top: auto` on card actions. Avoid fixed heights that clip content.
Q94advancedZ-index war in modal, dropdown, and toast—structure?
Define scale in tokens: dropdown 100, sticky header 200, modal 300, toast 400. Each creates isolation context at root portal level. Never arbitrary 99999—document layers. React portals to `#modal-root` simplify stacking.
Q95intermediateScenario: Style third-party widget you cannot markup-change.
Override with specific selectors carefully, CSS variables if widget exposes them, shadow parts (`::part`) if web component. `!important` last resort. iframe widgets cannot be styled—ask vendor theme API.
Q96intermediateWhen is inline style acceptable in React?
Dynamic values computed at runtime (position from drag, chart dimensions) suit inline styles or CSS variables set on element. Static presentation belongs in classes/stylesheets for caching and pseudo-states. `style={{ '--x': value }}` bridges to CSS.
Q97intermediateCompare table layout vs CSS grid for a pricing page.
Semantic `<table>` if comparing plan features row-by-row—screen readers expect table navigation. Marketing layout-heavy pages often use grid for visual design but should preserve accessible feature lists.
Q98intermediateHow implement responsive spacing scale with custom properties?
Define `--space-sm: 0.5rem; --space-md: 1rem;` on `:root`, override at breakpoints: `@media (min-width: 768px) { :root { --space-md: 1.25rem; } }`. Components use `padding: var(--space-md)`—single source of truth.
Q99advancedScenario: Print hides navigation but keeps URLs visible.
@media print { nav, .sidebar { display: none; } a[href^='http']::after { content: ' (' attr(href) ')'; font-size: 0.85em; } } Test pagination and page breaks on long tables.
Q100intermediateFloat-based layout legacy—why still asked?
Maintaining older codebases and understanding clearfix (`::after { content: ''; display: table; clear: both; }`) matters. Floats were for text wrap around images before flex/grid. Modern layouts should not use floats for columns.
Q101beginnerHow does `object-fit` control replaced elements?
`object-fit: cover` fills box cropping; `contain` letterboxes preserving aspect ratio. Pair with fixed dimensions on images/video containers. `object-position` controls crop focal point—useful for avatar thumbnails.
Q102advancedWhat are CSS container queries?
Container queries style an element based on its container's size (`@container`), not the viewport. Mark a parent with `container-type: inline-size` (and optional `container-name`), then `@container (min-width: 400px) { ... }`. Ideal for card components reused in sidebars vs main columns. Complements media queries rather than replacing them.
Q103advancedExplain `@layer` and cascade layers.
`@layer` groups rules into named layers with controlled priority independent of specificity wars. Later layers win over earlier ones (unless `!important` reverses layer order). Typical stack: reset → tokens → base → components → utilities. `!important` in earlier layers beats normal declarations in later layers—know the flip. Reduces specificity hacks in design systems.
Q104intermediateWhat is the `:has()` selector?
`:has()` is a parent/relational selector: `card:has(img)` styles cards containing images; `label:has(:checked)` styles checked states. Powerful for form UX and conditional layout without JS. Watch performance on very broad selectors; prefer scoped usage. Now widely supported in current browsers.
Q105intermediateHow does CSS scroll-snap work?
On the scroller: `scroll-snap-type: x mandatory` (or `y`/`both`, `proximity`). On children: `scroll-snap-align: start|center|end`. Creates carousel-like snapping without JS. Mind accessibility: honor `prefers-reduced-motion`, ensure keyboard scroll still works, and avoid trapping users mid-snap on small steps.
Q106advanced`position: sticky` pitfalls?
Sticky fails when any ancestor has `overflow: hidden/auto/scroll` (creates a scrollport that clips sticking), when no room to stick remains, or when missing a threshold (`top`/`bottom`). Parent height must exceed sticky element. Flex/grid children sometimes need `align-self: flex-start`. Debug by checking ancestor overflow first.
Q107intermediateExplain `clamp()` for fluid typography.
`font-size: clamp(1rem, 2.5vw, 2rem)` sets min, preferred, max. Preferred often uses `vw`/`vi` plus a rem bias (`clamp(1rem, 0.5rem + 1vw, 2rem)`). Avoid pure viewport units alone (a11y zoom issues). Pair with container queries for component-local fluid type when appropriate.
Q108intermediateWhat are CSS logical properties?
Logical properties use flow-relative directions: `margin-inline`, `padding-block`, `inset-inline-start`, `border-block-end` instead of left/right/top/bottom. They flip correctly for RTL (`dir=rtl`) and writing modes. Prefer them in multilingual UIs and design systems.
Q109beginnerHow does `aspect-ratio` help layout?
`aspect-ratio: 16 / 9` reserves height from width (or vice versa), replacing old padding-top hacks. Works with replaced elements and boxes. Combine with `object-fit` for media. Great for preventing CLS on video embeds and cards.
Q110advancedWhen should you use `will-change`?
`will-change` hints the browser to prepare layers for upcoming transforms/opacity. Overuse wastes memory and can hurt performance. Apply sparingly just before an animation and remove afterward, or limit to known heavy interactions. Prefer animating `transform`/`opacity` first; don't cargo-cult `will-change` on everything.
Q111advancedExplain the CSS `contain` property.
`contain: layout style paint` (or `content`/`strict`) tells the browser subtree changes are isolated, enabling optimization. `content-visibility: auto` skips rendering offscreen content. Useful for long lists/feeds. Incorrect containment can clip or break sticky/fixed expectations—test carefully.
Q112intermediateCSS nesting — how does it work?
Native nesting: `.card { & .title { } &:hover { } }` mirrors Sass. The `&` represents the parent selector. Helps colocate component rules without preprocessors. Keep nesting shallow for readability and specificity control; combine with `@layer` in systems.
Q113advancedWhat is CSS subgrid?
`display: grid` children can opt into `grid-template-rows/columns: subgrid` to inherit the parent's track sizing, aligning nested items to the outer grid. Solves card rows where titles/footers must align across cards. Browser support is modern-evergreen; provide sensible fallbacks if needed.
Q114intermediateAnimation performance best practices?
Prefer compositor-friendly properties: `transform` and `opacity`. Avoid animating `width`/`height`/`top`/`left` (layout thrash) when possible. Use `transform: translateZ(0)` sparingly; measure with Performance panel. Respect `prefers-reduced-motion: reduce` by disabling non-essential motion.
Q115intermediateHow do you honor `prefers-reduced-motion`?
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; } } — or selectively disable decorative motion. Keep essential UI state changes; remove parallax/autoplay carousels.
Q116intermediateWhat belongs in print CSS?
@media print { hide nav/ads, expand collapsed content, use black text, avoid pure white backgrounds if ink is a concern, set link URLs with `a[href]::after { content: " (" attr(href) ")"; }` carefully, control page breaks with `break-inside: avoid` on cards }. Test print preview. Provide a clean article layout.
Q117advancedCascade layers order vs specificity — summarize.
Unlayered styles beat layered styles. Among layers, later declared layers win for normal declarations. Specificity still applies within a layer. `!important` flips layer comparison. Transitioning a codebase: put legacy in an early `@layer legacy` so new layered code can override without ballooning specificity.
Q118beginner`min()`, `max()`, and `clamp()` together?
`width: min(100%, 40rem)` caps width. `height: max(12rem, 30vh)` floors height. `clamp(min, preferred, max)` is sugar for nested min/max. Useful for fluid grids without many breakpoints.
Q119beginnerWhat is `object-fit` vs `object-position`?
`object-fit: cover|contain|fill` controls how replaced content fits its box; `object-position` anchors the focal point. Essential for avatar crops and hero images in fixed frames without distortion.
Q120intermediateExplain `scroll-margin` / `scroll-padding`.
Offset scroll targets for sticky headers: `html { scroll-padding-top: 4rem; }` or `scroll-margin-top` on headings so in-page anchors aren't hidden under fixed nav. Small detail, big UX win.
Q121beginner`gap` in flexbox vs grid?
`gap` sets gutters between items in both flex and grid without margin hacks. Prefer gap over margins for equal spacing; margins still useful for asymmetric spacing. Older Safari needed prefixes historically—modern evergreen is fine.
Q122beginnerWhat does `:focus-visible` solve?
Shows focus rings for keyboard users while avoiding rings on mouse click when the UA determines appropriate. Prefer `:focus-visible` over removing all outlines. Never `outline: none` without a visible replacement.
Q123intermediateExplain `@supports` feature queries.
@supports (display: grid) { ... } progressively enhances. Also `@supports not (...)`. Use for container queries, subgrid, or `backdrop-filter`. Prefer progressive enhancement over UA sniffing.
Q124beginnerWhat is the difference between `em` and `rem`?
`em` is relative to the element's font-size (compounding with nesting); `rem` is relative to the root. Prefer `rem` for spacing/type scales; `em` for component-local scaling (buttons padding relative to button text).
Q125advancedHow do you prevent layout shift from web fonts?
Use `font-display: swap` or `optional`, preload critical fonts, match fallback metrics (`size-adjust`, `ascent-override` in `@font-face`), and reserve space. Variable fonts can reduce file count.
Q126advanced`position: fixed` inside a transformed ancestor?
A `transform`/`filter`/`perspective` on an ancestor creates a containing block; `fixed` then behaves like absolute relative to that ancestor—not the viewport. Common modal bug. Move the fixed element outside transformed parents or use the top layer (`dialog`/`popover`).
Q127advancedExplain CSS `color-mix()` briefly.
`color-mix(in srgb, var(--brand) 40%, white)` mixes colors in a color space. Useful for hover states and theme tokens without preprocessors. Support is modern; provide solid fallbacks when needed.
Q128advancedWhat are cascade `@layer` vs `!important` wars?
Important declarations compare layers in reverse order. Escalating `!important` across layers becomes hard to maintain. Prefer layer order and lower specificity; reserve `!important` for utilities/third-party overrides with clear convention.
Q129intermediateGrid `minmax()` and `auto-fit`/`auto-fill`?
`grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr))` builds responsive columns without breakpoints. `auto-fill` keeps empty tracks; `auto-fit` collapses empty ones. Classic interview responsive grid pattern.
Q130advancedWhat is `content-visibility: auto`?
Skips rendering work for offscreen content, improving initial load for long pages. May need `contain-intrinsic-size` to avoid scrollbar jumps. Related to CSS containment family.
Q131intermediateHow do logical properties map `left`/`right`?
In horizontal TB LTR: `inline-start`≈left, `inline-end`≈right, `block-start`≈top, `block-end`≈bottom. In RTL, inline-start becomes the right side. Use for padding/margin/inset/border-radius corners carefully (`border-start-start-radius`).
Q132advancedSticky + overflow + flex header pattern issues?
A common failure: sticky nav inside a flex column with `overflow:auto` on the wrong element. Make the scrolling container explicit and put sticky inside that scrollport with `top:0`. Verify no parent `overflow:hidden`.
Q133beginnerWhat does `@media (prefers-color-scheme: dark)` do?
Matches OS/browser dark preference. Pair with CSS variables for themes; still offer an in-app toggle that sets `data-theme` because users override OS sometimes. Don't rely only on color—check contrast.
Q134advancedExplain `overflow: clip` vs `hidden`.
`clip` visually clips without creating a scroll container and may not programmatically scroll; `hidden` still establishes a scrollport in some senses. Useful when you want clipping without breaking sticky as often—still verify per browser.
Q135intermediateAnimation `transform` vs `translate` property?
Individual transform properties (`translate`, `rotate`, `scale`) compose more cleanly than one `transform` string and are easier to animate independently. Still compositor-friendly. Fall back to `transform` where needed.
Q136beginnerHow do you structure print styles for a resume page?
Hide chrome, force background where needed with print-color-adjust, ensure links are readable, avoid cutting cards mid-box (`break-inside: avoid`), set margins via `@page`. Provide a 'Print' preview test in QA.
Q137intermediateWhat are Core Web Vitals?
Google's key UX metrics: LCP (loading), INP (interactivity), and CLS (visual stability). They influence SEO and real-user experience. Measure in lab (Lighthouse) and field (CrUX/RUM). Optimize with evidence, not folklore.
Q138intermediateExplain LCP and how to improve it.
Largest Contentful Paint times when the main content element becomes visible. Improve with optimized hero images (`priority`/preload), faster servers, critical CSS, and avoiding late-loading fonts blocking text. Identify the LCP element in DevTools. Often an image or large text block.
Q139advancedWhat is INP?
Interaction to Next Paint measures responsiveness across interactions—replacing FID as a Core Web Vital. Long tasks, heavy JS, and main-thread congestion hurt INP. Break up work, debounce, and defer non-critical scripts. Profile with performance timelines.
Q140intermediateExplain CLS and common causes.
Cumulative Layout Shift scores unexpected layout movement. Causes: images without dimensions, late-loading ads/fonts, dynamic injection above existing content. Reserve space with width/height or aspect-ratio; avoid inserting banners atop content. Stable UI feels higher quality.
Q141beginnerHow do you use Lighthouse effectively?
Run in private/incognito, note lab vs field differences, and treat scores as diagnostics with specific audits—not vanity. Re-test after each fix. Focus on opportunities affecting Web Vitals. Automate in CI carefully for regression signals.
Q142advancedCritical CSS strategy?
Inline or prioritize CSS needed for above-the-fold content; defer the rest. Reduces render-blocking. Tooling can extract critical paths. Overdoing inlining hurts caching—balance carefully.
Q143intermediateFont loading and CLS/LCP?
FOIT/FOUT cause shifts and delayed text. Use `font-display: swap/optional`, preload key fonts, and match fallback metrics (`size-adjust`). Subset fonts. Typography is a Web Vitals issue, not just aesthetics.
Q144beginnerHow do images affect LCP?
Unoptimized large heroes dominate LCP. Use modern formats, correct dimensions, responsive `srcset`, and CDN. Preload the LCP image when known. Lazy-load below-the-fold only—never lazy the LCP image.
Q145intermediateThird-party scripts impact on INP?
Tags for analytics/chat can monopolize the main thread. Load async/defer, delay until interaction, or self-host critical parts. Audit with coverage/performance panels. Negotiate which tags are mandatory.
Q146intermediateLab vs field metrics?
Lab (Lighthouse) is controlled simulation; field (RUM/CrUX) is real users' devices/networks. Optimize for field outcomes; use lab to debug. Disagreements are common—trust field for SEO thresholds. Instrument your own RUM when possible.
Q147advancedCSS containment for performance?
`contain` hints the browser about subtree isolation to limit layout/paint scope. Useful for complex widgets. Misuse can break layouts. Advanced optimization tool—profile first.
Q148advancedContent-visibility awareness?
`content-visibility: auto` skips rendering offscreen content to speed initial load. Needs careful sizing (`contain-intrinsic-size`) to avoid CLS. Powerful for long pages. Progressive enhancement mindset.
Q149advancedHow does hydration JS affect INP/LCP?
Large React bundles delay interactivity even if HTML appeared fast via SSR. Code-split, reduce client components, and defer non-critical hydration. SSR alone does not guarantee good INP. Measure TTI/INP after hydration strategies.
Q150beginnerSkeleton screens vs CLS?
Skeletons reserve space and improve perceived performance if dimensions match final content. Mismatched skeletons still shift. Prefer stable placeholders. UX pattern with measurable CLS impact.
Q151beginnerWhat Lighthouse accessibility audits catch?
Contrast issues, missing names, heading order problems—not complete a11y assurance. Still useful CI signal. Pair with manual keyboard/screen-reader testing. Performance panel ≠ accessibility panel—run both.
Q152intermediateHTTP caching of CSS/JS for Web Vitals?
Long-cache hashed assets speed repeat visits; avoid huge uncacheable bundles. Critical for LCP on return users. Pair with CDN. First visit still needs small critical path.
Q153intermediateMain thread long tasks—what are they?
JS tasks over ~50ms block input/paint, harming INP. Break work with scheduling/`requestIdleCallback`, web workers for heavy compute. Performance panel highlights long tasks. Core responsiveness concept.
Q154beginnerResponsive images to save LCP on mobile?
Serve smaller resolutions to narrow viewports via `srcset`/`sizes` so mobile LCP images weigh less. Art direction with `<picture>` when crops differ. Mobile field data often dominates CWV. Test on throttled networks.
Q155advancedHow do layout thrashing and forced sync layout hurt?
Reading layout then writing styles in loops forces recalculation—jank. Batch DOM reads/writes. Prefer transforms/opacity for animations. Shows up as poor INP/FPS. Classic performance interview topic.
Q156intermediateSummarize a Web Vitals optimization workflow.
Measure field baseline → identify LCP/INP/CLS culprits in lab → ship fixes with budgets → re-measure. Document regressions in CI. Prioritize user journeys that matter for SEO/conversion. Continuous, not one-off.
JavaScript
246 questions
Q1beginnerDifference between var, let, and const?
`var` is function-scoped, hoisted as `undefined`, can be redeclared. `let`/`const` are block-scoped, TDZ until declared, cannot redeclare in same scope. `const` cannot be reassigned (object properties still mutable). Prefer `const` by default, `let` when reassigning, avoid `var`.
Q2beginnerWhat is hoisting in JavaScript?
Declarations are processed before execution. `var` → initialized undefined; function declarations fully hoisted (callable earlier); `let`/`const` hoisted but TDZ; function expressions follow their variable rules. Interview tip: distinguish declaration vs initialization.
Q3intermediatecall vs apply vs bind?
`fn.call(thisArg, a, b)` invokes immediately with individual args. `fn.apply(thisArg, [a,b])` invokes with array of args. `fn.bind(thisArg, a)` returns a new function with bound `this` (and optional preset args) without calling yet. All set `this` explicitly.
Q4beginnerArrow functions vs regular functions?
Arrows have lexical `this`/`arguments`/`super` (no own), cannot be `new`'d as constructors, no `prototype`, concise syntax. Regular functions get `this` from call site. Use arrows for callbacks needing outer `this`; methods needing dynamic `this` often need regular functions or bind.
Q5beginnermap vs filter vs reduce — with examples?
`map` transforms each item → same-length array: `[1,2].map(x=>x*2)` → `[2,4]`. `filter` keeps items passing test: `[1,2,3].filter(x=>x>1)` → `[2,3]`. `reduce` accumulates: `[1,2,3].reduce((a,b)=>a+b,0)` → `6`. Prefer these over mutating loops for clarity.
Q6beginnerforEach vs map — when to use which?
`forEach` runs side effects, returns `undefined`, cannot chain. `map` returns a new array of results. Use `map` when you need transformed data; `forEach` only for intentional side effects (logging, DOM). Neither breaks on `return` like `for` loops.
Q7beginnerfind, findIndex, some, every, includes?
`find` → first matching element or undefined. `findIndex` → index or -1. `some` → true if any match. `every` → true if all match. `includes` → boolean membership (NaN handled correctly unlike indexOf). Short-circuit when possible.
Q8beginnerWhat does Array.isArray do and why not typeof?
`typeof []` is `'object'` — useless to detect arrays. `Array.isArray(x)` is the reliable check (works across iframes better than `instanceof Array`). Always use it in validation.
Q9beginnerPass by value vs pass by reference in JS?
Primitives (number, string, boolean, null, undefined, symbol, bigint) are copied by value. Objects/arrays/functions are referenced — assignment copies the reference. Mutating a property affects all aliases; reassigning the parameter does not change the caller's binding.
Q10intermediateShallow copy vs deep copy in JavaScript?
Shallow: `{...obj}`, `Object.assign`, `[...arr]` — nested objects still shared. Deep: `structuredClone(obj)` (modern), or careful recursion; `JSON.parse(JSON.stringify)` loses Date/Map/undefined/functions. Know when shallow is enough (immutable state updates).
Q11beginnerRest vs spread syntax?
Spread expands: `fn(...arr)`, `[...a,...b]`, `{...o}`. Rest collects remaining: `function(a,...rest)`, `const {x,...rest}=obj`. Same `...` token, opposite direction. Rest must be last parameter.
Q12beginnerDefault function parameters?
`function greet(name='Guest'){}` — default used when argument is `undefined` (not null). Evaluated at call time; can reference prior params: `function f(a,b=a)`. Avoid mutable object defaults shared across calls — use `= undefined` then create inside.
Q13beginnerTemplate literals?
Backticks allow `${expr}` interpolation and multi-line strings. Tagged templates: `tag`hello ${name}`` for custom processing (i18n, sanitization). Prefer over string concatenation for readability.
Q14intermediateWhat is the arguments object? Why prefer rest?
`arguments` is array-like (not real array) available in non-arrow functions. Rest `...args` is a real Array, clearer, works with arrows. In strict mode `arguments` doesn't alias parameters the same way. Prefer rest in modern code.
Q15beginnertypeof operator results for common values?
`typeof 1` → 'number', `'a'` → 'string', `true` → 'boolean', `undefined` → 'undefined', `function(){}` → 'function', `{}`/`[]`/`null` → 'object', `10n` → 'bigint', `Symbol()` → 'symbol'. Remember null quirk.
Q16beginnerinstanceof operator?
`obj instanceof Constructor` checks if Constructor.prototype is in obj's prototype chain. Fails across realms/iframes for builtins — prefer `Array.isArray`. Useful for custom classes: `err instanceof Error`.
Q17beginnerObject.keys vs Object.values vs Object.entries?
`keys` → enumerable own string keys. `values` → values. `entries` → `[key,value]` pairs — great for `Object.fromEntries`, Map conversion, looping. Symbol keys excluded (use `getOwnPropertySymbols`).
Q18intermediateObject.freeze vs Object.seal vs Object.preventExtensions?
`preventExtensions`: no new props. `seal`: + no delete, existing configurable→false. `freeze`: + values read-only (shallow). Nested objects still mutable unless deep-frozen. `Object.isFrozen` to check.
Q19beginnerJSON.stringify and JSON.parse caveats?
stringify drops `undefined`/functions, converts Date to ISO string, fails on circular refs (throws). parse revives only JSON types — Dates become strings unless reviver. Always try/catch parse of untrusted input.
Q20beginnerString common methods interviewers ask?
`includes`, `startsWith`, `endsWith`, `slice`, `substring`, `split`, `trim`, `replace`/`replaceAll`, `toLowerCase`, `padStart`. Strings immutable — methods return new strings. Prefer `slice` over `substr` (deprecated).
Q21beginnerHow do you reverse a string in JS?
`[...str].reverse().join('')` or `str.split('').reverse().join('')`. Careful: `split('')` breaks some Unicode; spread/Array.from better for code points. Time/space O(n).
Q22beginnersetTimeout vs setInterval — cleanup?
`setTimeout` once after delay; `setInterval` repeats. Always `clearTimeout`/`clearInterval` on cleanup (React useEffect return). Prefer recursive setTimeout when next tick should wait for previous work to finish.
Q23beginnerDOM: querySelector vs getElementById?
`getElementById` fastest for id. `querySelector`/`querySelectorAll` use CSS selectors — All returns static NodeList. Prefer querySelector for flexibility. Cache results; avoid querying in hot loops.
Q24beginnercreateElement and appendChild vs innerHTML?
`createElement` + `textContent`/`append` is safer against XSS. `innerHTML` parses HTML — dangerous with user input. Prefer DOM APIs or frameworks that escape by default (React).
Q25beginnertextContent vs innerText vs innerHTML?
`textContent` raw text, fast, no style computation. `innerText` respects CSS visibility/layout (slower). `innerHTML` HTML markup. For setting user text use textContent.
Q26beginnerevent.preventDefault vs stopPropagation?
`preventDefault` stops browser default (link navigate, form submit). `stopPropagation` stops bubbling/capturing to other listeners. `stopImmediatePropagation` also blocks other listeners on same element. Don't confuse them.
Q27beginnerWhat is event.target vs event.currentTarget?
`target` is the deepest element that originated the event. `currentTarget` is the element whose listener is running (useful in delegation). In React synthetic events same idea.
Q28intermediateHow does == coerce null and undefined?
`null == undefined` is true; both only loosely equal each other among primitives in that sense. `null == 0` is false. Prefer `===` or explicit `value == null` check for both nullish.
Q29intermediateWhat is Object.is?
Same-value equality: `Object.is(NaN,NaN)` true, `Object.is(+0,-0)` false — unlike `===`. Rarely needed daily; useful for edge-case equality and some React internals historically.
Q30intermediatePromise.race vs Promise.any?
`race`: settles with first fulfilled OR rejected. `any`: fulfills with first fulfillment; rejects only if all reject (AggregateError). Use race for timeouts; any for first success among mirrors.
Q31beginnerWhat does promise.finally do?
Runs when promise settles (fulfill or reject) for cleanup; does not change fulfillment value (unless it throws/rejects). Good for hiding loaders: `fetch().finally(()=>setLoading(false))`.
Q32beginnerHow to convert callback API to Promise?
`new Promise((resolve,reject)=> fs.readFile(path,(e,d)=> e?reject(e):resolve(d)))` or `util.promisify`. Always handle both success and error paths.
Q33beginnerWhat is a pure function?
Same inputs → same output; no side effects (no mutate external state, I/O, Date.now unless injected). Easier to test and reason. React render ideally pure given props/state.
Q34intermediateImmurability pattern: update nested object?
`{...state, user:{...state.user, name:'A'}}` — copy each level you change. Libraries: Immer. Required for React state and Redux.
Q35beginnerHow does switch work? fall-through?
Matches with `===`. Without `break`/`return`, execution falls through to next case — intentional sometimes, often a bug. Prefer early return in functions. `default` handles unmatched.
Q36beginnertry / catch / finally?
`try` risky code; `catch` handles thrown errors; `finally` always runs (cleanup) even if return in try/catch. Async: use try/catch with await, or .catch on promises. finally still runs on return.
Q37intermediateHow to create and throw custom errors?
`class ValidationError extends Error { constructor(msg){ super(msg); this.name='ValidationError'; } }` then `throw new ValidationError('bad')`. Catch by `instanceof`. Keeps stack traces.
Q38intermediateDate basics — common pitfalls?
`new Date('YYYY-MM-DD')` parses as UTC in ES5; local parsing varies. Prefer explicit `new Date(y, mIndex, d)` or libraries. Months 0-based. `Date.now()` ms timestamp. Don't mutate shared Date without cloning.
Q39beginnerMath.max / Math.min with arrays?
`Math.max(...arr)` spreads; huge arrays can exceed arg limit — use `arr.reduce((a,b)=>Math.max(a,b), -Infinity)` instead. Interview coding often forbids Math.max for teaching loops.
Q40beginnerWhat is strict mode?
`'use strict'` or ES modules (always strict): throws on silent errors (assign undeclared), `this` is undefined in bare calls, no `with`, duplicate params disallowed. Safer defaults.
Q41beginnerDifference between slice and splice?
`slice(start,end)` non-mutating copy/substring of array. `splice(start,deleteCount,...items)` mutates — remove/insert. React: prefer slice/toSpliced or filter to avoid mutating state.
Q42beginnerHow to check if property exists on object?
`'key' in obj` includes prototype chain. `Object.hasOwn(obj,'key')` or `obj.hasOwnProperty` for own only. `obj.key !== undefined` fails if value is undefined intentionally.
Q43beginnerOptional catch binding?
`try {..} catch {..}` without binding if unused (ES2019). Prefer naming when logging: `catch (err)`.
Q44advancedWhat is a generator function?
`function*` with `yield` pauses and returns iterator. Lazy sequences, custom iterables. `yield*` delegates. Async generators `async function*` for streams. Redux-Saga historically used generators.
Q45intermediateIterable protocol briefly?
Object is iterable if `[Symbol.iterator]()` returns iterator with `next()` → `{value, done}`. Enables `for...of`, spread, destructuring. Arrays, Maps, Sets, strings are iterable.
Q46beginnerHow does for...of differ from for...in on arrays?
`for...of` values; `for...in` keys (and inherited enumerable) — avoid for...in on arrays. Use `Object.keys`/`entries` for objects.
Q47intermediateWhat is hoisting of function declarations vs expressions?
`function foo(){}` fully hoisted — call before line OK. `const foo = function(){}` or arrow — TDZ/not initialized; call before throws. `var foo = function(){}` — foo is undefined until line.
Q48beginnerIIFE modern replacement?
ES modules and block `{ const x = 1 }` give scope. Async IIFE still used: `(async ()=>{ await init(); })()`. Prefer modules for app structure.
Q49advancedHow to deep freeze an object?
Recursively `Object.freeze` own properties that are objects. Or use libraries. Shallow freeze alone is incomplete for nested state.
Q50intermediateNullish assignment ??= and logical assignment?
`a ??= b` assigns if a is null/undefined. `||=` if falsy; `&&=` if truthy. Useful for defaults without overwriting 0/''.
Q51beginnerArray flat and flatMap?
`arr.flat(depth)` flattens nested arrays (Infinity for deep). `flatMap` map then flat 1 level — good for mapping to arrays without nested result.
Q52beginnerHow to remove duplicates from array?
`[...new Set(arr)]` for primitives. For objects, Map keyed by id or filter with seen Set. O(n) average with Set.
Q53beginnerSort array of numbers correctly?
Default sort is lexicographic strings — `[10,2,1].sort()` → `[1,10,2]` wrong. Use `.sort((a,b)=>a-b)`. `toSorted` for non-mutating.
Q54beginnerWhat is event bubbling used for in practice?
One parent listener handles many children (delegation) — efficient for dynamic lists. Also understand stopPropagation when nested widgets conflict.
Q55beginnerlocalStorage vs sessionStorage vs cookies?
localStorage: persistent, ~5MB, JS-readable (XSS risk). sessionStorage: tab session. cookies: sent to server, size small, can be HttpOnly. Don't store tokens in localStorage if avoidable.
Q56beginnerHow fetch error handling works?
`fetch` only network-fails into catch; HTTP 404/500 still resolve — check `response.ok` or status. Then `response.json()`. Use AbortController for cancel.
Q57beginnerWhat is CORS from a JS developer view?
Browser blocks reading cross-origin responses without ACAO headers. Fix on server (or Vite proxy in dev). Client cannot 'disable CORS' securely.
Q58intermediateModule type="module" script behavior?
Deferred by default, strict mode, module scope, CORS for cross-origin modules. `import`/`export` work. Classic scripts without type differ.
Q59intermediateWhat is tree shaking?
Bundlers drop unused ESM exports if static `import`/`export` and side-effect free. Prefer named exports; avoid wildcard side-effect imports of huge libs.
Q60intermediateExplain memoization with a simple example?
Cache function results by arguments: `const memo={}; function fib(n){ if(n in memo)return memo[n]; ...}`. Trade memory for CPU. React.memo/useMemo are related ideas for UI.
Q61advancedWhat is currying briefly?
`const add = a => b => a+b; add(1)(2)`. Partial application presets some args. Useful in functional pipelines; don't overuse for readability.
Q62intermediateHow to compare two objects for equality?
Reference `===` checks identity. Deep equality: recursive compare or `JSON.stringify` (key order issues) or libraries (lodash isEqual). React uses Object.is shallow for memo.
Q63advancedWhat are typed arrays?
`Uint8Array`, `ArrayBuffer` for binary data — files, WebGL, network protocols. Not normal arrays; fixed length. Node Buffers relate to this model.
Q64intermediateIntl API use cases?
`Intl.NumberFormat`, `DateTimeFormat`, `Collator` for locale-aware formatting/sorting — better than hand-rolled for i18n apps.
Q65advancedWhat is a Proxy object?
Wraps object with traps for get/set/has — Vue 3 reactivity uses Proxies. Powerful; overkill for simple apps. Know existence for advanced interviews.
Q66intermediateWeakMap vs Map — interview answer?
WeakMap keys must be objects; entries don't prevent GC of keys; not iterable, no size. Use for private metadata on DOM nodes/objects. Map for general key-value.
Q67intermediateHow does garbage collection relate to removing listeners?
If element removed but listener closure still referenced, both may stay in memory. Remove listeners / AbortController on teardown. SPA discipline.
Q68beginnerOutput puzzle: for (var i=0;i<3;i++) setTimeout(()=>console.log(i));
Prints 3,3,3 because var is function-scoped shared. Fix with let or IIFE/bind i. Demonstrates closures + var.
Q69beginnerWhat is document.readyState?
loading / interactive / complete. DOMContentLoaded ~ interactive; load when resources done. Frameworks often bootstrap after DOM ready.
Q70beginnerclassList add/remove/toggle?
Modern way to change CSS classes without string parsing className. `el.classList.toggle('open', forceBoolean)`. Prefer over className+= hacks.
Q71beginnerdataset and data-* attributes?
`data-user-id` → `el.dataset.userId`. Convenient for JS hooks; don't store secrets. Prefer for progressive enhancement markers.
Q72intermediateFormData API?
`new FormData(form)` collects fields for multipart upload/fetch body. Also `.append` for files. Content-Type boundary set automatically when body is FormData.
Q73beginnerURL and URLSearchParams?
`new URL(href)`, `searchParams.get('q')`, `set`, `toString`. Prefer over manual query string parsing/encoding.
Q74beginnerWhat is debounce — one-liner definition + use?
Delay invoking until calls stop for N ms — search-as-you-type, resize end. Contrast throttle: max once per interval (scroll).
Q75intermediateExplain lexical this with arrow in setTimeout?
`obj.method = function(){ setTimeout(()=> console.log(this), 0) }` arrow keeps obj. Regular function callback would lose this (undefined/global).
Q76beginnerHow to clone an array correctly?
`arr.slice()`, `[...arr]`, `Array.from(arr)` — shallow. Nested arrays still shared. `structuredClone(arr)` deep.
Q77advancedWhat does void 0 mean?
Historically guaranteed `undefined` even if undefined redefined (old browsers). Rarely needed now; appears in compiled code.
Q78beginnereval dangers?
Executes string as code — XSS, scope leakage, perf, CSP blocked. Never on user input. Prefer JSON.parse for data.
Q79beginnerWhat is a side effect in JS?
Any interaction beyond returned value: DOM write, network, global mutation, console. Keep pure core logic; isolate side effects (easier testing).
Q80advancedHow do default exports interop with require?
Bundlers/Node interop may put export on `.default`. ESM `import x from` vs `import * as ns`. Know duplication issues with React copies.
Q81beginnerNumeric separators and exponential notation?
`1_000_000`, `1e6` readability. Don't change value. Useful in interviews for large number literals.
Q82intermediateWhat is boxing of primitives?
Temporary object wrapper when calling methods: `'hi'.toUpperCase()` — autoboxing to String object. `new String('hi')` is object typeof object — avoid.
Q83beginnerDifference between == for objects?
Objects compared by reference. Two `{}` are not ==. Coercion with == can call valueOf/toString — prefer === and explicit compares.
Q84beginnerHow to make an object non-extensible in interview terms?
Mention freeze/seal for immutability intent; note shallow. For React state, prefer copying over freeze for updates.
Q85beginnerWhat is requestAnimationFrame?
Schedules paint-aligned callback (~60fps). Better for animations than setTimeout. Cancel with cancelAnimationFrame. Pauses in background tabs often.
Q86intermediateIntersection Observer purpose?
Async observe element visibility — lazy images, infinite scroll, analytics. Better than scroll listeners + getBoundingClientRect thrashing.
Q87advancedMutationObserver purpose?
Watch DOM changes (childList, attributes). Used by libraries; careful of loops. Prefer framework reactivity when possible.
Q88advancedHow to handle large list rendering without React?
Virtualize: render only visible window, recycle DOM nodes. Or paginate. Same idea as react-window.
Q89intermediateBinary vs unary plus?
Binary `a+b` add/concat. Unary `+x` coerces to number (`+'5'`→5, `+true`→1). `{}+[]` parsing quirk uses unary plus.
Q90beginnerWhat is short-circuit evaluation?
`a && b` returns a if falsy else b; `a || b` returns a if truthy else b. Used for defaults before `??`. Know falsy pitfalls with 0.
Q91beginnerGuard clauses style?
Early return on invalid input instead of deep nesting — clearer functions. Common clean-code interview preference.
Q92beginnerWhat is a higher-order function?
Takes or returns a function: map, filter, debounce wrappers. Cornerstone of JS callbacks and functional style.
Q93intermediateExplain stack vs heap briefly for JS values?
Primitives often stack-like simple values; objects allocated on heap, variables hold references. Closures keep heap objects alive.
Q94beginnerWhat causes 'Cannot read property of undefined'?
Accessing `.prop` on undefined/null. Fix with optional chaining, defaults, validation. Common runtime bug in nested API data.
Q95beginnerHow to safely access nested property?
`obj?.a?.b?.c` or lodash `_.get`. Validate API schemas (zod) to reduce need.
Q96beginnerArray destructuring swap variables?
`[a,b]=[b,a]` swaps without temp. Interview trick showing destructuring.
Q97beginnerNamed vs default parameters clarity?
Pass options object `fn({a:1,b:2})` for readability when many args. Destructure with defaults inside.
Q98beginnerWhat is temporal dead zone in one sentence?
Period from block start until `let`/`const` declaration where access throws ReferenceError.
Q99intermediateWhy avoid extending native prototypes?
Breaks for-in, conflicts libraries, future JS may add same name. Prefer utility functions or well-known polyfills carefully.
Q100beginnerWhat is a polyfill?
Code implementing a newer API on older engines (e.g., Array.prototype.flat). Transpile changes syntax (Babel); polyfill adds runtime APIs.
Q101intermediateDifference between undefined variable and undeclared?
Declared without value → undefined. Undeclared access → ReferenceError (strict). `typeof undeclaredVar` is 'undefined' without throw — quirky.
Q102intermediateHow does JS handle integers vs floats?
Number is IEEE-754 double — integers exact to 2^53-1. `0.1+0.2!==0.3`. Use integers/cents for money or BigInt/decimal libs.
Q103intermediateWhat is Same-origin policy impact on JS?
Scripts can only read data from same origin unless CORS/JSONP (legacy). Protects users; shapes how APIs and cookies work with frontends.
Q104beginnerExplain the difference between `==` and `===` in JavaScript.
`===` compares value and type without coercion—`0 === '0'` is false. `==` applies Abstract Equality Comparison: null/undefined only equal each other, strings coerce to numbers, etc. Linters enforce `===` to avoid subtle bugs. Exception knowledge: `Object.is(NaN, NaN)` is true; `NaN === NaN` is false.
Q105beginnerWhat is typeof null and why?
`typeof null` returns `'object'`—a historical bug from the first JS implementation representing null as NULL pointer (type tag 0, object type 0). Use `value === null` explicitly. `typeof undefined` correctly returns `'undefined'`.
Q106advancedWalk through `[] + {}` vs `{} + []` results.
`[] + {}` → `[].toString()` is '' + `[object Object]` → `'[object Object]'`. In expression context `{} + []`, `{}` may parse as empty block leaving `+[]` → 0. Context matters—JS parsing rules trip people in REPL vs script.
Q107beginnerDifference between null and undefined?
`undefined` means variable declared but not assigned, missing object property, or function with no return. `null` is intentional absence assigned by developer. JSON.stringify omits undefined properties but keeps null. APIs use null for empty; optional params may be undefined.
Q108beginnerWhat is NaN and how do you reliably test for it?
NaN means Not a Number from failed numeric ops (`'x' * 2`). It is not equal to itself. Use `Number.isNaN(value)`—not global `isNaN` which coerces: `isNaN('hello')` true. `Number.isNaN` only true for actual NaN.
Q109beginnerExplain truthy and falsy values.
Falsy: false, 0, -0, 0n, '', null, undefined, NaN. Everything else truthy—including `[]`, `{}`, `'0'`. Short-circuit `&&`/`||` return operands, not booleans. Prefer explicit checks in APIs (`value != null`).
Q110intermediateBigInt vs Number—when use BigInt?
BigInt handles integers beyond `Number.MAX_SAFE_INTEGER` (2^53-1). Literal: `123n`. Cannot mix BigInt and Number in arithmetic without explicit conversion. Use for crypto, large IDs, ledger math—not general floats.
Q111intermediateSymbol use cases in modern JavaScript.
Symbols are unique opaque property keys—`Symbol('desc')` not equal across calls. Used for well-known internals (`Symbol.iterator`), avoiding collision on objects, and meta-programming. Not enumerable in `for...in`.
Q112beginnerExplain lexical scope with an example.
Functions resolve variables from where they were defined, not where called. Nested function `inner` sees `outer`'s `let x` at definition time. Block scope with `let`/`const` limits visibility to `{}`; `var` is function-scoped and hoisted.
Q113intermediateWhat is a closure and give a practical use?
A closure is a function retaining access to outer bindings after outer returns. Use cases: private state (`function counter() { let n=0; return () => ++n; }`), partial application, event handlers referencing loop variables (fix with `let` or IIFE).
Q114intermediateClassic loop + var + setTimeout bug—fix?
`for (var i=0; i<3; i++) setTimeout(() => console.log(i), 0)` logs 3 thrice—shared `i`. Fix: `let i` per iteration, or IIFE capturing copy, or `setTimeout(..., 0, i)`. Interview staple demonstrating block scope.
Q115intermediateTemporal Dead Zone (TDZ) for let/const?
From start of block until declaration, binding exists but access throws ReferenceError—'cannot access before initialization'. Unlike hoisted `var` which is undefined until assignment. TDZ prevents using let before declare line.
Q116intermediateIIFE purpose in ES5 codebases?
Immediately Invoked Function Expression creates private scope before modules: `(function(){ var secret = 1; })();` Avoids polluting global. Largely replaced by ES modules and block scope but appears in legacy bundles.
Q117intermediateModule scope vs script scope?
ES modules are strict, defer-loaded, and have top-level `this` as undefined. Top-level bindings are module-scoped not global. Classic scripts share global object properties unless wrapped.
Q118intermediateScenario: Factory function returning methods sharing private array.
`function makeStore(){ const items=[]; return { add:x=>items.push(x), list:()=>[...items] }; }` Closure hides `items` from outside—encapsulation without classes. Methods share same array reference via closure environment.
Q119advancedHow do closures relate to memory leaks in browsers?
Long-lived callbacks holding DOM references prevent GC of detached nodes. Remove listeners on unmount, null references in SPAs, use WeakMap for caches keyed by DOM. React effects cleanup prevents common closure+DOM leaks.
Q120intermediateHow is `this` determined in JavaScript?
Depends on call site: implicit—object before dot; explicit—call/apply/bind; new—fresh object; arrow—lexical from enclosing scope (not own `this`). Unbound function call: strict undefined, sloppy global.
Q121intermediateDifference between __proto__ and prototype?
Instance `obj.__proto__` (use `Object.getPrototypeOf`) links to constructor's `.prototype` object. `Constructor.prototype` is object used as [[Prototype]] for instances. Confusing naming—`prototype` only on functions (except arrows).
Q122advancedImplement `Function.prototype.bind` conceptually.
`function bind(fn, thisArg, ...args){ return function(...rest){ return fn.apply(thisArg, [...args,...rest]); }; }` Bound function ignores later `new` unless constructed as constructor with special handling. Native bind sets `bound` name prefix.
Q123beginnerPrototype chain lookup for missing property.
Engine walks [[Prototype]] chain until null. `hasOwnProperty` checks own keys only; `in` operator includes inherited. Setting shadow property on instance stops delegation for that key.
Q124intermediateClass syntax vs constructor function—differences?
`class` is mostly syntactic sugar: methods non-enumerable, requires new, extends sets up prototype chain and super. Hoisting unlike function declarations—TDZ until class declaration line. Still prototype under hood.
Q125intermediateObject.create use case?
`Object.create(proto)` creates object with specified prototype—useful for inheritance without constructor, or null-prototype dicts `Object.create(null)` safe from prototype pollution.
Q126intermediateScenario: Method extracted loses `this`.
`const log = user.getName; log()` loses user context. Fix: `log.call(user)`, arrow method in class (instance field arrow), or `bind` in constructor. React class components historically bound handlers in constructor.
Q127advancedWhat is prototype pollution attack?
Attacker merges untrusted keys like `__proto__` into objects affecting all instances. Mitigate: validate JSON input, use `Object.create(null)` for maps, freeze prototypes, libraries patched with safe merge.
Q128advancedExplain the event loop microtask vs macrotask order.
Call stack runs sync code; microtasks (promise callbacks, queueMicrotask) drain fully after each macrotask; macrotasks (setTimeout, I/O) run one per turn. `Promise.then` before `setTimeout(0)`.
Q129intermediatePromise states and chaining rules.
Pending → fulfilled or rejected once. `.then` returns new promise; throwing in handler rejects it; returning value fulfills. Returning promise adopts its state. Unhandled rejection events warn in Node/browsers.
Q130intermediateasync/await error handling patterns.
try/catch around await; `.catch` on returned promise from async function. Parallel: `await Promise.all([a,b])`—one failure rejects all. `Promise.allSettled` for partial success reporting.
Q131intermediateDifference between Promise.all and Promise.allSettled?
`Promise.all` fails fast on first rejection—good when all required. `Promise.allSettled` waits for all, returns `{status, value|reason}` each—good for batch operations tolerating partial failure.
Q132beginnerWhat does async function always return?
Always a Promise. Sync return wraps in fulfilled promise; thrown error becomes rejected promise. `return await promise` vs `return promise` subtle in try/catch—await catches rejection inside try.
Q133intermediateScenario: Sequential vs parallel fetches for 10 URLs.
Sequential: loop with await—slower, limits concurrency. Parallel: `await Promise.all(urls.map(u=>fetch(u)))`—faster but spikes connections; use pool/semaphore for rate limits.
Q134beginnerImplement sleep/delay without blocking.
`const sleep = ms => new Promise(r => setTimeout(r, ms)); await sleep(1000);` Non-blocking—other tasks run. Never busy-loop wait in Node/browser main thread.
Q135intermediateAbortController with fetch?
`const c = new AbortController(); fetch(url, {signal: c.signal}); c.abort()` cancels in-flight request. React useEffect cleanup should abort fetches on unmount to prevent setState on unmounted component.
Q136beginnerMutable array methods vs non-mutating—examples?
`push/splice/sort` mutate; `map/filter/slice/toSorted` return new arrays. React state updates require immutability—copy before mutate or use non-mutating methods. `sort()` mutates in place—use `toSorted()` ES2023.
Q137beginnerObject spread vs Object.assign?
Both shallow copy enumerable own properties. Spread `{...a, ...b}` in literals; assign `Object.assign(target, source)`. Nested objects still shared—deep clone needs structuredClone or library.
Q138intermediateMap vs plain object for keyed collections?
Map allows any key type, maintains insertion order, has `.size`, better frequent add/delete perf. Objects fine for JSON-serializable string keys. WeakMap for object-keyed metadata without preventing GC.
Q139beginnerSet use cases.
Unique value collection—dedupe array `[...new Set(arr)]`, track visited nodes in graph, membership O(1) average. WeakSet for object tags private to runtime.
Q140beginnerDestructuring defaults and renaming.
`const {name: userName = 'Anon', age = 0} = user;` Renames and defaults if undefined (not null unless nullish coalescing separately). Array destructuring skip holes: `const [a,,b] = arr`.
Q141beginnerOptional chaining and nullish coalescing?
`obj?.prop?.()` short-circuits on null/undefined. `value ?? default` only for null/undefined—not falsy 0 or ''. Combine: `config?.timeout ?? 5000`.
Q142intermediatestructuredClone vs JSON.parse(JSON.stringify)?
`structuredClone` handles Date, Map, Set, circular refs (with limits), typed arrays. JSON roundtrip loses types and functions. Use structuredClone for deep copy in modern runtimes.
Q143intermediateScenario: Group array of objects by category field.
`Object.groupBy(items, i => i.category)` ES2024 or reduce: `items.reduce((acc,x)=>{(acc[x.cat]??=[]).push(x); return acc;}, {})`. Choose based on target environment support.
Q144beginnerDefault vs named exports?
Named: `export const x`; import `{ x }` or rename `{ x as y }`. Default: `export default fn`; import any name `import fn from`. Mix allowed one default + named. Tree-shaking favors named exports in libraries.
Q145intermediateDynamic import use case.
`const mod = await import('./heavy.js')` code-splits lazy routes in bundlers. React `React.lazy(() => import('./Comp'))`. Returns promise resolving module namespace.
Q146advancedCircular dependency problem and mitigation.
Two modules import each other—one may see uninitialized bindings. Fix: extract shared deps third module, defer access until after init, or merge modules. Bundlers often handle but edge cases throw TDZ errors.
Q147intermediateCommonJS vs ESM in Node?
CJS: `require/module.exports` sync. ESM: `import/export` static, async capable. Node package.json type module or `.mjs`. Interop: default import from CJS may be `.default`. Prefer ESM for new Node code.
Q148advancedTop-level await implications?
Module waits for await before executing importers—blocks dependency graph. Useful for config loading; misuse slows app start. Not in non-module scripts.
Q149intermediateTree shaking requirements?
ESM static imports enable dead code elimination. Side-effect-free modules (`package.json sideEffects: false`) help. CommonJS dynamic requires limit shaking.
Q150intermediateScenario: Barrel file export pitfalls?
`index.ts` re-exporting everything can pull entire library into bundle and worsen circular deps. Prefer direct imports or explicit barrel subsets in performance-critical apps.
Q151intermediateimport.meta.url for asset paths?
In bundlers/Vite, `new URL('./img.png', import.meta.url)` resolves file-relative assets at build time. Replaces webpack require.context patterns.
Q152intermediateEvent propagation: capture, target, bubble?
Capture from window to target, bubble back. `addEventListener('click', fn, true)` capture phase. `stopPropagation` stops further phases; `preventDefault` blocks default action (not same as stop).
Q153intermediateEvent delegation pattern?
Attach listener on parent; use `event.target.closest('.item')` to handle children—fewer listeners, works for dynamic nodes. React 17+ delegates at root; synthetic events abstract differences.
Q154intermediateDebouncing vs throttling?
Debounce: wait until pause (search input). Throttle: at most once per interval (scroll). Implement with timers; lodash utilities common. Choose based on fire rate vs responsiveness.
Q155intermediateCustomEvent usage.
`new CustomEvent('saved', {detail:{id:1}})` dispatch on element for decoupled widgets. Web Components use for external API. Not a substitute for app state in large React apps.
Q156advancedPassive event listeners?
`{passive:true}` on touch/wheel tells browser won't call preventDefault—enables smooth scrolling. Chrome warns non-passive touch listeners hurting perf.
Q157intermediateMemory: removeEventListener requirements?
Must pass same function reference and capture flag. Anonymous inline functions can't be removed—store named handler. Frameworks abstract cleanup; vanilla needs discipline.
Q158intermediateScenario: Click outside dropdown to close.
Document listener mousedown checking `!dropdown.contains(e.target)`; cleanup on unmount. React hooks pattern; mind portal targets outside DOM subtree—include portal root check.
Q159beginnerDifference DOMContentLoaded vs load?
DOMContentLoaded when HTML parsed—defer scripts run before. `load` waits all resources images/styles. Init app logic often on DOMContentLoaded; measure LCP separately.
Q160beginnerPure function definition and why it matters.
Same inputs → same outputs, no side effects (no mutate external state, I/O). Easier to test, memoize, parallelize. React reducers should be pure; impure logic in effects.
Q161intermediateImmutability in UI state management.
New references trigger React re-render equality checks. Update nested: `{...state, user: {...state.user, name}}`. Immer library simplifies draft-style updates producing immutable result.
Q162intermediateHigher-order function example.
Function taking/returning functions—`const withLog = fn => (...args) => { console.log(args); return fn(...args); }`. Array methods map/filter are HOFs. React HOC pattern legacy before hooks.
Q163advancedCurrying vs partial application?
Currying transforms `f(a,b,c)` into `f(a)(b)(c)`. Partial application fixes some args: `fn.bind(null, a)`. Useful for config presets and functional pipelines.
Q164advancedCompose vs pipe utilities.
`compose(f,g)(x)` → f(g(x)); pipe left-to-right readable. lodash/fp Ramda patterns. Build middleware stacks similar to Redux.
Q165intermediateRecursion vs iteration for tree traversal?
Recursive DFS elegant; deep trees risk stack overflow—use iterative stack. BFS with queue. DOM traversal often iterative in production engines.
Q166intermediateScenario: Memoize expensive pure function.
Cache Map keyed by JSON.stringify args (careful key stability) or use lodash memoize with resolver. LRU cap prevents memory blowup. React useMemo caches within render lifecycle.
Q167advancedFunctor/Monad— practical JS relevance?
Rare in interviews unless FP roles. Optional chaining resembles functor; Promise chain resembles monad. Know map/flatMap on arrays and promises as approachable examples.
Q168advancedXSS types and prevention in frontend.
Stored/reflected/DOM XSS inject scripts via unsanitized HTML. Prevent: escape output, CSP, avoid innerHTML with user data, DOMPurify if rich text needed. React escapes JSX text by default.
Q169beginnerJSON.parse try/catch—what throws?
Invalid JSON SyntaxError. undefined not valid JSON. Valid JSON types only—no trailing commas, no single quotes. Validate schema after parse (Zod).
Q170intermediateError: stack trace and custom errors.
`class AppError extends Error { constructor(msg,code){ super(msg); this.code=code; } }` Preserve stack with `Error.captureStackTrace` in Node. Don't leak stacks to clients in production.
Q171intermediateSame-origin policy basics.
Protocol+host+port must match for DOM access cross-window. CORS relaxes for XHR/fetch read responses with headers. JSONP legacy bypass—avoid.
Q172intermediatelocalStorage security considerations?
Accessible to any script on origin—XSS steals tokens. Prefer HttpOnly cookies for session tokens. Never store refresh tokens unencrypted if avoidable. sessionStorage tab-scoped.
Q173advancedCSRF vs XSS—frontend role?
CSRF: forged requests using user's cookies—mitigate with SameSite cookies, CSRF tokens. XSS: run attacker JS—steals tokens regardless CSRF token. Both matter; frontend validates origins for sensitive actions.
Q174advancedScenario: Eval and new Function risks?
Executing user strings is RCE in Node or full DOM access in browser. Never eval user input. JSON.parse not eval. Template engines must escape.
Q175advancedContent Security Policy from client view?
Server header restricts script/style sources. Report-only mode for testing. Nonce hashes allow inline scripts in strict CSP. Frontend teams coordinate with backend for nonce injection SSR.
Q176intermediateJest mock function basics.
`const fn = jest.fn(); expect(fn).toHaveBeenCalledWith(1);` Track calls, implement mockReturnValue. Mock modules with jest.mock hoisting rules. Clear mocks between tests.
Q177beginnerUnit vs integration vs e2e tests?
Unit: isolate function/component with mocks—fast. Integration: several units together (component + hook + MSW). E2E: Playwright/Cypress real browser—slowest, highest confidence.
Q178beginnerDebugging async code in DevTools?
Enable async stack traces, breakpoints on promise rejections, log points, network tab for fetch timing. `debugger` statement pauses if DevTools open.
Q179intermediateScenario: Flaky test depending on setTimeout.
Use fake timers `jest.useFakeTimers()` advance time deterministically. Prefer awaiting observable state (`waitFor`) over fixed sleeps.
Q180intermediateTypeScript narrowing with typeof and in.
`if (typeof x === 'string')` narrows; `in` operator discriminates union `'foo' in obj`. satisfies operator validates without widening.
Q181beginnerStrict mode benefits?
'use strict' disallows implicit globals, duplicate params, unsafe delete, changes `this` in plain calls to undefined. Modules and classes strict by default.
Q182intermediatePerformance: profiling JS in browser.
Performance tab record, flame chart, long tasks, memory heap snapshots for leaks. Lighthouse for lab metrics. Avoid premature optimization—measure first.
Q183intermediateSource maps purpose?
Map bundled/minified code back to original TS/JS for stack traces and debugging. Hide from production users optionally; still server-side symbolication for errors.
Q184advancedScenario: Deep equality check without library.
Recursive compare primitives, null, Date getTime, arrays length+elements, objects key sets+values. Mind cycles with WeakMap visited. Production use lodash isEqual or Node util.isDeepStrictEqual.
Q185intermediateScenario: Implement Promise.race.
`function race(promises){ return new Promise((res,rej)=>{ promises.forEach(p=>Promise.resolve(p).then(res,rej)); }); }` First settle wins.
Q186beginnerScenario: Flatten nested array one level.
`arr.flat()` or `[].concat(...arr)` if only one level. Deep: recursive or flat(Infinity) cautiously on depth.
Q187advancedScenario: Rate limit API calls client-side.
Queue + token bucket or max concurrent with p-limit pattern. Exponential backoff on 429 Retry-After header. Debounce user-triggered search.
Q188intermediateCompare var hoisting vs let temporal dead zone.
var hoists undefined initialization; let hoists uninitialized TDZ. Function declarations hoist fully; function expressions follow variable rules.
Q189beginnerScenario: Detect browser vs Node environment.
`typeof window !== 'undefined'` common check; `import.meta.env` in Vite; `process.versions.node` in Node. Isomorphic libraries branch carefully.
Q190advancedWeakRef and FinalizationRegistry use?
WeakRef soft reference to object without preventing GC—cache with caution. FinalizationRegistry cleanup callback when object collected—rare advanced API.
Q191intermediateScenario: Polyfill Array.prototype.at.
`function at(i){ i=Math.trunc(i)||0; if(i<0)i+=this.length; if(i<0||i>=this.length)return undefined; return this[i]; }` Handles negative indices.
Q192advancedGenerator function practical use?
Lazy sequences, infinite iterators, custom iterables for for-of. Async generators for streaming data. Redux-saga historically used generators for async flows.
Q193intermediateScenario: Prevent double form submit.
Disable button on first click, idempotency key header, debounce handler. Server must still enforce idempotency—client guard insufficient alone.
Q194advancedCompare microtask scheduling queueMicrotask vs Promise.then.
Both microtasks; queueMicrotask schedules callback without promise allocation. Order relative to other microtasks FIFO per turn.
Q195beginnerScenario: Parse query string manually.
`new URLSearchParams(window.location.search)` preferred. Manual: split & decodeURIComponent on keys/values—mind + vs space encoding differences.
Q196intermediateWhat is the event loop in Node.js vs browser?
Both use V8; browsers add Web APIs (DOM, fetch) queued as macrotasks. Node has libuv thread pool for fs/crypto and phases timers poll check close. Neither runs JS concurrently on multiple threads for your code.
Q197intermediateimport.meta in browsers and bundlers?
Exposes module url env in Vite `import.meta.env.MODE` hot `import.meta.hot`. Node ESM has import.meta.url for file paths.
Q198beginnerGlobal object window vs globalThis?
`globalThis` unified cross-environment reference. window browser global global Node self workers.
Q199intermediatePolyfill vs transpile vs ponyfill?
Transpile syntax Babel TypeScript to older JS. Polyfill adds missing API prototype. Ponyfill standalone function no prototype mutation preferred libraries.
Q200intermediateScenario: CORS error in fetch—client fix?
CORS is server header fix Access-Control-Allow-Origin not client hack. Dev proxy vite.config server.proxy same-origin during development.
Q201intermediatelocalStorage quota exceeded handling?
Try catch QuotaExceededError prune old keys compress data IndexedDB larger storage alternative.
Q202beginnerrequestAnimationFrame vs setTimeout animation?
rAF syncs paint 60hz pauses hidden tab battery efficient visual updates setTimeout drift.
Q203intermediateScenario: Detect offline navigator.onLine?
Unreliable optimistic use fetch failed event online offline listeners queue sync service worker background.
Q204intermediateImplement debounce function?
Return function reset timer each call execute fn after ms quiet `let t; return (...a)=>{clearTimeout(t); t=setTimeout(()=>fn(...a),ms)}`
Q205intermediateImplement throttle function?
Execute at most once per window trailing or leading edge flag track last run timestamp or trailing call.
Q206beginnerScenario: Sort array objects by date field?
`arr.sort((a,b)=> new Date(a.date)-new Date(b.date))` mutates copy first `[...arr].sort`. ISO strings lex sort works if ISO8601.
Q207beginnerScenario: Group array by property reduce?
`items.reduce((acc,x)=>{(acc[x.type]??=[]).push(x); return acc},{})` builds buckets keyed by property. ES2024 adds `Object.groupBy(items, x => x.type)` when available. Either approach is O(n) and preferable to manual nested loops for grouping.
Q208advancedWeakMap vs Map for DOM metadata?
WeakMap keys objects GC when node removed no memory leak attach private data elements.
Q209intermediateScenario: Clone array shallow nested mutation?
Spread `[...arr]` shallow nested objects shared structuredClone deep or JSON if JSON-safe.
Q210advancedTagged template literals use?
styled-components gql lit html sanitize sql template tag function process strings raw values.
Q211beginnerScenario: Fix callback hell with promises?
Chain then async await linearize error try catch one level avoid pyramid.
Q212intermediateName common RegExp flags and what they do.
`g` global (find all), `i` ignore case, `m` multiline `^/$` on lines, `s` dotAll (`.` matches newline), `u` Unicode (code-point aware, enables `\p{}`), `y` sticky (match only at `lastIndex`), `d` indices for groups. Example: `/\p{Emoji}/gu`. Flags change matching semantics—know `g` + `exec`/`lastIndex` interactions.
Q213advancedWhat is the sticky `y` flag and how does it differ from `^`?
`y` forces matches to start exactly at `lastIndex` (not search forward). `^` anchors to start of string/line depending on `m`. Sticky is useful for tokenizers that advance through a string. With `g`/`y`, `lastIndex` updates; forgetting to reset causes subtle bugs.
Q214advancedRegExp `lastIndex` pitfalls with `/g`?
Stateful regexes with `g` or `y` store `lastIndex` on the RegExp object. Reusing the same literal/object across calls can skip matches or return null unexpectedly. Prefer `string.matchAll` carefully, create fresh regexes, or reset `re.lastIndex = 0`. Avoid sharing `/g` regexes in async concurrent code.
Q215advancedWhat are Unicode property escapes?
With the `u` flag: `\p{Letter}`, `\p{Number}`, `\p{Script=Greek}`, `\P{...}` for negation. Enables proper Unicode-aware validation beyond `[a-z]`. Example: `/^\p{L}+$/u` for letters across languages. Requires `u` flag.
Q216advancedWhat is the Reflect API?
Reflect mirrors Object operations as functions: `Reflect.get`, `set`, `has`, `deleteProperty`, `construct`, `apply`. Used with Proxies so traps can forward default behavior via Reflect and return booleans consistently (`defineProperty` success). Prefer Reflect in Proxy `set`/`defineProperty` traps for correct invariants.
Q217intermediateService Worker basics — what problem does it solve?
A Service Worker is a programmable network proxy in a separate thread: cache assets, offline fallbacks, background sync, push. Lifecycle: register → install → activate. Must be HTTPS (or localhost). Use Cache Storage carefully; version caches and skipWaiting/clients.claim intentionally to avoid sticky old SW bugs.
Q218intermediateIndexedDB overview for interviews?
Browser NoSQL key-value/object store DB for large structured data, async via events/promises (idb wrapper helps). Supports indexes and transactions. Use for offline apps, draft storage, caching large datasets beyond localStorage (~5MB sync string limits). Not for tiny prefs—localStorage/sessionStorage suffice there.
Q219intermediateWeb Workers vs async on the main thread?
Workers run JS off-main-thread via message passing (`postMessage`, structured clone). Great for CPU-heavy parsing/crypto/image processing without jank. Cannot touch DOM. Module workers: `new Worker(url, {type:'module'})`. Transferables (ArrayBuffer) avoid copies. SharedArrayBuffer needs cross-origin isolation headers.
Q220intermediateWhat is BroadcastChannel?
`new BroadcastChannel('name')` pub/sub across same-origin browsing contexts (tabs, workers). Simpler than localStorage storage events for same-browser messaging. Not for cross-device; closing channels matters. Useful for logout-all-tabs patterns.
Q221beginnerHistory API: `pushState` vs `replaceState`?
`pushState` adds a history entry; `replaceState` updates the current entry without stacking. Both change the URL without reload. Listen to `popstate` for back/forward. SPAs must sync UI on `popstate` and avoid breaking accessibility focus management on route change.
Q222advancedModule workers — how do you create one?
`const w = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });` enables `import` inside the worker. Better bundler integration than classic workers with importScripts. Communicate via messages; handle errors with `w.onerror`.
Q223advancedAtomics and SharedArrayBuffer — brief?
SharedArrayBuffer shares memory between workers; Atomics provide synchronized read/write/wait/notify to avoid races. Requires cross-origin isolation (`COOP`/`COEP`) after Spectre mitigations. Niche for high-perf parallelism—not typical app CRUD. Mention carefully in interviews as advanced awareness.
Q224intermediateWhat is the Intl API used for?
`Intl.DateTimeFormat`, `NumberFormat`, `Collator`, `RelativeTimeFormat`, `ListFormat` localize correctly per locale/options. Prefer Intl over handmade date strings. Example: `new Intl.NumberFormat('en-IN', { style:'currency', currency:'INR' }).format(n)`.
Q225advancedTemporal proposal — what should you know?
Temporal aims to replace awkward Date with immutable types: `PlainDate`, `PlainDateTime`, `Instant`, `ZonedDateTime`, durations. Better DST/time-zone handling. Not universally production-default everywhere yet—awareness plus current Date/luxon/dayjs practice is the interview stance.
Q226intermediateWhat is `error.cause`?
ES2022: `throw new Error('Failed to save', { cause: originalError })` chains underlying errors. Helps debugging and logging without losing stack context. Catch sites can inspect `err.cause`. Prefer over string-concatenating messages alone.
Q227intermediate`Object.groupBy` / `Map.groupBy` awareness?
`Object.groupBy(iterable, fn)` groups items into a plain object keyed by callback result; `Map.groupBy` returns a Map (better for non-string keys). Example: `Object.groupBy(users, u => u.role)`. Newer standard—polyfill or alternative reduce when targeting older runtimes. (Earlier proposals used `Array.groupBy` naming.)
Q228advancedWhat is `Promise.withResolvers()`?
Returns `{ promise, resolve, reject }` so you can expose resolvers outside the Promise constructor executor—cleaner deferred patterns. Example: `const { promise, resolve } = Promise.withResolvers();`. Handy for event-to-promise bridges.
Q229advanced`using` disposable resources (Explicit Resource Management)?
Proposal/modern syntax: `using resource = acquire()` auto-calls `[Symbol.dispose]()`/`asyncDispose` at block end (like RAII/Python `with`). Useful for file handles, locks. Awareness-level topic—confirm runtime support before relying on it in production Node/browsers.
Q230beginnerCommon RegExp patterns: email/URL — interview caution?
Interviewers may ask for a simple email regex, but perfect RFC email validation via regex is impractical—prefer HTML `type=email` + server checks. For URLs, prefer `new URL(str)` in try/catch. Know character classes, capturing vs non-capturing `(?:)`, and lookaheads basics.
Q231intermediateHow does `String.prototype.matchAll` work with groups?
`for (const m of str.matchAll(/(\w+)/g))` yields match objects including groups; requires `g` flag. Cleaner than manual `exec` loops. Remember sticky/global lastIndex effects if reusing the regex object.
Q232advancedService Worker cache strategies — name three.
Cache-first (static assets), network-first (API freshness), stale-while-revalidate (return cache immediately, update in background). Choose per resource type. Always plan cache versioning and offline fallback pages.
Q233beginnerlocalStorage vs sessionStorage vs IndexedDB?
localStorage: sync, string-only, persists, ~5MB, same-origin. sessionStorage: per-tab session. IndexedDB: async, structured/large, indexed queries. Don't store secrets; beware XSS reading storage. Prefer memory + httpOnly cookies for auth tokens when possible.
Q234intermediateHow do you terminate and restart a Web Worker cleanly?
Call `worker.terminate()` from the main thread; the worker can call `self.close()`. Recreate a new Worker instance when needed. Ensure you remove event listeners and revoke object URLs to avoid leaks.
Q235intermediate`history.scrollRestoration` — why care?
Browsers may restore scroll on back navigation. SPAs often set `history.scrollRestoration = 'manual'` and restore scroll intentionally per route for consistent UX.
Q236advancedStructured clone vs JSON for postMessage?
`postMessage` uses structured clone: supports Date, Map, Set, ArrayBuffer (or transfer), cyclic-ish handling rules—broader than JSON. Functions/DOM nodes aren't cloneable. Transfer list zero-copies ArrayBuffers.
Q237intermediateWhat does `queueMicrotask` do vs `setTimeout(0)`?
Microtasks run before the next render/macrotask; `setTimeout` schedules a macrotask. Promise thenables and `queueMicrotask` are microtasks. Starving the event loop with endless microtasks blocks rendering—know the difference for interview depth.
Q238advancedRegex lookbehind — example?
`/(?<=@)\w+/` matches word after `@` without consuming `@` (fixed-length lookbehind in JS). Lookahead `(?=...)` / `(?!...)` are common. Useful for validation tokens; keep patterns readable.
Q239intermediateHow do Intl and time zones interact?
`Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Kolkata', ... })` formats an Instant in a zone. Storing UTC ISO strings server-side and formatting at the edge/client avoids ambiguous local Date pitfalls.
Q240advancedWhat is a classic `/g` + `test()` bug?
`const re=/a/g; re.test('a'); re.test('a');` second call may be false because `lastIndex` advanced. Don't use stateful regexes with `test` in loops without resetting. Prefer non-global for simple existence checks.
Q241intermediateAbortSignal with fetch — pattern?
`const ac = new AbortController(); fetch(url, { signal: ac.signal }); ac.abort()` rejects with AbortError. Wire to timeouts via `AbortSignal.timeout(ms)` (modern) or manual timers. Essential for canceling stale React effects.
Q242beginnerWhat is `crypto.randomUUID()`?
Secure UUID v4 generation in Web Crypto—prefer over `Math.random` IDs. Available in modern browsers and Node. Still treat as opaque IDs, not auth proof alone.
Q243advancedWeakRef / FinalizationRegistry awareness?
Advanced memory tools: WeakRef holds weak reference to object; FinalizationRegistry schedules cleanup callbacks after GC. Don't use for normal app logic—nondeterministic. Mention as awareness for caches.
Q244beginnerHow does `import()` dynamic import help performance?
Returns a Promise of the module namespace for code-splitting and conditional loading. Pair with React `lazy`. Handle errors and loading states. Static analysis/bundlers create separate chunks.
Q245intermediateBroadcastChannel vs Service Worker messaging?
BroadcastChannel is same-origin tab/worker pubsub. SW `postMessage`/`clients.matchAll` reaches controlled pages for update prompts. Use SW for network/cache control; BroadcastChannel for simple UI sync across tabs.
Q246beginnerExplain `Object.hasOwn` vs `in` vs `hasOwnProperty`.
`Object.hasOwn(obj, key)` is the safe own-property check (works for objects without Object.prototype). `key in obj` walks the prototype chain. Prefer `Object.hasOwn` over `obj.hasOwnProperty(key)` when the object may lack the method.
React
155 questions
Q1beginnerWhat is JSX and what does it compile to?
JSX is syntax sugar for `React.createElement(type, props, ...children)` or the automatic runtime `_jsx`. It is not HTML—className not class, expressions in `{}`. Babel/Vite transforms JSX before bundling. Fragments `<>...</>` avoid extra DOM nodes.
Q2beginnerFunctional vs class components—when classes today?
Functions + hooks are default for new code. Classes remain in legacy codebases; error boundaries still require class in React 18 (React 19 adds experimental function support). Prefer functions for simplicity and hook composition.
Q3beginnerControlled vs uncontrolled inputs?
Controlled: value driven by React state via `value` + `onChange`. Uncontrolled: DOM holds state, read via ref. Controlled enables validation and single source of truth; uncontrolled simpler for one-off forms with react-hook-form hybrid patterns.
Q4beginnerWhy must component names be capitalized?
Lowercase tags are HTML elements (`<div>`); uppercase are components. JSX transformer uses first letter to distinguish. Custom elements lowercase only for web components with hyphen.
Q5intermediateKeys in lists—purpose and anti-patterns?
Keys help reconciliation match items across renders—stable identity, not index if list reorders/deletes. Index keys cause wrong state on reorder. Use database ids; generate stable ids for static lists.
Q6intermediateProps drilling vs context—when switch?
Drilling passes props through intermediates—fine for 2–3 levels. Context shares theme/auth/locale without prop noise. Over-context everything causes unnecessary rerenders—split contexts or use selectors (use-context-selector).
Q7intermediateChildren prop patterns.
`children` can be elements, text, render function, or array. Compound components pass implicit context: `<Select><Select.Option/></Select>`. `React.Children.map` rarely needed vs explicit props.
Q8intermediateStrictMode double invoke in dev—why?
React 18 StrictMode mounts, unmounts, remounts components and double-invokes effects to surface side effects missing cleanup. Production does not double-run. Helps find unsafe lifecycles and impure renders.
Q9beginnerRules of Hooks—explain.
Only call hooks at top level of function components or custom hooks—never in loops, conditions, or nested functions. Ensures hook call order stable across renders. ESLint plugin enforces.
Q10intermediateuseState batching behavior React 18?
Updates inside events, setTimeout, native handlers batch into one render automatically. `flushSync` forces sync render when needed (measure DOM immediately). Multiple setStates in event handler → one paint.
Q11intermediateuseEffect vs useLayoutEffect?
useEffect runs after paint—good for fetch, subscriptions. useLayoutEffect runs after DOM mutations before paint—measure layout, sync DOM writes avoiding flicker. SSR: both warn—useEffect only runs client.
Q12intermediateuseEffect dependency array pitfalls?
Missing deps cause stale closures; exhaustive-deps lint helps. Objects/functions as deps retrigger every render unless memoized. Empty `[]` runs once on mount—cleanup on unmount. Omitting array runs every render.
Q13intermediateuseRef use cases beyond DOM access.
Mutable box persisting across renders without triggering re-render—timer ids, previous value, instance variables. `ref.current` updates don't cause render. Forward refs pass to child DOM via `forwardRef`.
Q14intermediateuseMemo vs useCallback—when each?
useMemo caches computed value; useCallback caches function identity. Both help child memoization when deps stable. Don't wrap everything—measure first. useCallback is useMemo for functions.
Q15intermediateCustom hook pattern—example.
`function useDebounce(value, ms){ const [v,setV]=useState(value); useEffect(()=>{const t=setTimeout(()=>setV(value),ms); return ()=>clearTimeout(t);},[value,ms]); return v; }` Encapsulates reusable stateful logic.
Q16intermediateuseReducer when prefer over useState?
Complex state transitions, multiple sub-values, next state depends on previous—form wizards, reducers testable pure. `dispatch({type:'increment'})` clearer than many setters. Combine with context for lightweight global state.
Q17beginnerLifting state up—example scenario.
Two siblings need shared selected tab—move `selected` state to parent, pass down props and callbacks. Avoid duplicating source of truth in both children.
Q18advancedContext performance problem and fixes?
Any context value change rerenders all consumers. Split contexts by concern, memoize value object `useMemo(()=>({user,login}),[user,login])`, use state libraries (Zustand, Redux) with selectors for fine subscriptions.
Q19intermediateRedux vs Zustand vs React Query—division of labor?
Redux: client global UI state, predictable middleware. Zustand: lighter global store. React Query/TanStack Query: server state cache, sync, invalidation—not for all client state. Most apps combine local state + query library.
Q20intermediateServer state vs client state?
Server state: from API, stale, shared, async—cache with Query/SWR. Client state: UI toggles, form drafts local until submit. Don't put server cache in Redux unnecessarily.
Q21advancedOptimistic updates pattern.
Update UI before server confirms; rollback on error. TanStack Query `onMutate` snapshot + revert. Improves perceived speed; requires idempotent APIs and conflict handling.
Q22intermediateForm state: react-hook-form benefits?
Uncontrolled inputs with refs reduce rerenders per keystroke; validation schema (Zod/Yup); integrates controlled when needed. Better perf on large forms vs naive useState per field.
Q23intermediateURL as state for filters/pagination?
Search params survive refresh, shareable links. `useSearchParams` in React Router syncs UI. Bookmarkable list filters beat hidden component state alone.
Q24intermediateAnti-pattern: mirroring props to state.
`useState(props.value)` desyncs when prop updates unless syncing in effect (usually wrong). Derive from props directly or fully controlled pattern with key reset.
Q25advancedHow React reconciliation works at high level?
Render phase builds new fiber tree comparing element type/key—reuse DOM if compatible, else replace. Commit phase applies DOM updates. Diff O(n) heuristic vs tree diff exponential.
Q26intermediateReact.memo when worth it?
Wrap component skipping render if props shallow equal. Helps expensive pure components with stable props. useless if props always new objects—pair with useMemo/useCallback on parent.
Q27intermediateVirtualization for long lists?
Render only visible rows (react-window, tanstack virtual)—constant DOM nodes vs thousands. Measure row height fixed or dynamic. Essential for tables with 10k+ items.
Q28intermediateCode splitting with React.lazy and Suspense.
`const Page = lazy(()=>import('./Page')); <Suspense fallback={<Spinner/>}><Page/></Suspense>` Splits bundles per route. Error boundaries catch chunk load failures separately.
Q29intermediateWhy inline object in JSX prop hurts perf?
`<Child style={{color:'red'}} />` creates new object every render—breaks memo on Child. Hoist constant or useMemo for object if child memoized.
Q30advancedConcurrent features: useTransition, useDeferredValue?
Mark updates low priority—keep UI responsive during heavy filter/sort. `startTransition(()=>setFilter(q))` defers expensive tree. deferredValue lags behind fast input.
Q31intermediateProfiler API interview mention?
React DevTools Profiler records commit times, why components rendered. `<Profiler id='List' onRender={fn}>` programmatic. Identify unnecessary renders before blind memoization.
Q32advancedHydration mismatch causes?
SSR HTML differs client first render—Date.now, random ids, invalid HTML nesting. Fix: suppressHydrationWarning sparingly, generate ids server-side, match markup. React 19 improves streaming hydration.
Q33intermediateReact Router v6 nested routes?
Layout routes wrap `<Outlet/>` for child routes. Relative links `to='settings'`. Data APIs loaders/actions in v6.4+. Index routes for default child.
Q34beginnerProtected route pattern.
Wrapper checks auth from context; redirect `<Navigate to='/login' replace/>` if unauthenticated. Preserve intended URL in location state for post-login redirect.
Q35intermediateuseEffect fetch on mount—cleanup?
AbortController abort fetch on unmount; ignore flag prevents setState after unmount. Better: TanStack Query handles lifecycle. Race: later responses overwrite earlier if not cancelled.
Q36intermediateSubscription pattern in useEffect.
`useEffect(()=>{ socket.on('msg', handler); return ()=>socket.off('msg', handler); },[socket]);` Cleanup prevents duplicate handlers and leaks.
Q37intermediateEvent listeners in useEffect vs ref callback?
Effect attaches after render—fine for window listeners. Ref callback on mount node when need DOM immediately—rare. Passive scroll listeners note.
Q38advancedDependency on stable callback—useEffectEvent?
React 19 `useEffectEvent` reads latest props/state without adding effect deps—replaces eslint-disable patterns for stable subscription callbacks.
Q39intermediateScroll restoration on navigation?
React Router scroll restoration optional; manual `window.scrollTo(0,0)` in layout effect on pathname change. Preserve scroll on back navigation with history state or library.
Q40advancedLoader pattern vs useEffect data fetch?
Route loaders fetch before render—no loading flash, parallel data, error boundaries on route. useEffect simpler but waterfall risk and duplicate fetch StrictMode.
Q41intermediateError boundaries—what they catch?
Catch render/lifecycle errors in children, not event handlers or async. Display fallback UI `getDerivedStateFromError` / `componentDidCatch`. Log to Sentry in didCatch.
Q42intermediatePortal use cases.
`createPortal(child, document.body)` for modals/tooltips escaping overflow:hidden ancestors. Event bubbling still through React tree—important for delegated handlers.
Q43intermediateCompound component pattern.
Parent provides context; children read implicit state—Tabs, Accordion APIs. Flexible composition vs monolithic props blob.
Q44intermediateRender props vs hooks?
Render prop `<Data fetcher={(data)=>...}/>` explicit but verbose. Custom hook `useFetcher()` cleaner—hooks largely replaced render props except library interop.
Q45intermediateTesting Library philosophy?
Test behavior users see—queries by role/label, not implementation details. `fireEvent`/`userEvent` interactions; avoid testing state directly. async `findBy` waits.
Q46intermediateMocking fetch in component tests?
MSW intercepts network layer realistically. jest-fetch-mock simpler. Avoid mocking child components unless isolation necessary.
Q47beginnerSnapshot testing cautions?
Large snapshots churn without value—prefer assert visible text/role. Good for stable serialized output (error messages).
Q48advancedforwardRef and useImperativeHandle?
Expose limited imperative API on ref—focus input, play video. `useImperativeHandle(ref, ()=>({focus:()=>inputRef.current.focus()}),[])` Don't overuse—declarative preferred.
Q49intermediateCSR vs SSR vs SSG vs ISR?
CSR: client renders empty shell. SSR: server HTML per request. SSG: build-time HTML. ISR: static + revalidate interval. Choose by freshness, SEO, TTFB, infra cost.
Q50advancedNext.js App Router vs Pages Router?
App Router: React Server Components default, layouts, streaming, nested loading.js. Pages: getServerSideProps/getStaticProps familiar model. Migration gradual.
Q51advancedWhat are React Server Components?
Components run only on server—zero client JS by default, fetch server-side, pass serializable props to client components. `'use client'` boundary for interactivity. Cannot use hooks/state in server components.
Q52advancedHydration and selective hydration?
Client attaches listeners to server HTML. Streaming SSR sends shell first, hydrates interactive islands. Mismatch debugging critical skill.
Q53intermediateSEO considerations for React SPA?
CSR alone poor crawl without prerender/SSR. Meta tags via react-helmet or SSR injection. Core content in initial HTML for LCP/SEO.
Q54intermediateEnvironment variables in Vite vs Next?
Vite: `import.meta.env.VITE_*` exposed client-side only prefixed. Next: `NEXT_PUBLIC_*` client; others server-only. Never embed secrets in client bundle.
Q55intermediateImage optimization Next/Image?
Lazy load, responsive sizes, modern formats, blur placeholder. Prevents layout shift with width/height. CDN transformation on Vercel or custom loader.
Q56advancedMiddleware in Next.js use cases?
Edge middleware auth redirects, geo routing, A/B flags before render. Runs close to user—keep fast, no heavy DB ideally.
Q57advancedFiber architecture purpose?
Incremental rendering—split work into units pausable for high priority updates (input). Enables concurrent features. Replaces stack reconciler blocking main thread.
Q58advanceduseSyncExternalStore for external stores?
Subscribe to Redux/Zustand/browser APIs safely concurrent— avoids tearing. Library authors use; app devs rarely direct.
Q59advancedSuspense for data fetching future?
Suspense boundaries show fallback while promise resolves—integrating with frameworks and cache. experimental patterns; TanStack Query suspense option exists.
Q60advancedReact 19 features overview?
Actions, useActionState, document metadata, ref as prop (no forwardRef), improved hydration, useOptimistic. Track release notes for interviews.
Q61advancedPreventing unnecessary context rerenders with selectors.
Zustand `useStore(s=>s.slice)` or context-selector hook re-render only when selected slice changes via shallow compare.
Q62intermediateDangerouslySetInnerHTML when acceptable?
Only sanitized HTML from trusted source or DOMPurify-cleaned CMS content. Never raw user input. XSS vector if misused.
Q63intermediateAccessibility in React modals?
Focus trap, initial focus, return focus on close, `role='dialog' aria-modal='true'`, Escape closes, aria-labelledby. Libraries: Radix, Headless UI handle primitives.
Q64intermediateInternationalization i18n in React?
react-i18next namespaces, lazy load locales, ICU pluralization. Avoid string concat—use interpolation keys. SSR must match locale server/client.
Q65intermediateScenario: Infinite scroll product list implementation.
IntersectionObserver sentinel at bottom triggers fetch next page; append to state; dedupe by id; loading flag prevents duplicate requests. Virtualize if list huge. TanStack Query infinite queries handle cache.
Q66intermediateScenario: Debounced search input with API.
Local state immediate; debounced value in useEffect triggers fetch with abort cleanup. Or useDeferredValue + memo filter client-side for small datasets.
Q67beginnerScenario: Theme toggle dark/light.
Context or data attribute on html; CSS variables switch; persist localStorage; avoid flash with inline script SSR. Respect prefers-color-scheme default.
Q68intermediateScenario: Form with 20 fields performance.
react-hook-form uncontrolled; split into steps; avoid top-level state per keystroke; validate on blur/submit. Memoize heavy field components.
Q69beginnerScenario: Child needs to call parent method.
Prefer callback prop `onSave`. Ref imperative handle only for focus/media. Events bubble through props not DOM for logic.
Q70intermediateCompare lifting state vs global store for cart.
Small app: context enough. Many features/analytics/persistence: Zustand/Redux with middleware. Server cart sync needs API layer regardless.
Q71intermediateScenario: Handle 401 globally in SPA.
Axios/fetch interceptor clears auth context, redirects login, optionally refresh token queue. React Query global onError mutation/query cache.
Q72beginnerScenario: Conditional hook call mistake.
`if(cond) useState()` breaks rules—extract child component `function Inner(){ const [x]=useState(); ...}` rendered conditionally instead.
Q73advancedScenario: List drag and drop state update.
Libraries dnd-kit compute new order; immutable reorder array; optimistic UI; keyboard a11y from library. Keys stable on items.
Q74advancedScenario: SSR auth cookie check.
Server reads HttpOnly cookie in loader/getServerSideProps; pass user to page props; client hydrates matching state; never expose raw token to JS.
Q75intermediateWhy not store derived data in state?
Derive `fullName = first + last` during render; storing duplicates source of truth and sync bugs. useMemo if expensive derivation.
Q76intermediateScenario: Modal open traps focus—implementation notes?
Focus first focusable, tab cycle inside, restore focus to trigger on close, lock body scroll, aria attributes. Use battle-tested headless component.
Q77advancedReact 19 useActionState pattern?
Form actions async transition pending state error result `const [state, action, pending] = useActionState(fn, initial)` progressive enhancement.
Q78intermediateControlled file input caveats?
Value read-only security reset form key remount clear selection upload same file twice onChange.
Q79intermediateReact Hook Form Controller when?
Wrap controlled third party MUI datepicker integrates validation schema Zod resolver.
Q80intermediateTesting async component waitFor?
`await waitFor(()=> expect(screen.getByText('Loaded')).toBeInTheDocument())` avoid bare wait fixed timeout flake.
Q81intermediateMSW in React tests benefit?
Mock network REST realistic handlers integration without mocking fetch implementation detail.
Q82beginnerStorybook role in React teams?
Isolate component states visual regression docs design QA accessibility addon.
Q83intermediateReact DevTools highlight re-renders?
Profiler flamegraph why did render props changed hook state context.
Q84beginnerAvoid defaultProps on functions?
ES6 default parameters preferred function Component({size= 'md'}) defaultProps legacy.
Q85advancedSlot pattern composition?
Pass children subcomponents Card Header Body flexible API Radix style asChild prop merge props.
Q86intermediateState colocation principle?
Keep state closest needs lift only when siblings share reduces rerender scope.
Q87advancedTaint API React experimental?
Mark data server never pass client sensitive prevent accidental leak RSC.
Q88advanceduse hook read promise context?
React 19 read promise resource suspend boundary experimental data fetching.
Q89advancedReact compiler automatic memo?
Forget compiler optimize memoization build time reduce manual useMemo cognitive load.
Q90intermediateKey on component remount reset state?
Change key prop force remount fresh state user switch profile `<Profile key={userId} />`.
Q91advancedSuspense list waterfall problem?
Nested suspense sequential fetch parallelize route loader single boundary or prefetch.
Q92intermediateReact native vs react-dom interview?
Different renderer native views bridge fabric not DOM styling flex default web skills transfer concepts.
Q93intermediateScenario: Pagination client vs server React?
Server page query params TanStack Query pageParam keepPreviousData smooth UX client slice all data small sets only.
Q94intermediateScenario: WebSocket live updates React?
useEffect subscribe cleanup setState merge events throttle burst connection status indicator reconnect backoff.
Q95intermediateScenario: Auth context flash wrong UI?
Loading state skeleton until session verified don't redirect unauthenticated before check completes.
Q96intermediateScenario: Share state between distant cousins?
Lift context Zustand URL state event bus last resort prop drilling acceptable few levels.
Q97intermediateScenario: React strict double fetch dev?
useEffect runs twice mount strict cleanup abort controller production once explain interview.
Q98intermediateScenario: Migrate class to function component?
Map state useState lifecycle useEffect getDerivedStateFromError error boundary stay class or react-error-boundary.
Q99beginnerScenario: Prevent layout shift loading skeleton?
Reserve min-height skeleton same dimensions content aspect-ratio placeholder CLS.
Q100intermediateScenario: i18n language switch rerender?
I18nextProvider change language all useTranslation hooks update key on language.
Q101beginnerWhat is `React.Fragment` and short syntax?
Fragments group children without an extra DOM node: `<React.Fragment>` or `<>...</>`. Use keyed fragments (`<Fragment key={id}>`) when mapping. Avoid unnecessary wrapper divs that break flex/grid or tables.
Q102intermediateWhy does Strict Mode double-invoke effects in development?
React 18+ Strict Mode mounts, unmounts, remounts to surface missing cleanup (subscriptions, timers). Production runs once. Write effects idempotent with proper cleanups. Don't disable Strict Mode to 'fix' double fetches—fix the effect.
Q103intermediateRedux Toolkit `createSlice` — what does it give you?
`createSlice` generates reducer + action creators from a name, initial state, and reducers map. Uses Immer so you 'mutate' state safely in reducers. Cuts boilerplate vs classic Redux switch statements. Export actions and reducer for the store.
Q104intermediateWhat is `createAsyncThunk`?
RTK helper that creates pending/fulfilled/rejected actions for async logic. Write a payload creator returning a Promise; handle cases in `extraReducers`. Centralizes loading/error patterns for API calls.
Q105advancedRTK Query overview?
Data-fetching/caching layer in Redux Toolkit: define `createApi` endpoints, auto-generate hooks (`useGetXQuery`), cache keys, invalidation tags, deduping. Reduces hand-rolled thunk+useEffect fetching. Prefer for CRUD-heavy apps already on Redux.
Q106intermediateWhen do you use React portals?
`createPortal(child, domNode)` renders children into a DOM node outside the parent hierarchy—modals, tooltips, toasts—to escape overflow/z-index stacking. Events still bubble through the React tree. Pair with focus traps and accessibility.
Q107advancedWhat does `flushSync` do?
`flushSync(() => setState(...))` forces synchronous DOM updates before continuing—escape hatch for measuring layout or integrating with non-React libraries. Avoid generally; it hurts performance and defeats batching. Prefer normal async updates.
Q108advanced`useTransition` vs `useDeferredValue`?
`useTransition` marks state updates as non-urgent (`startTransition`) so urgent input stays responsive. `useDeferredValue` defers a derived value lagging behind urgent input. Use for heavy lists/filtering while typing. Not a substitute for debouncing network calls.
Q109intermediateWhat is `useId` for?
Generates stable unique IDs for accessibility attributes (`htmlFor`/`aria-labelledby`) that match across SSR/CSR. Don't use as list keys. Prefer over incrementing global counters that mismatch hydration.
Q110advanced`useImperativeHandle` with `forwardRef`?
`forwardRef` lets parents pass a ref to a child. `useImperativeHandle(ref, () => ({ focus(){...} }))` customizes the imperative instance exposed—rare, for focus management or media controls. Prefer declarative props; use imperative handles sparingly.
Q111advancedReact 19 Actions / `use` — awareness?
React 19 expands form Actions, optimistic updates patterns, and `use()` to read resources/promises/context conditionally. Server Components continue evolving with frameworks. Interview: know CSR vs RSC boundaries and that `use` is not a replacement for all data fetching libraries yet.
Q112advancedServer Components vs client CSR — key difference?
RSC render on the server, can touch backend directly, ship less client JS, cannot use hooks/browser APIs. Client components hydrate and handle interactivity. Default to Server Components in Next.js app router; add `'use client'` at boundaries for state/effects.
Q113intermediateNext.js App Router basics?
File-based routes in `app/`: `page.tsx`, `layout.tsx`, `loading.tsx`, `error.tsx`. Nested layouts persist UI. Server Components by default; fetch on server with caching semantics. Use route handlers in `route.ts` for APIs. Prefer this over pages router for new apps.
Q114advancedWhat causes hydration mismatch errors?
Server HTML differs from client's first render: `Date.now()`, `Math.random()`, `window` checks without guards, invalid HTML nesting, locale/time differences. Fix by making initial render deterministic, using `useEffect` for client-only values, or suppressing only with documented caveats.
Q115intermediateKeys remount trick — changing key to reset state?
Changing a component's `key` forces React to unmount/remount, resetting state—useful to reset forms when `userId` changes (`<Editor key={id} />`). Don't use random keys every render (destroys performance/state). Keys should be stable identities among siblings.
Q116beginnerComposition with `children` vs prop drilling?
Pass `children` (or render slots) to let parents compose UI: `<Card><Header/><Body/></Card>`. Prefer composition over deeply threading props. Avoid cloning children to inject props when context or explicit props are clearer.
Q117intermediateWhat are render props? Why legacy?
A prop that is a function returning React nodes: `<DataProvider render={data => ...} />` or children-as-function. Historically solved cross-cutting before Hooks. Today hooks usually replace render props for reuse; still appears in older libs.
Q118beginnerControlled vs uncontrolled inputs in React?
Controlled: value from state + `onChange`. Uncontrolled: DOM holds value via `defaultValue`/`ref`. Prefer controlled for validation/UX; uncontrolled for simple forms or heavy integrations. Don't mix modes on the same input.
Q119beginnerWhy list keys shouldn't be the array index (often)?
Index keys break identity when reordering/inserting—state attaches to wrong items. Use stable IDs. Indexes are OK for static lists that never reorder. Interviewers expect this nuance.
Q120intermediateHow does React batch state updates?
React 18 batches updates in event handlers, timeouts, promises automatically. Multiple `setState` calls produce one re-render when possible. Use functional updates `setX(x => x+1)` when depending on previous state.
Q121advancedContext performance pitfall?
Any provider value change re-renders all consumers. Split contexts, memoize value objects, or use selectors (e.g., Zustand) for fine-grained subscriptions. Don't put rarely-and-frequently changing data in one giant context.
Q122intermediateError boundaries — what do they catch?
Class boundaries catch render/lifecycle/constructor errors in children, not event handlers, async, or SSR sometimes. Provide fallback UI. Pair with logging. Hooks don't create error boundaries—need class or libraries.
Q123intermediate`memo` / `useMemo` — when justified?
After measuring: expensive pure subtrees or stable referential equality for child props. React Compiler may memoize automatically in newer setups—follow project guidance; don't sprinkle everywhere.
Q124beginnerHow do you prevent forms from re-submitting in React?
Disable submit button while pending, use AbortController, debounce, and idempotency keys on the API. For React 19 actions, pending state is built-in. Handle double-click and Enter key.
Q125intermediateClient-only component pattern in Next.js?
Add `'use client'` at top, or dynamic import with `ssr: false` for browser-only libs (maps, rich editors). Keep client islands small. Don't mark entire trees client without need.
Q126beginnerWhat is prop drilling and how do you fix it?
Passing props through many intermediate components that don't use them. Fix with composition, context, or state libraries—pick based on update frequency and locality.
Q127advancedSuspense for data — awareness?
Suspense shows fallback while children 'suspend' on promises (framework-integrated fetch). Works with concurrent features. Exact semantics differ CSR vs RSC frameworks—speak in terms of your stack (Next.js).
Q128beginnerHow does `useEffect` dependency array work?
Runs after paint when dependencies change (Object.is). Empty [] = mount/unmount only. Missing deps cause stale closures; overbroad deps cause loops. Exhaustive-deps lint rule exists for a reason.
Q129intermediateRedux vs Context vs React Query — choose?
Server state (cache, sync): React Query/RTK Query. Global client UI state: Context if rare updates, Redux/Zustand if complex. Don't put all server cache into Redux manually without tooling.
Q130beginnerWhat is lifting state up?
Move state to the nearest common ancestor so siblings can share data via props. Classic React pattern before reaching for global stores. Keep state as local as possible.
Q131advancedPortals and accessibility for modals?
Portal to `document.body`, trap focus, restore focus on close, Esc to dismiss, `aria-modal`, label with `aria-labelledby`, hide background with `inert`. Native `<dialog>` reduces DIY risk.
Q132intermediateWhy avoid deriving state that can be computed?
Duplicating props into state causes desync bugs. Compute during render or useMemo when expensive. Sync with `useEffect` only when truly mirroring external systems.
Q133intermediateExplain controlled `key` on a form to reset fields.
When switching entities, `key={entityId}` remounts the form with fresh state instead of patching many `useEffect` resets. Cleaner than dozens of setters.
Q134advancedWhat does `startTransition` wrap?
Non-urgent updates like filtering a large list or navigating. Urgent updates (typing into input) stay snappy. Combine with `isPending` UI indicators from `useTransition`.
Q135advancedforwardRef TypeScript tip briefly?
`forwardRef<HTMLInputElement, Props>((props, ref) => ...)` types the ref correctly. In React 19, ref may be a regular prop—know your React version's API.
Q136intermediateWhat is the Next.js App Router?
App Router is Next.js's file-system routing under `app/` using React Server Components by default, nested layouts, and conventions like `page.tsx`, `layout.tsx`, and `loading.tsx`. It replaces many Pages Router patterns with server-first defaults. Client components opt in with `'use client'`. Interviewers expect you to contrast it with the older `pages/` router.
Q137intermediateSSR vs SSG vs ISR in Next.js?
SSR renders HTML per request—fresh but higher TTFB cost. SSG prebuilds HTML at build time—fast/cheap for static content. ISR revalidates static pages on a timer or on-demand so content updates without full rebuilds. Choose based on freshness needs and traffic. Hybrid apps mix modes per route.
Q138advancedServer Components vs Client Components?
Server Components render on the server, can touch data/secrets, and ship no client JS for themselves. Client Components handle interactivity, state, and browser APIs and must be marked `'use client'`. Push interactivity to the leaves; keep heavy data fetching on the server. Do not import server-only modules into client files.
Q139advancedWhat causes React hydration mismatches?
Server HTML must match the client's first render. Divergence comes from `Date.now()`, random IDs, locale-dependent formatting, or invalid HTML nesting. Fix by using stable rendering, `suppressHydrationWarning` sparingly, or rendering time-dependent UI only after mount. Mismatches force client re-renders and hurt performance.
Q140intermediateWhat does `loading.tsx` do in App Router?
It automatically wraps the segment in a React Suspense boundary and shows instant loading UI while server content streams in. Improves perceived performance without manual Suspense wiring for that route. Combine with meaningful skeletons. Nested routes can each define their own loading UI.
Q141advancedExplain Next.js middleware.
Middleware runs on the Edge before a request completes—useful for auth redirects, A/B bucketing, rewrites, and headers. Keep it lightweight; heavy logic belongs in server handlers. Configure matchers carefully to avoid running on every static asset. Mistakes here can break caching or create redirect loops.
Q142intermediateHow do route handlers relate to API routes in App Router?
`route.ts` files export HTTP method handlers (`GET`, `POST`) replacing many `pages/api` use cases. They run on server/edge runtimes you choose. Still validate inputs and auth like any backend. Prefer Server Actions or route handlers thoughtfully—do not expose privileged logic to the client.
Q143advancedWhat are Server Actions in Next.js?
Server Actions are server-side functions you can call from forms/components to mutate data without hand-writing API endpoints. They reduce boilerplate but still need authz, validation, and CSRF considerations. Use progressively enhanced forms when possible. Treat them as public entry points.
Q144advancedHow does streaming work with SSR in Next?
React streams HTML as Suspense boundaries resolve so users see shells sooner while slow data loads continue. Pair with `loading.tsx` and selective suspense. Improves TTFB perception on data-heavy pages. Avoid blocking the entire page on one slow query.
Q145beginnerWhen prefer Pages Router knowledge still?
Legacy codebases and some tutorials still use `pages/`; `_app`, `getServerSideProps`, and `getStaticProps` remain common interview topics. Understand migration paths to App Router. Many companies run hybrid apps during migration. Knowing both shows practicality.
Q146intermediateHow do you share layout state across App Router pages?
Use nested `layout.tsx` for persistent chrome; lift client state into client layout components or external stores. Server layouts cannot hold interactive React state. URL search params often replace unnecessary global state. Design server/client boundaries intentionally.
Q147advancedWhat is partial prerendering awareness?
Emerging Next/React capabilities combine static shell with dynamic holes streaming later. Goal is static performance with dynamic freshness. Exact APIs evolve—speak conceptually about static shell + dynamic islands. Shows you follow modern React/Next direction.
Q148beginnerHow do image optimizations work in Next?
`next/image` handles resizing, modern formats, and lazy loading with layout stability. Requires allowed image domains configuration. Improves LCP when used correctly. Avoid turning off optimization without reason.
Q149advancedCaching in Next.js App Router—mental model?
Fetch caching, `revalidate`, and route segment configs control freshness. Default caching behaviors have changed across versions—verify current docs. Over-caching auth-specific data is a footgun. Be explicit for personalized pages.
Q150advancedHow do you test Server Components?
Prefer integration/e2e for full routes; unit-test pure utilities extracted from server components. Mock data access at boundaries. Client components still use React Testing Library. Adjust strategy because RSC is not a browser runtime.
Q151beginnerClient-side navigation benefits in Next?
`next/link` prefetches and does client transitions without full reloads, preserving layout state. Still need proper loading/error UI for segments. Prefetch can increase network use—tune for low-end clients. Accessibility of routing remains important.
Q152beginnerEnvironment variables: `NEXT_PUBLIC_` meaning?
Vars prefixed `NEXT_PUBLIC_` are inlined into the client bundle—never put secrets there. Server-only secrets stay unprefixed and accessible only on server. Misprefixing leaks API keys. Classic Next interview security check.
Q153intermediateError handling with `error.tsx`?
Segment-level error boundaries catch rendering errors and show fallback UI with recovery. Differs from `not-found.tsx` for 404s. Log errors to monitoring from these boundaries. Improves resilience of nested routes.
Q154intermediateWhen would you still use a separate React SPA instead of Next?
Highly interactive apps with existing Vite tooling, no SEO needs, or simple static hosting may not need Next. Next shines for SSR/SEO, hybrid rendering, and integrated routing. Choose based on constraints, not hype. Honest tradeoffs impress interviewers.
Q155advancedHow do parallel routes / intercepting routes help?
Advanced App Router features for simultaneous slots (dashboards) and modal URL patterns without losing deep links. Useful for sophisticated UX. Complexity cost is real—adopt when product needs them. Shows deeper Next literacy.
Angular
107 questions
Q1beginnerWhat is Angular and how does it differ from a library like React?
Angular is a full framework for building SPAs: routing, forms, HTTP, DI, and build tooling are first-party. React is a UI library—you choose router, state, and data-fetching. Angular uses TypeScript by default, templates with its own syntax, and a strong opinionated structure. Choose Angular for large enterprise apps that want consistency; React when you want compositional freedom. Interview tip: emphasize trade-offs, not which is better.
Q2beginnerWhat is a component in Angular?
A component is a TypeScript class decorated with @Component that owns a template, styles, and behavior for a UI slice. Metadata includes selector, templateUrl or template, styleUrls, and often standalone: true in modern Angular. Components communicate via @Input/@Output and services. They are the primary building block you compose into pages.
Q3intermediateExplain standalone components vs NgModules.
Standalone components declare their own imports (other components, directives, pipes, router pieces) without an NgModule. Since Angular 14+ and especially 15+, standalone is the recommended default for new apps. NgModules group declarations/imports/exports and still exist in many codebases. Migration path: convert feature by feature; both can coexist. Common mistake: forgetting to import CommonModule or the needed directives in standalone imports.
Q4beginnerWhat does an NgModule do?
@NgModule declares components/directives/pipes, imports other modules, exports what other modules can use, and can provide services. AppModule historically bootstrapped the app. Feature modules and shared modules organize large apps. With standalone, you may skip NgModules entirely, but interviews still expect you to explain them for legacy and hybrid apps.
Q5beginnerName the four types of data binding in Angular.
Interpolation {{ value }} binds expression to text. Property binding [prop]="expr" sets a DOM or component property. Event binding (event)="handler()" listens to events. Two-way binding [(ngModel)]="prop" combines property plus event (requires FormsModule). Common mistake: confusing attribute binding [attr.aria-label] with property binding when the DOM property does not exist.
Q6intermediateWhat is the difference between property binding and interpolation?
Interpolation is sugar for text content and some attributes; property binding can set any property including objects and booleans. Use [disabled]="isDisabled" not disabled="{{isDisabled}}" because the string 'false' is truthy. Prefer property binding for non-string values. Both are one-way from component to view.
Q7beginnerHow does two-way binding with ngModel work?
[(ngModel)]="name" expands to [ngModel]="name" (ngModelChange)="name = $event". It keeps form control and component property in sync for template-driven forms. Import FormsModule or include NgModel in standalone imports. Prefer reactive forms for complex validation; ngModel is fine for simple forms.
Q8intermediateStructural vs attribute directives—examples?
Structural directives change DOM layout: *ngIf, *ngFor, *ngSwitch (asterisk desugars to ng-template). Attribute directives change appearance or behavior of an element: ngClass, ngStyle, custom @Directive with HostBinding/HostListener. Custom structural directives use TemplateRef and ViewContainerRef.
Q9beginnerExplain *ngIf and *ngFor and a common pitfall.
*ngIf="condition" adds or removes the element from the DOM (unlike CSS hide). *ngFor="let item of items; trackBy: trackId" repeats a template. You cannot put two structural directives on the same host—wrap with ng-container. Always use trackBy on large lists to avoid recreating DOM nodes on every change detection.
Q10beginnerWhat is ng-container and when do you use it?
ng-container is a grouping element that does not render a real DOM node. Use it to host *ngIf/*ngFor without extra wrappers that break CSS or HTML semantics. Also useful for projecting multiple roots or wrapping ngTemplateOutlet. Prefer it over a useless div when structure matters.
Q11intermediateWhat are pipes? Pure vs impure?
Pipes transform displayed values in templates: {{ date | date:'short' }}, {{ list | json }}. Pure pipes (default) re-run only when input references change—efficient. Impure pipes re-run every change detection—use sparingly. Custom pipes implement PipeTransform.transform. Prefer component logic or computed signals for heavy transforms.
Q12intermediateHow do you create a custom pipe?
@Pipe({ name: 'truncate', standalone: true }) class TruncatePipe implements PipeTransform { transform(value: string, limit = 20) { return value?.length > limit ? value.slice(0, limit) + '…' : value; } }. Import it in the standalone component or declare in NgModule. Keep pipes pure and synchronous when possible; async data belongs with async pipe and Observables.
Q13beginnerWhat is a service and why use providedIn: 'root'?
Services hold shared logic and state (API clients, auth, stores) injected via DI. providedIn: 'root' registers a singleton in the root injector and is tree-shakable if unused. Feature-scoped providers on a component or route create new instances for that subtree. Common mistake: providing the same service both in root and in a component, creating duplicate instances.
Q14advancedExplain Angular's dependency injection hierarchy.
Injectors form a hierarchy: element injectors (components/directives) to module/environment injectors to root to platform. Angular looks up the injector tree for a token. Providing at a component creates a new instance for that component and children. Environment injectors matter for lazy routes. Understanding hierarchy explains why my service state is empty bugs.
Q15beginnerHow do you inject HttpClient and make a GET request?
Provide provideHttpClient() in app config (or import HttpClientModule in older apps). Inject HttpClient and call this.http.get<User[]>('/api/users') which returns an Observable. Subscribe in the component, use async pipe, or convert with signals/firstValueFrom. Always type the response and handle errors with catchError.
Q16advancedmap vs switchMap vs mergeMap vs concatMap vs exhaustMap?
map transforms emitted values. switchMap cancels prior inner Observable—ideal for search typeahead. mergeMap runs inner Observables concurrently—parallel requests. concatMap queues sequentially—ordered writes. exhaustMap ignores new triggers while inner is active—login button double-submit. Choosing wrong operator causes race conditions or lost updates.
Q17intermediateWhat does debounceTime do and when use it?
debounceTime(300) waits until emissions pause for 300ms before forwarding—classic for search inputs. Pair with distinctUntilChanged and switchMap to the HTTP call. Without it, every keystroke hits the API. Common mistake: putting debounce after switchMap instead of on the input stream.
Q18advancedcatchError and shareReplay—what problems do they solve?
catchError recovers from errors in a pipe, often returning of(fallback) or rethrowing via throwError. Without it, an errored Observable dies for all subscribers. shareReplay({bufferSize:1, refCount:true}) multicasts and caches last value so late subscribers get data without re-hitting HTTP. Use shareReplay carefully with refCount to avoid leaking subscriptions.
Q19intermediateSubject vs BehaviorSubject vs ReplaySubject vs AsyncSubject?
Subject is a hot multicast Observable with no initial value—late subscribers miss prior emissions. BehaviorSubject requires an initial value and replays the latest to new subscribers—great for current auth/user state. ReplaySubject buffers N past values. AsyncSubject emits only the last value on complete—rare in UI apps. Prefer BehaviorSubject or signals for app state.
Q20intermediateWhat is the async pipe and why prefer it?
{{ users$ | async }} subscribes to an Observable or Promise and unwraps the value in the template, unsubscribing automatically on destroy. It marks the view for check when new values arrive—works well with OnPush. Avoids manual subscribe/unsubscribe leaks. Common mistake: using async pipe multiple times on the same Observable without shareReplay, causing duplicate HTTP calls—use *ngIf="users$ | async as users" once.
Q21advancedDefault vs OnPush change detection?
Default checks the whole component tree when any async event runs (zone.js). OnPush checks a component only when its @Input references change, events originate from the component or children, or you markForCheck/async pipe/signals update. OnPush plus immutability improves performance on large lists. Common mistake: mutating arrays/objects in place with OnPush—view will not update.
Q22intermediateWhat are Angular signals (signal, computed, effect)?
Signals are reactive primitives: count = signal(0), update with count.set(1) or count.update(c => c+1). computed(() => count() * 2) derives values lazily and caches. effect(() => ...) runs side effects when dependencies change. Signals integrate with change detection and reduce Zone reliance. Prefer signals for local UI state; Observables still fit streams and HttpClient.
Q23beginnerList key lifecycle hooks and when they run.
ngOnChanges when @Input changes; ngOnInit once after first inputs; ngDoCheck custom change detection; ngAfterViewInit after view children ready; ngAfterContentInit after projected content; ngOnDestroy cleanup. Prefer constructor for DI only; put init logic that needs inputs in ngOnInit. Unsubscribe and clear timers in ngOnDestroy or use takeUntilDestroyed.
Q24intermediateHow does Angular routing and lazy loading work?
Configure routes with provideRouter([...]) or RouterModule.forRoot. Lazy load: loadComponent: () => import('./page').then(m => m.Page) or loadChildren for modules. Lazy loading splits bundles so features download on demand. Use preloadingStrategy for UX balance. Guard routes so lazy chunks are not fetched for unauthorized users when possible (CanMatch).
Q25advancedCanActivate vs CanMatch vs resolvers?
CanActivate decides if a route can activate (boolean, UrlTree, or Observable). CanMatch (preferred for lazy) decides if a route config is eligible to match—can prevent loading the lazy bundle. Resolvers prefetch data before activation via ResolveFn. Prefer functional guards in modern Angular. Do not put heavy logic in resolvers that belongs in the component with loading UI.
Q26intermediateTemplate-driven vs reactive forms?
Template-driven: ngModel, directives in template, simpler for small forms, harder to unit test. Reactive: FormGroup/FormControl/FormArray in TypeScript, explicit validators, better for dynamic complex forms and testing. Most enterprise apps prefer reactive forms. Example: new FormGroup({ email: new FormControl('', [Validators.required, Validators.email]) }).
Q27intermediateHow do you add custom validators in reactive forms?
A validator is (control: AbstractControl) => ValidationErrors | null. Sync: Validators.minLength(8) or custom passwordMatch. Async validators return Observable/Promise of errors—use for unique username checks; set updateOn: 'blur' to avoid spam. Attach via FormControl constructor or setValidators. Display with control.hasError('required') and touched/dirty checks.
Q28intermediateWhat are HTTP interceptors used for?
Interceptors sit in the HttpClient pipeline to mutate requests/responses centrally: attach JWT Authorization headers, show loading spinners, refresh tokens, log, or normalize errors. Provide with provideHttpClient(withInterceptors([authInterceptor])) or class-based HTTP_INTERCEPTORS. Common mistake: infinite loops when refresh interceptor retries without a skip flag.
Q29intermediateHow would you attach a JWT in an interceptor?
Functional example: authInterceptor: HttpInterceptorFn = (req, next) => { const token = inject(AuthService).token; return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req); }. Skip auth header for login and public URLs. Prefer httpOnly cookies when possible. Handle 401 by refresh-or-logout once.
Q30advancedNgRx basics—what problem does it solve?
NgRx is Redux-style state: Store holds immutable state, Actions describe events, Reducers update pure state, Effects handle side effects (HTTP). Use for complex shared client state with many contributors. Overkill for small apps—signals, services with BehaviorSubject, or ComponentStore may suffice. Mention selectors for derived state and DevTools for debugging.
Q31intermediateWhy is trackBy important in *ngFor?
Without trackBy, Angular destroys and recreates DOM nodes when the array reference changes even if items are the same—hurting performance and losing input focus. trackBy: (i, item) => item.id reuses nodes for matching identities. With @for (item of items; track item.id), tracking is required. Always track by stable business ids, not array index (index fails on reorder/insert).
Q32intermediateViewChild vs ContentChild?
@ViewChild queries elements/components in the component's own template. @ContentChild queries projected content (ng-content). Both available after ngAfterViewInit/ngAfterContentInit respectively (or as signals in newer APIs). Common mistake: reading ViewChild in ngOnInit—it may be undefined. Use { static: true } only when needed for static templates.
Q33intermediateExplain content projection with ng-content.
ng-content projects parent-supplied markup into a child component's template—like React children. Selectors: ng-content select="[header]" for multi-slot projection. Projected content is owned by the parent for DI and change detection context. Use for reusable cards, modals, and layouts. Do not assume projected nodes always exist.
Q34intermediateAngular vs React—what do interviewers want to hear?
Angular: batteries-included, DI, RxJS-centric, templates plus TypeScript, strong conventions, steeper learning curve. React: JSX/functions, ecosystem choice, hooks, lighter core, more decisions. Both can build large apps; hiring and team skills often decide. Mention change detection (Zone/signals vs VDOM) and forms/routing as built-in vs library. Avoid fanboy answers.
Q35advancedAOT vs JIT compilation?
AOT (Ahead-of-Time) compiles templates to JS at build time—faster startup, earlier template errors, default in production Angular builds. JIT (Just-in-Time) compiles in the browser—historically used in dev; largely irrelevant for modern ng build which uses AOT. Production always AOT for performance and security (no template compiler in bundle).
Q36advancedWhat is zone.js and what is zoneless Angular?
zone.js patches async APIs so Angular knows when to run change detection. Zoneless Angular relies on signals and explicit notifications instead of zones—smaller bundles, clearer update model. Many apps still use Zone; new apps may adopt zoneless with signals. Awareness shows you follow modern Angular.
Q37intermediateBriefly explain Angular Universal / SSR.
Angular Universal renders pages on the server for faster First Contentful Paint and better SEO, then hydrates on the client. Use provideClientHydration() in modern setups. Avoid browser-only APIs (window, localStorage) without isPlatformBrowser guards. SSR matters for marketing/content sites; pure authenticated dashboards may stay CSR.
Q38intermediateHow do you unit test a component with TestBed?
TestBed.configureTestingModule({ imports: [MyComponent, ...] }) then fixture = TestBed.createComponent(MyComponent). Set inputs, fixture.detectChanges(), query with fixture.nativeElement or DebugElement. Mock services via providers: [{ provide: Api, useValue: mock }]. Prefer testing behavior over implementation. For standalone, import the component directly.
Q39beginnerHow do environment configs work in Angular?
Classic pattern: environment.ts vs environment.prod.ts replaced at build via fileReplacements in angular.json. Newer apps use runtime config JSON fetched before bootstrap for the same build across envs. Never put secrets in frontend environments—only public API URLs and keys meant for browsers.
Q40intermediateHow do you handle HTTP errors globally?
Interceptor catches failures with catchError, maps to user-friendly messages, redirects on 401, and rethrows or returns fallback. Component-level: pipe catchError on specific calls. Show toast via a notification service. Do not swallow errors silently—log with correlation ids. Distinguish network errors vs 4xx vs 5xx in UX.
Q41beginnerWhat is the Angular CLI and why use it?
ng new, ng generate component, ng serve, ng build, ng test standardize scaffolding and builds. CLI configures TypeScript, testing, and optimization. Prefer CLI schematics for consistent project structure in teams. Custom builders exist but start with defaults.
Q42beginnerExplain @Input and @Output with an example.
@Input() user!: User receives data from parent [user]="selected". @Output() saved = new EventEmitter<User>() sends events (saved)="onSave($event)". Prefer immutable inputs and emit events upward—one-way data flow. Signals-based inputs/outputs (input(), output()) are the modern alternative.
Q43intermediateWhat is a directive selector and host binding?
Selector like [appHighlight] applies the directive as an attribute. @HostBinding('class.active') isActive sets host properties; @HostListener('click', ['$event']) onClick listens. Keep directives focused on cross-cutting DOM behavior. Prefer components when you need a template.
Q44beginnerngClass vs ngStyle vs class bindings?
[class.active]="isOn" or [ngClass]="{ active: isOn, disabled: !ok }" toggle classes. [style.width.px]="w" or ngStyle set styles. Prefer class bindings plus CSS over heavy ngStyle. With new control flow, class/style bindings remain the same.
Q45intermediateWhat is the new control flow (@if, @for, @switch)?
Angular 17+ built-in control flow: @if (user) { ... } @else { ... }, @for (item of items; track item.id) { ... }, @switch. It is faster and does not need CommonModule imports. Prefer it over *ngIf/*ngFor in new code. track is mandatory in @for—good performance habit.
Q46beginnerExplain RouterLink and RouterLinkActive.
routerLink="/users" or [routerLink]="['/users', id]" navigates without full page reload. routerLinkActive="active" adds classes when the route matches; use routerLinkActiveOptions for exact matching. Prefer these over href to keep SPA state. Absolute vs relative links matter inside nested routes.
Q47beginnerWhat are route parameters and query params?
Required params: /users/:id via route.snapshot.paramMap.get('id') or route.paramMap Observable. Query params: ?page=2 via queryParamMap. Prefer Observables when params can change while component is reused. Snapshot is fine when component is created fresh each navigation.
Q48intermediateHow do nested routes and router-outlet work?
Parent template has router-outlet; children render inside. Layout routes share chrome (nav/sidebar). Configure children: [...] under a parent path. Multiple named outlets exist for advanced layouts. Common mistake: forgetting a secondary outlet name when using auxiliary routes.
Q49advancedWhat is APP_INITIALIZER?
A multi-provider that runs functions before bootstrap—load runtime config, feature flags, or auth session. Return Promise/Observable to delay start. Overuse slows startup; keep it minimal. Modern alternative: provideAppInitializer. Failures can block the app—handle errors gracefully.
Q50advancedExplain ChangeDetectorRef.detectChanges vs markForCheck.
detectChanges() runs change detection immediately on this view. markForCheck() marks the path to root so the next CD cycle checks OnPush components. Prefer markForCheck with async work outside Angular zone. Signals often remove the need for manual calls.
Q51intermediateHow do you unsubscribe from Observables safely?
Use async pipe, takeUntilDestroyed(), DestroyRef, or subscribe with teardown. Avoid leaked subscriptions in services that outlive components. Manual Subscription arrays are older style—still correct if cleaned in ngOnDestroy.
Q52intermediatefirstValueFrom vs lastValueFrom vs toSignal?
firstValueFrom(obs) converts first emission to a Promise—useful in async functions. lastValueFrom waits for completion. toSignal(obs) bridges RxJS into signals for templates. Do not use firstValueFrom on streams that never emit without timeout—it hangs forever.
Q53advancedWhat is a resolver vs loading data in ngOnInit?
Resolvers delay navigation until data is ready—good for SEO/critical data, but can make navigations feel blocked. Loading in component shows skeleton UI and cancels via switchMap on param changes. Prefer component loading for most dashboards; resolvers for rare cases needing guaranteed data before paint.
Q54intermediateHow does Angular encapsulation (ViewEncapsulation) work?
Emulated (default) rewrites CSS selectors with attributes so styles do not leak. ShadowDom uses real Shadow DOM. None applies global styles. Prefer Emulated; use :host and ::ng-deep sparingly (ng-deep deprecated). Global styles belong in styles.css.
Q55beginnerWhat are Angular animations used for?
@trigger transitions for enter/leave/state changes via @angular/animations. Use for meaningful motion (drawer, list reorder), not noise. Prefer CSS for simple transitions when possible. Disable animations for prefers-reduced-motion accessibility.
Q56intermediateExplain inject() vs constructor injection.
inject(Service) can be called in injection context (constructor, field initializers, factory functions, router guards). Cleaner for functional guards and reducing constructor boilerplate. Constructor injection remains valid. Do not call inject() asynchronously outside injection context.
Q57intermediateHow do you protect routes based on roles?
Auth guard reads user roles from AuthService/JWT claims and returns true or UrlTree to /login or /forbidden. Prefer CanMatch for lazy modules. Never rely only on frontend guards—API must authorize. Encode roles as claims; refresh permissions on login.
Q58intermediateFormArray use case?
FormArray holds a dynamic list of controls—phone numbers, order line items. Push/remove controls as UI grows. Validate the array length. Template iterates formArr.controls with index. Common in reactive forms interviews.
Q59beginnerWhat is dirty, touched, pristine, valid on controls?
Pristine/dirty: user changed value or not. Untouched/touched: blurred or not. Valid/invalid/pending: validator state. UX pattern: show errors when invalid && (dirty || touched) or after submit. markAllAsTouched() on submit reveals all errors.
Q60intermediateHow do you share state between unrelated components?
Lift to a service with signals/BehaviorSubject, use a store (NgRx), or route state/query params for shareable filters. Avoid huge @Input chains (prop drilling). Event buses via plain Subjects work but are harder to trace—prefer explicit services.
Q61advancedWhat is HttpClient testing with HttpClientTestingModule?
Provide testing module, inject HttpTestingController, trigger code, httpMock.expectOne(url).flush(data), verify no outstanding requests. Assert method and headers. Prevents real network calls in unit tests. Essential for service tests.
Q62beginnerExplain path vs hash location strategies.
PathLocationStrategy uses clean URLs (/users/1)—needs server rewrite to index.html. HashLocationStrategy uses /#/users/1—works on static hosts without rewrite. Prefer Path with proper server config. SSR and SEO favor Path.
Q63beginnerWhat is a smart vs presentational component?
Smart/container: talks to services, store, router. Presentational: @Input/@Output only, reusable, easier to test. Keeps templates simple and logic concentrated. Similar to React container/presentational pattern.
Q64advancedHow do you optimize Angular bundle size?
Lazy routes, standalone tree-shaking, avoid importing whole libraries, analyze with source-map-explorer, OnPush/signals, careful third-party imports, disable unused polyfills. Production budgets in angular.json fail CI on regressions.
Q65intermediateWhat is ng-template vs ng-container vs ng-content?
ng-template defines a template not rendered until stamped (structural directives, TemplateRef). ng-container groups without DOM. ng-content projects parent content. Mixing them up is a common interview trap—explain each in one sentence.
Q66advancedExplain TemplateRef and ViewContainerRef.
TemplateRef is a handle to an embedded template. ViewContainerRef inserts/clears embedded or host views—how structural directives work. Used for dynamic component loading (createComponent) and portals. Powerful but easy to leak views if not cleared.
Q67advancedHow does Angular handle XSS by default?
Templates sanitize bindings; interpolation escapes HTML. Bypass with DomSanitizer.bypassSecurityTrustHtml only for trusted content. Prefer Angular bindings over innerHTML. Still validate backend and use CSP. Never bypass sanitizer for user-generated HTML without a proper sanitizer.
Q68intermediateWhat are functional guards and interceptors?
Plain functions instead of classes: export const authGuard: CanActivateFn = () => inject(Auth).isLoggedIn() || inject(Router).createUrlTree(['/login']);. Less boilerplate, easier tree-shaking. Preferred in Angular 15+. Classes still work in older code.
Q69beginnerDescribe a typical Angular app folder structure.
app/core (singleton services, interceptors), shared (reusable UI), features/feature-name (routed feature), layouts. Keep features lazy-loaded. Avoid dumping everything in AppModule. Consistency matters more than exact names.
Q70intermediateHow do signals replace some RxJS patterns?
Local UI state, derived values (computed), and simple reactions (effect) fit signals. Keep RxJS for HTTP, WebSockets, complex async composition. toSignal/toObservable bridge both worlds. Do not rewrite every Observable—use the right tool.
Q71intermediateWhat is provideRouter and bootstrapApplication?
Standalone bootstrap: bootstrapApplication(AppComponent, { providers: [provideRouter(routes), provideHttpClient()] }). Replaces platformBrowserDynamic().bootstrapModule(AppModule) in modern apps. Providers configure DI at root. Know both for migrating interviews.
Q72intermediateExplain CanDeactivate for unsaved changes.
Guard prompts when navigating away from dirty forms: return confirm dialog boolean or UrlTree. Implement as functional guard reading component state. Do not annoy users on pristine forms. Pair with beforeunload carefully for browser close.
Q73advancedHow do you internationalize (i18n) in Angular?
Angular i18n with @angular/localize and build-time locale variants, or runtime libraries like ngx-translate. Build-time is strong for performance; runtime is flexible for language switching. Format dates/numbers with locale pipes. Plan message IDs early.
Q74advancedWhat is a custom structural directive sketch?
Inject TemplateRef and ViewContainerRef; in ngOnChanges clear and createEmbeddedView when condition true. That is how *appUnless works. Prefer built-in control flow unless you need reusable structural behavior.
Q75advancedSSR hydration mismatch—what causes it?
Server HTML differs from client's first render—random IDs, Date.now(), browser-only branching. Fix by guarding browser APIs, using stable IDs, and enabling proper hydration. Mismatches cause re-renders and warnings. Critical for Universal apps.
Q76beginnerHow do you call a child method from a parent?
@ViewChild(Child) child! then this.child.refresh() after view init. Prefer @Output events or shared services over tight coupling. Template ref variables #child also work for simple cases. Overuse indicates design smell.
Q77intermediateExplain Observables being lazy vs Promises.
Observables do not execute until subscribed (cold HTTP); Promises start immediately and cache one result. Observables are cancellable via unsubscribe/switchMap; Promises are not. Multiple subscribers can retrigger cold Observables—use shareReplay when needed.
Q78advancedWhat is exhaustMap good for in Angular UI?
Prevent duplicate in-flight submits: button click then exhaustMap(() => this.api.save()). Extra clicks ignored until the request completes. switchMap would cancel the in-flight save—bad for writes. concatMap queues every click—may over-save.
Q79advancedHow do environment injectors relate to lazy routes?
Lazy-loaded routes get their own environment injector for provided services—scoped singletons per lazy feature. Providing in route providers array scopes DI. Explains why a singleton is not shared across lazy features if provided there.
Q80intermediateUnit testing pipes and services without TestBed?
Pipes: new MyPipe().transform(input) directly. Services with no DI deps: instantiate with mocks. Use TestBed when DI graph is complex. Prefer fast, focused tests. Do not TestBed everything blindly.
Q81intermediateWhat is Angular CDK?
Component Dev Kit provides a11y, overlay, drag-drop, virtual scroll primitives without Material styling. Use CDK virtual scroll for large lists. Overlays power dropdowns/modals. Shows enterprise UI depth beyond basic components.
Q82advancedHow does virtual scrolling help performance?
Renders only visible rows plus a buffer instead of thousands of DOM nodes. Use CDK cdk-virtual-scroll-viewport with fixed item sizes. Combine with trackBy/OnPush. Not a substitute for pagination on huge server datasets—still page from API.
Q83intermediateExplain pure component mindset in Angular.
Same inputs yield same UI; no hidden mutation; OnPush-friendly. Emit events instead of mutating inputs. Use immutable updates: return new arrays/objects. Signals make this pattern more natural. Interviewers link this to change detection performance.
Q84intermediateHow do you handle file uploads with HttpClient?
Build FormData, http.post(url, formData) without manually setting Content-Type (browser sets multipart boundary). Show progress via reportProgress: true, observe: 'events'. Validate size/type client-side and server-side. Do not base64 huge files into JSON.
Q85intermediateWhat is a guard returning UrlTree?
Instead of boolean false, return router.createUrlTree(['/login'], { queryParams: { returnUrl } }) for proper redirect navigation. Better cancelation/redirect semantics than imperative navigate inside guards. Functional guards make this concise.
Q86advancedHow do you debug ExpressionChangedAfterItHasBeenCheckedError?
Often updating state in ngAfterViewInit causing a second binding change in dev mode. Fix: move update earlier, use carefully scheduled updates, or ChangeDetectorRef.detectChanges intentionally. Dev-mode double-check surfaces impure side effects—do not ignore it.
Q87advancedWhat is provideHttpClient(withFetch())?
Optional fetch backend instead of XHR for HttpClient—better alignment with Fetch API features. Awareness question for modern Angular. Interceptors still apply. Know that some progress events differ vs XHR.
Q88advancedHow would you structure auth token refresh?
Interceptor catches 401, queues concurrent requests, calls refresh endpoint once, retries with new token, or logs out on failure. Use a single refresh Subject to avoid stampedes. Prefer rotating refresh tokens httpOnly. Avoid long-lived tokens in localStorage if XSS is a concern without mitigations.
Q89beginnerWhat is ActivatedRoute vs Router?
Router navigates and inspects full config. ActivatedRoute is the route instance for this component—params, data, parent. Inject ActivatedRoute in routed components. Do not confuse router.url string parsing with paramMap.
Q90advancedExplain host directives (Angular 15+).
Reusable directive behavior applied via hostDirectives on a component/directive metadata—composition without inheritance. Example: share disabled-state behavior. Modern alternative to deep class hierarchies. Good signal of up-to-date Angular knowledge.
Q91intermediateHow do you use async validators with pending UI?
Control status becomes PENDING while async validator runs—disable submit or show spinner via control.status === 'PENDING'. Debounce async validators. Cache last result for same value. Common in username availability checks.
Q92advancedWhat is ngZone.run and runOutsideAngular?
runOutsideAngular for high-frequency events (mousemove, polling) to avoid CD thrash; re-enter with ngZone.run when UI must update. With zoneless/signals, patterns change. Useful performance interview topic.
Q93intermediateDescribe error handling with ErrorHandler.
Implement custom ErrorHandler to log to monitoring (Sentry) and show global UI. Provide in root. Catch unexpected exceptions; expected HTTP errors often handled in interceptors. Do not double-report handled errors.
Q94intermediateHow do reactive form valueChanges streams work?
this.form.valueChanges.pipe(debounceTime(300), distinctUntilChanged()) reacts to edits for autosave/search. Unsubscribe properly. statusChanges tracks validity. Use emitEvent: false when patching programmatically to avoid loops.
Q95advancedWhat is a multi-provider in Angular DI?
Tokens like HTTP_INTERCEPTORS or APP_INITIALIZER collect multiple values with multi: true. Order can matter for interceptors. Useful for plugin-style architecture. Single providers overwrite; multi aggregates.
Q96intermediateHow do you migrate Module-based app to standalone?
Convert components to standalone: true, move declarations to imports, replace RouterModule.forChild with routes plus loadComponent, bootstrap with bootstrapApplication. Migrate incrementally—Angular schematics help. Both styles can coexist during transition.
Q97intermediateWhen NOT to use NgRx?
Small/medium apps with limited shared state—services plus signals suffice. NgRx adds boilerplate and learning cost. Prefer NgRx when many features share complex state, need strong auditability, or team already standardized on it. ComponentStore for local feature complexity.
Q98intermediateExplain select and async pipe with NgRx store.
store.select(selectUsers) returns Observable slice; template uses async pipe. Memoized selectors prevent recomputation. Do not subscribe manually in components if async pipe works. Keep selectors pure and small.
Q99advancedWhat is the difference between snapshot and Observable route params when reusing components?
Navigating /users/1 to /users/2 may reuse the component—snapshot stays at first id. Subscribe to paramMap or use toSignal(route.paramMap) to react. Common production bug. Set runGuardsAndResolvers as needed.
Q100advancedHow do you implement a search typeahead in Angular?
input stream then debounceTime then distinctUntilChanged then switchMap(term => http.get(...)) then results. Cancel in-flight with switchMap. Handle empty term with of([]). Show loading/error states. Classic RxJS interview exercise.
Q101advancedWhat are Angular schematics?
Code generators/transformers used by CLI (ng generate) and libraries to scaffold or migrate code. Teams can write custom schematics for internal standards. Shows tooling maturity beyond writing components by hand.
Q102beginnerExplain provideAnimations vs provideNoopAnimations.
Animations module providers enable Angular animation DSL; noop disables for tests/perf/low-end. Use noop in TestBed to avoid animation flakiness. Respect reduced-motion preferences in real UX.
Q103intermediateHow does content projection multi-slot work with select?
Child template: ng-content select="app-card-header" and default ng-content. Parent supplies app-card-header projected into named slot. Enables flexible card APIs. Prefer clear selectors over brittle CSS class selectors when possible.
Q104beginnerCompare Angular HttpClient to fetch API directly.
HttpClient integrates interceptors, typed JSON, testing module, and RxJS. Raw fetch is fine in simple utilities but loses interceptor pipeline. Prefer HttpClient in Angular apps for consistency. Can wrap fetch via withFetch().
Q105beginnerHow do you reset or patch reactive forms?
patchValue updates subset without requiring all controls; setValue requires the full shape. reset() restores to initial/null and clears flags. Use emitEvent: false to avoid valueChanges loops. Common mistake: setValue with missing keys throws.
Q106intermediateWhat is takeUntilDestroyed and why prefer it?
takeUntilDestroyed() (with DestroyRef) auto-completes the subscription when the component is destroyed—less boilerplate than manual Subject. Call in injection context or pass DestroyRef. Prefer over forgotten ngOnDestroy unsubscribes. Still prefer async pipe when template-bound.
Q107intermediateExplain distinctUntilChanged in Angular streams.
Emits only when the current value differs from the previous (default ===). Essential after debounce on search to avoid duplicate identical queries. Provide a custom comparator for objects. Without it, retyping the same term after blur/focus can still refetch.
Python
135 questions
Q1beginnerMutable vs immutable types in Python?
Immutable: int, float, str, tuple, frozenset, bytes—operations create new objects. Mutable: list, dict, set, bytearray— in-place change affects all references. Default args must not use mutable literals `def f(x=[]):` bug.
Q2beginnerList vs tuple—when use tuple?
Tuple fixed-length heterogeneous record—dict keys, return multiple values, hashable if elements hashable. List homogenous sequence needing mutation. Tuple smaller and faster iteration marginally.
Q3beginnerExplain `is` vs `==`.
`==` compares values (calls __eq__). `is` compares identity (same object id)—use for None, small int cache caveat not reliable for large ints. `a is b` implies `a == b` for sane types.
Q4beginnerWhat are Python's truthiness rules?
Falsy: None, False, 0, empty containers '', [], {}, set(). Custom classes falsy if __bool__ or __len__ returns 0. Use `if seq:` not `if len(seq)>0` idiomatically.
Q5intermediateType hints purpose—do they enforce at runtime?
Hints document intent for mypy/pyright; default no runtime enforcement unless pydantic/beartype. Python 3.10+ `list[str]`, 3.9 `from __future__ import annotations` strings.
Q6intermediateDeep copy vs shallow copy?
`copy.copy` duplicates container but shares nested objects. `copy.deepcopy` recursive clone. Assignment `b=a` aliases. Critical when mutating nested structures in APIs.
Q7beginnerExplain `*args` and `**kwargs`.
Collect positional and keyword overflow in function definition; unpacking at call `func(*list, **dict)`. Order: positional, *args, keyword-only, **kwargs. Useful wrappers and decorators.
Q8beginnerWhat is `__name__ == '__main__'` idiom?
Module run as script executes block; imported as module skips it. Entry point for CLI tools and tests. `python -m package.module` sets __name__ accordingly.
Q9advancedExplain `__init__` vs `__new__`.
`__new__` creates instance (classmethod, before init); `__init__` initializes it. Rare override __new__ for singletons, immutable subclasses str. Most classes only __init__.
Q10intermediate@staticmethod vs @classmethod vs instance method?
Instance: first arg self, access instance. Classmethod: cls, alternative constructors `from_json`. Staticmethod: no implicit first arg—utility namespaced in class. Pick by need for cls/self.
Q11advancedMultiple inheritance and MRO?
Method Resolution Order C3 linearization—`Class.__mro__` or `help()`. super() follows MRO not just parent. Mixins add behavior; avoid diamond confusion document order.
Q12intermediateDunder methods you should know?
__str__ user readable, __repr__ developer unambiguous ideally eval-able, __eq__, __hash__ (immutable contract), __enter__/__exit__ context manager, __len__, __getitem__ sequence protocol.
Q13intermediateDataclasses vs namedtuple vs Pydantic model?
dataclass generates boilerplate __init__, repr, optional frozen. namedtuple immutable lightweight. Pydantic validates/coerces runtime—API boundaries. Choose by validation needs.
Q14intermediateAbstract base classes purpose?
`abc.ABC` with @abstractmethod enforces subclass implementation. registers virtual subclasses. typing.Protocol structural subtyping without inheritance—duck typing formalized.
Q15intermediateProperty decorator use case.
@property getter; @name.setter controlled write—validation without breaking attribute syntax. Replace getter/setter Java style.
Q16beginnerComposition over inheritance example.
Class wraps helper instead of extends—`class Service: def __init__(self, repo): self.repo=repo`. Easier testing with mock repo than deep inheritance trees.
Q17intermediateWrite concept of a decorator that logs calls.
`def log(fn): @functools.wraps(fn) def wrapper(*a,**k): print(fn.__name__); return fn(*a,**k); return wrapper` Preserves metadata with wraps. Decorators are higher-order functions applying at definition time.
Q18advancedDecorator with arguments pattern?
Outer function takes decorator args returns actual decorator: `def repeat(n): def dec(fn): ... return dec`. Three levels nested.
Q19intermediateGenerator vs iterator?
Generator function with yield produces lazy iterator—state suspended between yields. Iterator implements __iter__/__next__. Generators memory efficient for large sequences.
Q20advancedyield from purpose?
Delegates to subgenerator—flatten nested generators, bidirectional communication in advanced coroutine patterns. Replaced partly by async await for async code.
Q21beginnerList comprehension vs generator expression?
[x*2 for x in range(n)] builds list. (x*2 for x in range(n)) lazy generator—memory friendly passed to sum/any. Dict/set comps exist too.
Q22intermediateContext manager without with statement class?
Implement __enter__ return resource, __exit__ exc_type/value/traceback cleanup return True suppresses. contextlib.contextmanager decorator yields once.
Q23intermediatefunctools.lru_cache cautions?
Caches by arguments—unhashable args fail. Memory grows unbounded unless maxsize set. Don't cache mutable return values that callers mutate.
Q24advancedScenario: Retry decorator with exponential backoff.
Loop attempts catch Exception sleep 2**attempt random jitter, reraise last. Used API clients; respect Retry-After headers in production not blind retry.
Q25beginnertry/except/else/finally flow?
try runs; except matches exception; else if no exception; finally always cleanup. else avoids catching code in try block accidentally. Prefer specific exceptions not bare except.
Q26intermediateCustom exception hierarchy best practice.
AppError base with DomainError subclasses carrying code/message. Catch broad AppError at API boundary map to HTTP status. Keep depth shallow.
Q27beginnerEAFP vs LBYL?
Easier Ask Forgiveness Permission—try access key except KeyError. Look Before You Leap—if key in dict. Pythonic EAFP when exception rare; LBYL for hot paths predictable.
Q28intermediatecollections module highlights?
Counter, defaultdict, deque O(1) ends, OrderedDict less needed 3.7+ dict ordered, namedtuple, ChainMap. Pick right tool for perf clarity.
Q29intermediateitertools common tools?
chain, groupby (sorted input!), islice, product, permutations. Lazy composition avoids materializing huge lists.
Q30beginnerpathlib vs os.path?
pathlib object-oriented paths `/` operator, read_text, mkdir parents=True. Preferred modern code; os.path still in legacy.
Q31intermediatejson module limitations?
No datetime/decimal/set natively—custom default encoder. Loads returns dict/list only. Use orjson/ujson perf; pydantic validation after load.
Q32intermediatedatetime timezone aware best practice?
Store UTC `datetime.now(timezone.utc)`, convert display zonezoneinfo Python 3.9+. Never naive datetimes for distributed systems.
Q33intermediateasyncio event loop basics?
Coroutines async def awaited cooperatively. await yields control. loop.run_until_complete or asyncio.run main. Blocking call in async def stalls loop—use asyncio.to_thread.
Q34intermediateasync vs threading vs multiprocessing?
async: IO-bound many connections single thread. threading: IO-bound C releases GIL sometimes. multiprocessing: CPU-bound parallel bypass GIL. Match tool to workload.
Q35intermediateGIL impact on CPU-bound Python?
Global Interpreter Lock allows one thread bytecode at a time—threads don't parallelize CPU work. Use multiprocessing, C extensions release GIL, or other runtimes.
Q36advancedasyncio.gather vs TaskGroup?
gather runs awaitables concurrent return results exception optional return_exceptions. Python 3.11 TaskGroup structured concurrency cancels siblings on failure.
Q37intermediateaiohttp vs requests in async app?
requests blocks—use in thread pool or httpx AsyncClient inside async route handlers. FastAPI often httpx/starlette async endpoints.
Q38intermediateSemaphore limit concurrency?
async with semaphore: await fetch—max N simultaneous downloads protecting server and client file descriptors.
Q39intermediateQueue patterns thread-safe?
queue.Queue producer-consumer threads. asyncio.Queue for coroutines. multiprocessing.Queue cross-process.
Q40advancedScenario: CPU work in FastAPI endpoint?
Run ProcessPoolExecutor or background task queue Celery/RQ; don't block event loop with heavy pandas on main thread.
Q41intermediatedict implementation intuition?
Hash table average O(1) lookup insert; keys hashable immutable mostly. 3.7+ insertion order preserved. Collision handling open addressing CPython.
Q42beginnerTime complexity list append vs insert(0)?
Append amortized O(1). insert(0) O(n) shift elements—use deque for frequent front inserts.
Q43intermediatedefaultdict vs setdefault?
defaultdict factory on missing key access. dict.setdefault computes once if missing—avoid repeated lookup patterns.
Q44intermediateheapq for top-k problems?
Min heap nlargest nsmallest O(n log k). Push pop maintain k elements streaming data.
Q45intermediatebisect module use?
Binary search insert sorted list maintain order O(log n) search. Alternative tree structures if many inserts.
Q46beginnerScenario: Two sum with hash map.
One pass store value→index; check target-current in map O(n). vs O(n^2) nested loops.
Q47intermediateScenario: Detect cycle linked list.
Floyd tortoise hare two pointers speed 1 and 2 meet if cycle. Python list cycle different—track visited set id(node).
Q48beginnerBig-O common Python operations cheat?
len list O(1), x in list O(n), x in set O(1), sort O(n log n), dict get O(1) avg. Interview narrate while coding.
Q49intermediatepytest fixtures scope?
function default fresh each test; module/class/session for expensive setup. yield fixture teardown after test. conftest.py shared fixtures.
Q50intermediateunittest.mock.patch where string?
Patch where object used not where defined—`patch('mymodule.requests.get')` if imported into mymodule. Common mock interview gotcha.
Q51beginnerVirtual environment why?
Isolate project dependencies per PEP 405 venv. requirements.txt or pyproject.toml lock versions. Never global pip install prod projects.
Q52intermediatepyproject.toml role?
Modern packaging metadata, build backend, tool configs black/ruff/pytest. PEP 621 project table replaces setup.cfg many cases.
Q53intermediateType checking mypy strictness?
Gradual typing optional strict disallow untyped defs. Helps large codebases catch None errors with Optional handling.
Q54beginnerLogging vs print production?
logging levels DEBUG INFO WARNING handlers rotation structured JSON. print not filterable disable in prod.
Q55advanced__slots__ when?
Restrict attributes reduce memory per instance __dict__ omitted. Breaks default __dict__ dynamic attrs—use known fixed fields millions of objects.
Q56advancedPickle security warning?
Never unpickle untrusted data—arbitrary code execution. Use JSON/msgpack for interchange. pickle internal persistence only trusted.
Q57intermediateFlask vs Django vs FastAPI tradeoffs?
Django batteries included ORM admin auth monolith. Flask micro compose extensions. FastAPI async type hints OpenAPI auto perf ASGI. Pick by team size and requirements.
Q58intermediateDjango ORM N+1 query problem?
Loop access foreign key hits DB each—fix select_related FK reverse prefetch_related M2M. django-debug-toolbar reveals.
Q59intermediateFastAPI dependency injection?
Depends(get_db) yields session per request cleanup. Reusable auth rate limit. Typed clean testing override deps.
Q60intermediateWSGI vs ASGI?
WSGI sync request response callable. ASGI async websocket lifespan scope—uvicorn hypercorn workers FastAPI Starlette.
Q61intermediateMiddleware order Django?
Request top to bottom response bottom up—security session auth. Custom middleware class __call__ or async variant.
Q62beginnerMigrations workflow Django?
makemigrations detect model changes migrate apply. Never edit applied migration history in prod casually—squash carefully.
Q63intermediateBlueprint Flask modular?
Register routes grouped url_prefix factory pattern create_app config classes Development Production.
Q64intermediatePydantic validation FastAPI request body?
Automatic 422 on invalid types coercion rules Field constraints example ge le. response_model filter output.
Q65intermediateScenario: Read large CSV without memory blowup.
pandas read_csv chunksize iterator or csv module row by row process aggregate. Don't readlines entire file.
Q66beginnerScenario: Merge two sorted lists.
Two pointers O(n+m) similar merge sort merge step. Or heapq.merge lazy.
Q67beginnerScenario: Count word frequency in file.
Counter with open loop split normalize case regex optional. most_common(n) top words.
Q68intermediateScenario: Singleton pattern Pythonic?
Module level instance simplest. __new__ override or decorator—often overkill; dependency injection preferred testability.
Q69intermediateScenario: Parse env config 12-factor.
os.environ.get cast int bool pydantic-settings BaseSettings validates env file .env not commit secrets.
Q70intermediateScenario: Thread-safe counter?
threading.Lock around increment or use itertools or atomic in multiprocessing Value. asyncio needs asyncio.Lock not threading.
Q71advancedScenario: Flatten nested dict keys dot notation.
Recursive yield parent_key + '.' + k if dict else leaf. Used config flattening logging.
Q72beginnerCompare list.sort and sorted().
list.sort in-place returns None; sorted returns new list any iterable. Both key= reverse= stable sort Timsort.
Q73intermediateScenario: Validate email without regex hell?
email-validator library or pydantic EmailStr pragmatic. Perfect RFC regex enormous—pragmatic validation plus send confirmation link.
Q74beginnerScenario: Implement context timer.
@contextmanager def timer(): start=time.perf_counter(); yield; print(time.perf_counter()-start). Wrap code blocks to measure elapsed wall time; `yield` splits setup and teardown. Useful for quick profiling in scripts without a full benchmarking harness.
Q75intermediateWalrus operator := example?
if (n := len(data)) > 10: ... assigns in expression avoid double compute. Python 3.8+.
Q76beginnerScenario: Remove duplicates preserve order list.
dict.fromkeys(seq) Python 3.7+ ordered or seen set loop append O(n). set() loses order.
Q77beginnerenumerate vs range len?
for i, item in enumerate(seq) pythonic index access avoid range len indexing.
Q78intermediatezip longest vs strict?
zip stops shortest zip_longest itertools fillvalue pad strict=True Python 3.10 raise unequal.
Q79beginnerf-string debugging = syntax?
f'{x=}' prints x=42 Python 3.8 debug logging expression and value.
Q80intermediatematch case structural pattern?
Python 3.10 match value case patterns guard if capture bindings algebraic data style.
Q81beginnertyping Optional vs X | None?
Optional[str] Union str None PEP 604 str | None 3.10+ modern concise.
Q82advancedProtocol structural typing?
class SupportsClose Protocol def close(): ... duck type static check without inheritance.
Q83intermediatemultiprocessing Pool map?
CPU parallel func across workers pickle args GIL bypass batch imap unordered faster.
Q84intermediatesecrets module vs random?
secrets token_urlsafe cryptographic random not random.choice passwords tokens.
Q85intermediateWSGI gunicorn workers?
Sync workers processes handle concurrent requests threads gevent eventlet alternative CPU count tuning.
Q86advancedCelery task retry ack?
autoretry_for max_retries countdown broker redis rabbit result backend flower monitor.
Q87intermediateSQLAlchemy session scope?
Request scoped session commit rollback close pattern Flask teardown FastAPI yield dependency.
Q88intermediateDjango middleware security?
SecurityMiddleware HTTPS redirect HSTS XSS filter CSRF clickjacking settings production checklist.
Q89intermediateuvicorn workers vs gunicorn uvicorn?
uvicorn single ASGI gunicorn -k uvicorn.workers.UvicornWorker multiple processes production.
Q90beginnerpython-dotenv not production?
Dev convenience prod inject env k8s secrets not commit .env gitignore.
Q91intermediateRate limit FastAPI slowapi?
Decorator limiter key func remote address redis backend distributed.
Q92beginnerOpenAPI auto docs FastAPI?
/docs swagger /redoc from type hints response_model validation schema contract.
Q93beginnerScenario: Read JSON file safely?
pathlib open encoding utf-8 json.load try except JSONDecodeError validate pydantic model.
Q94beginnerScenario: Reverse string Python?
s[::-1] slice or ''.join(reversed(s)) unicode aware not grapheme clusters.
Q95beginnerScenario: Find most common element?
collections.Counter(seq).most_common(1)[0][0] finds the mode in O(n) time. Counter internally hashes elements like a dict. For ties, most_common returns arbitrary winner—sort explicitly if tie-breaking matters.
Q96beginnerScenario: Merge two dicts Python 3.9+?
d1 | d2 merge later keys win in place d1 |= d2 update.
Q97intermediateScenario: Parse ISO date string?
datetime.fromisoformat replace Z +00:00 3.11 handles dateutil fallback.
Q98intermediateScenario: Chunk list batches?
itertools.batched seq n Python 3.12 or manual slice i i+n range step.
Q99beginnerScenario: Log exception stack trace?
logger.exception('msg') or logger.error('msg', exc_info=True) inside an except block captures the full traceback in structured logs. Never swallow exceptions silently in production—log context like user id and request id alongside the stack.
Q100beginnerScenario: Type narrow with isinstance?
if isinstance(x, str): mypy knows str methods elif list separate branches.
Q101intermediateExplain `match`/`case` structural pattern matching.
Python 3.10+: `match value:\n case 0: ...\n case {'type': t}: ...\n case Point(x=0, y=y): ...\n case _: ...`. Matches structure, supports guards (`case x if x>0`). Cleaner than long if-elif chains for AST-like data. Patterns can capture names.
Q102beginnerWhat is the walrus operator `:=`?
Assignment expression: `if (n := len(items)) > 10:` assigns and uses value. Useful in while loops `while (line := f.readline()):`. Don't overuse—readability first. Avoid in confusing comprehensions.
Q103advancedWhat are `__slots__`?
Class attribute listing fixed instance attribute names; prevents per-instance `__dict__` (unless included), saving memory and blocking accidental attrs. Example: `class P:\n __slots__=('x','y')`. Inheritance rules are subtle with multiple slotted bases.
Q104advancedMetaclasses — brief interview answer?
A metaclass is the class of a class (`type` by default); it controls class creation via `__new__`/`__init__`/`__call__`. Used for ORMs, registries, enforcing APIs. Prefer class decorators when sufficient—metaclasses are powerful but hard to reason about.
Q105advancedDescriptors — brief?
Objects defining `__get__`/`__set__`/`__delete__` that manage attribute access (functions, `property`, ORM columns). Data descriptors (with `__set__`) override instance dict. Foundation of `property` and bound methods.
Q106intermediate`asyncio.gather` vs `create_task`?
`create_task` schedules a coroutine concurrently on the running loop. `gather(*aws)` waits for many awaitables concurrently and returns results (or raises). Use TaskGroup (3.11+) for structured concurrency with better cancellation. Don't block the loop with CPU-heavy sync code.
Q107intermediateaiohttp overview?
Async HTTP client/server library on asyncio. ClientSession with connection pooling for concurrent requests. Prefer it (or httpx async) over blocking `requests` inside async apps. Always close sessions (`async with`).
Q108intermediateFastAPI `Depends` — what for?
Dependency injection: declare `def endpoint(user=Depends(get_current_user))`. Supports nested deps, caching per-request, and automatic OpenAPI params. Clean way to share auth, DB sessions, pagination.
Q109intermediateDjango middleware — what does it do?
Hooks wrapping request/response globally: auth, sessions, CSRF, security headers, logging. Implemented as callable classes with `__call__`/`process_*` patterns. Order matters—short-circuit carefully. Prefer middleware for cross-cutting, views for business logic.
Q110intermediateCelery — when and how briefly?
Distributed task queue: web workers enqueue jobs (email, image processing) to a broker (Redis/RabbitMQ), workers execute async. Use retries, idempotency, and result backends thoughtfully. Don't run long CPU tasks on web request threads.
Q111advancedWhat is `typing.Protocol`?
Structural typing (duck typing with types): define methods a type must have without inheritance. `@runtime_checkable` optional. Prefer Protocols for flexible interfaces vs ABC inheritance when appropriate.
Q112beginnerWhy prefer `pathlib.Path` over `os.path`?
Object-oriented paths: `Path('a')/'b'`, `.read_text()`, `.glob()`, `.resolve()`. Clearer and often safer composition than string joins. Interops with APIs accepting path-like objects.
Q113beginner`collections.deque`, `Counter`, `defaultdict`, `namedtuple`?
`deque` O(1) ends for queues; `Counter` frequency maps; `defaultdict(list)` auto-inits keys; `namedtuple`/typing.NamedTuple lightweight immutable records. High-frequency interview toolkit.
Q114intermediateUseful `itertools` functions?
`chain`, `islice`, `groupby` (needs sorted keys), `product`, `combinations`, `accumulate`, `cycle`. Build memory-efficient pipelines. Know groupby caveat: consecutive groups only.
Q115intermediate`functools.lru_cache` and `wraps`?
`lru_cache(maxsize=)` memoizes pure functions. Args must be hashable. `wraps` copies metadata when writing decorators. Prefer `cache` for unbounded (careful memory). Clear with `cache_clear` when needed.
Q116intermediate`contextlib` utilities?
`contextmanager` decorator builds context managers from generators; `closing`, `suppress`, `ExitStack` for dynamic cleanups. Prefer `with` for files/locks/sessions to guarantee teardown.
Q117advanced`multiprocessing.Pool` overview?
Process pool for CPU-bound parallelism bypassing GIL. `map`/`starmap`/`apply_async`. Pickling arguments has costs/limits; prefer for numeric/batch jobs. For I/O-bound, threads/asyncio often better.
Q118advancedPickle risks?
Unpickling untrusted data can execute arbitrary code—never pickle from users. Prefer JSON for data interchange. Pickle is Python-specific and version-sensitive. Use for trusted caches only with caution.
Q119beginnerWhy `if __name__ == '__main__':`?
Code under this guard runs only when the file is executed as a script, not when imported. Prevents side effects (starting servers, tests) on import. Standard entrypoint pattern.
Q120intermediatePoetry vs pip-tools awareness?
Poetry manages deps + packaging + lockfile (`poetry.lock`). pip-tools (`pip-compile`) generates pinned `requirements.txt` from abstract input. Both aim for reproducible installs; choose per team convention. Lock files belong in VCS.
Q121beginnerRuff vs Black?
Black is an opinionated formatter. Ruff is a fast linter (and increasingly formatter) replacing many flake8 plugins. Typical CI: ruff check + format (or black). Agree on config in `pyproject.toml`.
Q122intermediateGIL implications briefly?
CPython Global Interpreter Lock allows one thread executing Python bytecode at a time—threads help I/O concurrency, not CPU parallelism. Use multiprocessing, native extensions, or alternative runtimes for CPU-bound scale.
Q123intermediate`asyncio.to_thread` when?
Offload blocking sync I/O/CPU-ish calls from async functions to a thread so the event loop stays responsive. Prefer true async libraries when available.
Q124intermediatedataclass vs Pydantic models?
`dataclasses` for simple structured data with little validation. Pydantic for parsing/validation (FastAPI models) with coercion and errors. Don't reinvent validators in dataclasses for API boundaries.
Q125beginnerVirtual environments — why?
Isolate project dependencies (`python -m venv .venv`). Avoid polluting system Python. Activate or use tools (Poetry/uv) that manage envs. Pin versions for reproducibility.
Q126beginner`enumerate` and `zip` idioms?
`for i, x in enumerate(xs, start=1):` and `for a,b in zip(xs, ys):` (use `strict=True` in 3.10+). Prefer over range(len) for clarity.
Q127beginnerGenerators vs list comprehensions?
Generators (`(x for x in ...)`) lazy, memory-friendly; lists materialize all. Use generators for large streams; lists when you need len/reuse. Generator functions use `yield`.
Q128beginner`try`/`except`/`else`/`finally` roles?
`else` runs if no exception; `finally` always for cleanup. Catch specific exceptions, not bare `except:`. Avoid swallowing errors silently.
Q129beginnerType hints: `list[int]` vs `List[int]`?
Python 3.9+ builtin generics preferred (`list[int]`, `dict[str, int]`). `typing.List` legacy. Use `from __future__ import annotations` for postponing evaluation often.
Q130beginnerWhat is a context manager protocol?
Objects with `__enter__`/`__exit__` (or async variants). `with` ensures `__exit__` for cleanup even on exceptions. Files, locks, transactions use this pattern.
Q131intermediateFastAPI vs Django briefly?
FastAPI: modern async APIs, OpenAPI automatic, Pydantic validation—great microservices. Django: batteries-included monolith (ORM, admin, auth)—great full web apps. Choose by problem shape.
Q132advancedHow do you cancel asyncio tasks properly?
Call `task.cancel()` and await it, handling `CancelledError`. Prefer TaskGroup/structured concurrency so child failures cancel siblings cleanly. Don't fire-and-forget without tracking.
Q133intermediate`collections.abc` — why import ABCs?
Use `Mapping`, `Iterable`, `Sequence` for isinstance checks and type hints expressing capability rather than concrete list/dict. Encourages duck-typed APIs.
Q134beginnerWhat does `functools.partial` do?
Freezes some arguments of a function: `partial(print, sep=',')`. Useful for callbacks. Combined with operators for concise maps.
Q135intermediateExplain EAFP vs LBYL in Python.
EAFP: try/except and handle failure (idiomatic). LBYL: check first with if. Prefer EAFP when race conditions make checks unreliable (files exist then vanish), but don't use exceptions for ordinary control flow excessively.
Node.js
130 questions
Q1beginnerWhat is Node.js and why is it used for backends?
Node.js is a JavaScript runtime built on Chrome's V8 engine that runs JS outside the browser. It uses a non-blocking, event-driven I/O model, making it efficient for APIs, real-time apps, and microservices. You use one language (JS/TS) across frontend and backend, with a huge npm ecosystem. It is not ideal for heavy CPU-bound work without worker threads or offloading.
Q2intermediateExplain Node.js architecture at a high level.
Client request → Event Queue → Event Loop → may hand off I/O to libuv thread pool → callback/promise resumes on the loop. V8 executes JS; libuv handles async I/O (file, DNS, some crypto). Single main thread runs JS; I/O concurrency comes from the event loop + OS/thread pool, not from spawning a thread per request.
Q3intermediateIf Node is single-threaded, how does it handle many concurrent requests?
The main thread runs JS and the event loop. Concurrent I/O (network, disk) is non-blocking: while waiting, the loop serves other requests. For some blocking ops, libuv uses a thread pool (default 4). CPU-heavy work blocks the loop — use worker_threads, child_process, or a queue. Scaling: cluster/PM2 multiple processes or horizontal pods.
Q4intermediateWhat is the Node.js event loop?
The event loop processes phases: timers (setTimeout/setInterval), pending callbacks, idle/prepare, poll (I/O), check (setImmediate), close callbacks. Microtasks (Promises, process.nextTick) run between phases / after each operation with priority. Understanding phase order explains why `setTimeout(0)` and `setImmediate` order can vary.
Q5advancedprocess.nextTick vs setImmediate vs setTimeout(fn, 0)?
`process.nextTick` queues a microtask-like callback before the event loop continues — highest priority, can starve I/O if abused. `setImmediate` runs in the check phase after poll. `setTimeout(fn,0)` runs in the timers phase with minimum delay. Prefer setImmediate/setTimeout for deferring; use nextTick sparingly (e.g., ensure callback after current code).
Q6beginnerWhat is V8 and how does it relate to Node?
V8 is Google's open-source JS engine that compiles JS to native machine code (JIT). Node embeds V8 and adds libuv, modules, and Node APIs (fs, http, etc.). Performance of JS in Node depends heavily on V8 optimizations; long-running Node processes benefit from knowing GC and heap limits.
Q7intermediateCommonJS vs ES Modules in Node?
CommonJS: `require`/`module.exports`, sync load, still default in many packages. ESM: `import`/`export`, async, needs `"type": "module"` or `.mjs`. Interop exists but has quirks (default vs named exports). New projects often prefer ESM + TypeScript. `__dirname` exists in CJS; in ESM use `import.meta.url` + `fileURLToPath`.
Q8beginnerWhat is npm and package.json?
npm is Node's package manager. `package.json` lists name, version, scripts, dependencies, and engines. `dependencies` = runtime; `devDependencies` = build/test. `npm install` resolves the lockfile (`package-lock.json`) for reproducible installs. Always commit the lockfile for apps.
Q9beginnerpackage-lock.json vs package.json — why both?
`package.json` allows ranges (`^1.2.0`). Lockfile pins exact versions of the whole tree. Without a lockfile, CI and prod can install different transitive deps and break. Never delete lockfile casually; regenerate intentionally after upgrades.
Q10beginnerWhat is npx?
`npx` runs a package binary without global install (or uses local `node_modules/.bin`). Example: `npx create-react-app`, `npx eslint`. Useful for one-off CLIs and ensuring the project's local tool version runs.
Q11intermediateExplain require cache and how to clear it.
Node caches loaded modules in `require.cache`. Requiring the same path returns the same exports object. Hot-reload tools delete cache entries. In production, don't rely on clearing cache; restart the process. Circular requires can yield partial exports.
Q12intermediateWhat are Node streams and why use them?
Streams process data chunk-by-chunk instead of loading entire files into memory. Types: Readable, Writable, Duplex, Transform. Use for file upload/download, HTTP responses, piping. `pipeline()` or `pipeline` from stream/promises handles backpressure and errors better than naive `.pipe()`.
Q13intermediateReadable vs Writable vs Transform streams?
Readable produces data (`fs.createReadStream`). Writable consumes (`fs.createWriteStream`, HTTP response). Duplex is both (TCP socket). Transform is Duplex that modifies data (zlib gzip, crypto cipher). Interview tip: mention backpressure — writable signals when it can't accept more.
Q14beginnerWhat is Buffer in Node.js?
Buffer is a fixed-size chunk of binary data outside V8's string heap (historically; now more integrated). Used for binary protocols, file I/O, crypto. Create carefully: prefer `Buffer.from`/`Buffer.alloc` over deprecated `new Buffer()` to avoid uninitialized memory leaks.
Q15beginnerfs.readFile vs fs.createReadStream — when to use which?
`readFile` loads entire file into memory — fine for small configs. Streams for large files/videos to keep memory constant and start sending early. Never `readFile` a multi-GB file in an API request handler.
Q16intermediateSynchronous vs asynchronous fs methods?
`fs.readFileSync` blocks the event loop until done — OK in CLI startup scripts, dangerous in servers under load. Prefer async `fs.promises` or callbacks in request handlers. One sync DB or file call can stall all concurrent users on that process.
Q17beginnerHow does the http module work at a basic level?
`http.createServer((req,res)=>{})` listens on a port. `req` is IncomingMessage (readable stream); `res` is ServerResponse (writable). You set status, headers, then `res.end(body)`. Express wraps this with routing and middleware. Know raw http for interviews even if you use Express daily.
Q18advancedCluster module — what problem does it solve?
One Node process uses one CPU core for JS. `cluster` forks workers sharing a port (OS load balances). PM2 does similar. Use for multi-core machines. Shared memory isn't automatic — use Redis for sessions/cache. Sticky sessions needed for WebSockets sometimes.
Q19advancedWorker threads vs child_process vs cluster?
Worker threads: parallel JS in same process, shareable ArrayBuffer — good for CPU tasks. child_process: separate process, IPC — run another script/binary. Cluster: multiple Node processes for scaling HTTP. Don't use workers for I/O-bound work; event loop already handles that.
Q20advancedWhat is libuv?
C library providing Node's event loop, async I/O, and thread pool. Abstracts OS differences (epoll, kqueue, IOCP). Explains why some ops (dns.lookup, fs, crypto) can use thread pool while network I/O is often OS-async.
Q21beginnerExplain callback hell and how to avoid it.
Nested callbacks for sequential async create pyramid of doom and hard error handling. Avoid with Promises, async/await, or well-named functions. Always handle errors on every path. Prefer `util.promisify` for legacy APIs.
Q22beginnerPromises and async/await in Node — best practices?
Always return/await promises; never leave floating promises without catch. Use `Promise.all` for parallel independent I/O; `Promise.allSettled` when partial failure OK. Prefer async/await for readability. Top-level await available in ESM.
Q23intermediateWhat is the EventEmitter pattern?
Core Node pattern: objects emit named events; listeners subscribe. Streams and http.Server inherit EventEmitter. `on`/`once`/`emit`/`off`. Memory leak: forgetting to remove listeners — set `emitter.setMaxListeners` carefully and clean up.
Q24advancedHow do you handle uncaughtException and unhandledRejection?
Log and crash/restart for uncaughtException — process state may be corrupt. For unhandledRejection, log and ideally exit in production after alerting. Better: catch every promise, use domains is deprecated. Process managers (PM2) restart crashed workers.
Q25beginnerEnvironment variables and dotenv?
Config via `process.env` (PORT, DATABASE_URL). `dotenv` loads `.env` into env in development — never commit secrets. Production injects env via platform/K8s. Validate required env at startup (fail fast).
Q26beginnerWhat is middleware conceptually in Node HTTP stacks?
Function that receives (req, res, next), can modify request/response, end response, or call next(). Chain forms a pipeline: logging → auth → validate → route → error handler. Express popularized this; Koa uses async middleware.
Q27intermediateCORS in a Node API — how do you enable it?
Browser blocks cross-origin XHR unless server sends Access-Control-Allow-Origin etc. Use `cors` package or set headers manually. Configure allowed origins carefully — `*` with credentials is invalid. Preflight OPTIONS must be handled.
Q28intermediateJWT authentication flow in Node?
Login verifies credentials → signs JWT (jsonwebtoken) with secret/private key → client sends `Authorization: Bearer <token>` → middleware verifies signature and expiry → attaches user to req. Prefer httpOnly cookies for browsers. Rotate secrets; keep payloads small.
Q29intermediateSessions in Node — express-session + store?
Server stores session data; client gets session ID cookie. Default MemoryStore is not for production multi-instance. Use Redis/Mongo store. Set secure, httpOnly, sameSite on cookie. Contrast with stateless JWT.
Q30intermediateRate limiting — why and how in Node?
Prevent abuse/DDoS/brute force. Use express-rate-limit or Redis-backed counters per IP/user. Return 429. Place early in middleware. API gateways also rate-limit at edge.
Q31intermediateHelmet and security headers?
`helmet` sets secure HTTP headers (CSP, X-Frame-Options, HSTS helpers, etc.). Reduces XSS/clickjacking risk. Still need input validation, parameterized queries, and CSP tuned for your frontend.
Q32beginnerSQL injection prevention in Node?
Never concatenate user input into SQL. Use parameterized queries (pg, mysql2), ORMs (Prisma, Sequelize) with bind parameters. Validate types. Least-privilege DB user.
Q33intermediateXSS prevention on Node-rendered HTML?
Escape output (template engines auto-escape by default — don't disable). Sanitize rich HTML with allowlists. Prefer API + React (escapes text). CSP reduces impact of injected scripts.
Q34intermediateConnection pooling — why matters?
Opening a DB connection per request is slow and exhausts DB limits. Pool reuses connections (e.g., `pg.Pool`). Size pool relative to Node process count × workers — too many pools overwhelm DB.
Q35intermediateLogging best practices in Node services?
Structured JSON logs (pino, winston), request IDs, log levels, never log secrets/PII. Correlate errors with APM. stdout for containers. Avoid console.log-only in production.
Q36intermediateHow do you unit test Node code?
Jest/Vitest/Mocha + Supertest for HTTP. Mock DB/external APIs. Test pure business logic without Express if possible (separate controllers/services). CI runs tests on PR.
Q37beginnerWhat is REST API design in a Node service?
Resource URLs, proper HTTP verbs/status codes, consistent JSON errors, versioning, pagination. Thin controllers, fat services. OpenAPI docs. Idempotency for PUT/DELETE where possible.
Q38intermediateWebSockets with Node — when and how?
Bidirectional real-time (chat, notifications). `ws` library or Socket.IO. Needs sticky sessions or Redis adapter behind load balancer. Alternative: SSE for server→client only.
Q39intermediateFile uploads in Node?
Multer middleware for multipart/form-data; stream to disk or S3. Validate MIME/size; never trust client Content-Type alone. Virus scan for sensitive apps. Prefer direct-to-S3 signed URLs for large files.
Q40advancedChild process spawn vs exec vs fork?
`exec` buffers full output — OK for small commands. `spawn` streams — large output. `fork` special spawn for Node modules with IPC. Sanitize args to avoid shell injection; prefer spawn without shell.
Q41intermediateWhat is npm audit and how do you handle vulnerabilities?
`npm audit` reports known CVEs in dependency tree. Fix with `npm audit fix`, upgrades, or replace packages. For transitive issues, use overrides/resolutions carefully. Continuous Dependabot/Snyk in CI.
Q42beginnerSemantic versioning for Node packages?
MAJOR.MINOR.PATCH — breaking / features / fixes. `^1.2.3` allows minor/patch; `~1.2.3` patch only. Breaking changes require major bump. Communicate migrations in CHANGELOG.
Q43advancedHow does Node garbage collection work at a high level?
V8 GC (Scavenge + Mark-Sweep/Compact). Long-lived objects promote to old space. Memory leaks: global caches, uncleared timers, growing arrays, detached closures. Debug with `--inspect` and heap snapshots. Set `--max-old-space-size` if needed.
Q44advancedDetecting event loop lag?
Monitor event loop delay (perf_hooks.monitorEventLoopDelay, clinic.js, APM). Symptoms: rising latency under load. Causes: sync CPU, large JSON.parse, sync crypto, huge loops. Fix by offloading or chunking work.
Q45intermediateJSON.parse large payload risk?
Parsing huge JSON blocks the event loop and can OOM. Limit body size (express.json limit), stream parse when needed, reject oversized Content-Length early.
Q46advancedWhat is graceful shutdown?
On SIGTERM: stop accepting new connections, finish in-flight requests, close DB pools, then exit. Important for K8s rolling deploys. Express: track connections; `server.close()`.
Q47intermediatePM2 vs Docker/K8s for Node process management?
PM2: process manager with cluster mode, restarts, logs — good on VMs. Containers: one process per container, orchestrator restarts. Prefer 12-factor: env config, logs to stdout, disposable processes.
Q48intermediateWhat is the 12-factor app methodology (Node context)?
Codebase, dependencies, config in env, backing services as attached resources, build/release/run, processes, port binding, concurrency, disposability, dev/prod parity, logs, admin processes. Guides cloud-native Node APIs.
Q49intermediatecrypto module common uses?
Hashing (sha256), HMAC, randomBytes for tokens, createCipheriv for encryption (prefer authenticated encryption). Password hashing: use bcrypt/argon2 libraries, not plain sha256. Timing-safe compare for tokens.
Q50beginnerpath module — why not string concat?
`path.join`/`path.resolve` handle OS separators and `..` safely. Prevents path traversal when combining user input with base dirs — always resolve and check result stays under allowed root.
Q51beginnerurl and querystring parsing?
WHATWG `URL` API preferred over legacy `url.parse`. `URLSearchParams` for query. Validate and encode user-provided URLs to avoid open redirects.
Q52beginnerWhat is middleware order importance?
Order defines pipeline: body parser before routes that need body; auth before protected routes; error handler last with 4 args. Wrong order = empty body or unauthenticated access.
Q53intermediateHow do you structure a production Node project?
routes/ → controllers/ → services/ → repositories/db. Separate config, middleware, utils. Keep Express app creation separate from `listen` for testing. Feature folders for large apps.
Q54intermediateCaching strategies with Node?
In-memory (lru-cache) per process — not shared. Redis for shared cache/sessions. HTTP Cache-Control/ETag. Cache invalidation is hard — TTL + event-driven bust. Don't cache personalized data without keys.
Q55advancedMessage queues with Node (RabbitMQ/SQS/Kafka)?
Decouple producers/consumers for emails, webhooks, heavy jobs. Avoid doing slow work in request path — enqueue and respond 202. Idempotent consumers. At-least-once delivery needs dedup.
Q56intermediateBull/BullMQ for background jobs?
Redis-backed job queues for retries, delays, concurrency. Good for email, image processing. Monitor failed jobs. Alternative: cloud queues. Don't use setInterval for critical jobs in multi-instance.
Q57beginnerHealth check endpoints?
`GET /health` or `/ready` — liveness vs readiness. Readiness checks DB connectivity. Keep lightweight. K8s uses these for routing traffic.
Q58beginnerAPI versioning approaches?
URL `/api/v1`, header Accept-Version, or subdomain. URL versioning most common and clear. Maintain old versions during migration. Document deprecation policy.
Q59advancedIdempotency keys for POST?
Client sends Idempotency-Key; server stores result for key to avoid duplicate charges on retries. Important for payments. Redis TTL store mapping key → response.
Q60intermediateHow does require resolve module paths?
Looks node_modules walking up directories, then core modules. `NODE_PATH` legacy. Prefer explicit package exports field. Circular dependency can return incomplete exports.
Q61advancedWhat are native addons / N-API?
C/C++ extensions for performance or OS APIs. N-API stable ABI across Node versions. Prefer pure JS or WASM when possible for portability. Sharp (images) uses native code.
Q62intermediateTLS/HTTPS in Node?
`https.createServer` with cert/key or terminate TLS at load balancer/nginx. Force HTTPS redirects. Keep OpenSSL updated via Node upgrades. HSTS at edge.
Q63intermediateCookie security flags?
HttpOnly (no JS access), Secure (HTTPS only), SameSite=Lax/Strict (CSRF mitigation), Path/Domain scoped. Session fixation: regenerate session ID on login.
Q64advancedCSRF protection for cookie-based auth?
Synchronizer tokens or SameSite cookies + CORS lockdown. For SPA+JWT in header, CSRF less relevant. Double-submit cookie pattern also used.
Q65beginnerHow to debug a Node app?
`node --inspect`, Chrome DevTools, VS Code attach, console structured logs, clinic flame/bubbleprof for perf. Reproduce with same NODE_ENV and data. Breakpoints in async code need async stack traces.
Q66advancedMemory leak common causes in Node servers?
Global caches without bound, EventEmitter listeners accumulation, closures holding large buffers, uncleared intervals, growing arrays in module scope. Fix with WeakMap, max size LRU, proper cleanup.
Q67advancedWhat is backpressure?
When writable can't keep up with readable, pause reading until drain. Streams handle this if you use pipe/pipeline correctly. Ignoring backpressure causes unbounded memory growth.
Q68advancedHTTP keep-alive and agent in Node client?
http.Agent reuses TCP connections. Default agent has limits. For high outbound concurrency, tune `maxSockets` or use undici. Connection reuse lowers latency.
Q69beginnerfetch in Node vs axios/got?
Node 18+ has global fetch (undici). axios adds interceptors, older Node support. Prefer standard fetch for new code unless you need axios features. Always set timeouts/AbortSignal.
Q70intermediateTimeouts — why mandatory on outbound calls?
Without timeout, hung dependency blocks sockets/memory. Use AbortController, axios timeout, or undici headersTimeout. Fail fast and circuit-break.
Q71advancedCircuit breaker pattern?
After N failures, stop calling dependency briefly (open), then half-open probe. Libraries: opossum. Protects your service from cascading failure.
Q72intermediateTypeScript with Node — ts-node vs compile?
Dev: tsx/ts-node for speed. Prod: compile to JS (`tsc` or swc) and run `node dist`. Type-check in CI. `moduleResolution` bundler/nodenext matters for ESM.
Q73intermediateESM top-level await use case?
Initialize config/DB before exporting server module. Can delay module evaluation — use carefully for libraries. Handy in scripts.
Q74beginnerWhat does process.exit do and when avoid it?
Immediately ends process — may skip I/O flush and graceful cleanup. Prefer graceful shutdown then exit. In tests, avoid exit that kills runner.
Q75beginnerstdin/stdout/stderr in Node CLIs?
Streams for piping. Exit codes: 0 success, non-zero failure. Libraries: commander/yargs. Useful for DevOps tooling interviews.
Q76advancedHow Node handles DNS?
`dns.lookup` uses OS (may use thread pool); `dns.resolve` uses c-ares network. Misconfigured DNS causes intermittent latency — cache carefully.
Q77intermediateWhat is a ticket / callback queue misconception?
JS has one call stack. Async completions queue callbacks/microtasks. Interviewers ask to predict output of mixed nextTick, promises, timeouts — practice those puzzles.
Q78intermediateExplain microtasks vs macrotasks in Node.
Microtasks: process.nextTick (special), then Promise jobs. Macrotasks: timers, setImmediate, I/O. Microtasks drain before next macrotask — explains Promise before setTimeout(0).
Q79advancedSecurity: prototype pollution in Node apps?
Merging untrusted JSON into objects can pollute Object.prototype. Use Object.create(null), freeze, or safe merge libs. Validate payloads with zod/joi.
Q80advancedReDoS risk?
Evil regex on user input can block event loop. Avoid unbounded quantifiers on untrusted strings; use safe parsers; set timeouts.
Q81intermediateHow to serve SSR with Node?
Next.js/Nuxt or custom ReactDOMServer.renderToString/stream. Cache pages, stream HTML for TTFB. Heavier CPU than pure API — scale accordingly.
Q82advancedObservability: OpenTelemetry in Node?
Traces, metrics, logs with correlation. Auto-instrument http/express/pg. Export to Jaeger/Datadog. Essential for production debugging distributed APIs.
Q83intermediateWhat is nestjs vs express?
NestJS opinionated TypeScript framework (modules, DI, decorators) on Express/Fastify. Express is minimal and flexible. Nest common in enterprise; Express common in interviews for fundamentals.
Q84beginnerHow do you handle multipart and JSON on same API?
Different Content-Types: express.json for application/json; multer for multipart. Don't apply wrong parser. Size limits per type.
Q85beginnerHorizontal vs vertical scaling Node apps?
Vertical: bigger machine. Horizontal: more instances behind LB. Stateless APIs scale horizontally easily; sticky sessions or shared store for state. Prefer horizontal in cloud.
Q86intermediateBlue-green / rolling deploy with Node?
Run new version alongside old; shift traffic; drain old connections. Needs graceful shutdown and backward-compatible APIs/migrations.
Q87intermediateDatabase migrations in Node stacks?
Knex/Prisma migrate/Flyway-like tools. Run migrations in release pipeline before traffic. Never auto-migrate from random app instances without lock.
Q88beginnerSoft delete vs hard delete?
Soft: deleted_at flag for audit/recover. Hard: permanent. Indexes must account for soft delete filters. GDPR may require hard delete/anonymize.
Q89intermediatePagination: offset vs cursor in Node APIs?
Offset easy but slow/deep pages inconsistent under inserts. Cursor/keyset stable for feeds. Return nextCursor. Default limit max to prevent abuse.
Q90intermediateFile system watchers (fs.watch) pitfalls?
Platform differences, duplicate events, not always recursive. For dev hot reload use chokidar. Don't build critical prod workflows on watch alone.
Q91beginnerWhat is npm link / local packages?
Symlink local package for development. Can cause duplicate React/deps issues. Prefer workspaces for monorepos.
Q92beginnerCorepack and package managers?
Node can manage yarn/pnpm versions via Corepack. pnpm saves disk with content-addressable store. Teams standardize on one PM.
Q93beginnerExplain NODE_ENV=production effects.
Many frameworks cache templates, reduce logs, minify behavior. Express views cache. Always set in prod. Don't use it as only security switch.
Q94advancedHow to prevent blocking the event loop with heavy CPU?
Break work into chunks with setImmediate between slices, use worker_threads, move to separate service, or precompute. Profile first — guess less.
Q95intermediateWhat is undici?
Modern HTTP client used by Node's fetch. Connection pooling, HTTP/1.1 & HTTP/2 support goals. Prefer over legacy request package (deprecated).
Q96advancedWhat is `AbortSignal.any()`?
`AbortSignal.any([s1,s2])` aborts when any input signal aborts—compose timeouts + user cancel. Pair with `fetch`/`fs` abortable APIs. Related: `AbortSignal.timeout(ms)`. Cleaner than manual listeners.
Q97advanced`diagnostics_channel` overview?
Core module for low-overhead pub/sub diagnostics inside Node and libraries (`channel.subscribe`). Useful for observability without heavy EventEmitter costs. Subscribe in ops tooling; publish sparse events from hot paths carefully.
Q98intermediateNode's built-in test runner (`node:test`)?
`import { test, describe } from 'node:test'` + `node:assert/strict`. Run with `node --test`. Good for lightweight core tests without Jest. Supports subtests, mocking (newer versions), and coverage flags evolving by release.
Q99advancedPermission model awareness (`--permission`)?
Experimental Node permission flags restrict fs/network access for defense-in-depth (supply chain). Still evolving—know it exists for secure scripting. Don't rely as sole sandbox for untrusted code yet.
Q100advancedSEA (Single Executable Applications) brief?
Node can bundle a script into a single executable for distribution (SEA). Useful for CLIs. Awareness: constraints around native addons, size, and build steps. Alternative: pkg/nexe ecosystems historically.
Q101beginnerNode watch mode?
`node --watch app.js` restarts on file changes—built-in alternative to nodemon for many apps. Great for local DX. Prefer process managers in production, not watch.
Q102intermediateWhat do `--experimental-*` flags imply?
APIs under active development may change; don't enable casually in production without pinning Node versions and reading changelogs. Track when features graduate to stable.
Q103advancedESM loaders brief?
Custom loaders (`--import`/`register`) hook module resolution/transform (TypeScript transpile-at-runtime, mocking). Powerful for tooling; keep production paths standard and simple. Prefer build steps for prod TS.
Q104intermediateWhy use `sharp` for images?
High-performance native image pipeline (libvips) for resize/compress/format convert in Node—far faster than pure JS. Common for upload thumbnails. Watch memory and input validation (image bombs).
Q105beginnerNodemailer pattern?
Create a reusable transporter (SMTP/API), send mail with HTML+text, handle errors/retries, never log credentials. Prefer queues (Bull) for reliability instead of sending in the request path for user-facing signup emails.
Q106advancedBull/Agenda deeper comparison?
Bull/BullMQ: Redis-backed queues, rate limits, retries, repeatable jobs, prioritization—strong for high throughput. Agenda: Mongo-backed job scheduling, familiar if already on Mongo. Choose by datastore and scale needs; always make jobs idempotent.
Q107beginner`fs.promises` vs callback FS?
Prefer promise APIs or `fs/promises` with async/await. Avoid mixing callback styles. For streaming large files use streams, not full `readFile` into memory.
Q108intermediateHow do you handle unhandled rejections in Node?
Listen to `process.on('unhandledRejection')`/`uncaughtException` for logging; prefer fixing root causes. Newer Node may exit on unhandled rejections depending on flags. Always await or catch promises.
Q109intermediateCluster module vs PM2 vs K8s pods?
Cluster forks workers sharing a server handle for multi-core. PM2 process manager for deploys/restarts. Kubernetes scales containers. Prefer container orchestration in cloud-native setups; know cluster for classic Node scaling interviews.
Q110advancedWhat is the event loop phases reminder?
Timers → pending → idle/prepare → poll → check (setImmediate) → close callbacks; microtasks (promises) between. Blocking CPU starves I/O. Offload CPU with worker_threads/process pools.
Q111intermediate`worker_threads` vs `child_process`?
worker_threads share memory optionally (SharedArrayBuffer) with lighter weight for CPU tasks in-process. child_process spawns OS processes for isolation/CLI tools. Pick based on isolation vs overhead.
Q112advancedStreams backpressure — why?
Producers can outpace consumers. Use `.pipe`/`pipeline` and respect `writable.write` return/`drain`. Prevents unbounded memory growth on file/HTTP transforms.
Q113intermediate`crypto` module common uses?
Hashing (`createHash`), HMAC for webhooks, random bytes, scrypt/bcrypt via libs for passwords (not plain SHA). Prefer reputable password libraries (argon2/bcrypt).
Q114beginnerEnvironment config best practices?
12-factor: config via env, validate at startup (zod/envalid), never commit secrets, different configs per environment. `dotenv` for local only.
Q115advancedWhat is `package.json` `exports` field?
Controls public entrypoints for packages (subpath exports), enabling dual ESM/CJS and hiding internals. Modern packaging essential knowledge.
Q116beginnernpm vs pnpm vs yarn briefly?
npm default; pnpm content-addressable store + strict node_modules (saves disk, catches phantom deps); yarn classic/berry alternatives. Lockfiles must be committed.
Q117intermediateHow do you debug Node performance?
Use `node --inspect`, Clinic.js, CPU profiles, heap snapshots, and OpenTelemetry traces. Measure before optimizing. Watch event loop lag metrics.
Q118intermediateGraceful shutdown pattern?
On SIGTERM: stop accepting connections, drain in-flight requests, close DB pools, then `process.exit`. Important in K8s rolling deploys. Set sane timeouts.
Q119advancedWhat is N-API / native addons awareness?
Native modules bind C/C++ for performance (sharp, bcrypt). They must match Node ABI; use prebuilds. Increases install complexity on exotic platforms.
Q120beginner`fetch` in Node — status?
Global `fetch` (undici) is available in modern Node. Prefer it for HTTP; still know `http`/`https` modules and agents for advanced pooling/TLS.
Q121intermediateHow does `require` cache work?
CommonJS modules are cached after first load. `delete require.cache[id]` for hot reload hacks—avoid in prod. ESM has different cache semantics.
Q122beginnerStructured logging in Node?
JSON logs with request IDs (pino/winston), levels, and correlation. Don't log PII/secrets. Ship to centralized aggregation.
Q123intermediateRate limiting at Node layer?
express-rate-limit / Redis token buckets for distributed limits. Combine with gateway limits. Return 429 + Retry-After.
Q124advancedWhat is `AsyncLocalStorage` used for?
Propagates request context (trace IDs, user) across async calls without param drilling. Foundation for many telemetry libs. Avoid storing huge objects.
Q125beginnerHelmet in Node/Express — why?
Sets security headers (CSP, frameguard, HSTS, etc.). Baseline hardening—still configure CSP carefully for your frontends.
Q126advancedBullMQ job idempotency?
Use stable job IDs, transactional outbox, and handlers that tolerate duplicates. At-least-once delivery is common—design for retries.
Q127advancedDetecting memory leaks in Node?
Heap snapshots over time, watch RSS/heapUsed, find retained closures/caches without bounds. Fix unbounded Maps/arrays and global caches.
Q128beginner`node:assert` vs third-party asserts?
Built-in assert fine for `node:test`. Jest/Vitest bring matchers/mocks. Prefer strict equality asserts to avoid surprises.
Q129intermediateWhat is an EventEmitter memory leak warning?
Default max listeners (10) warns when exceeded—often forgotten `on` without `off`. Raise carefully; prefer fixing listener leaks.
Q130intermediateFile upload processing pipeline?
Stream to object storage, validate MIME/size, virus scan async, generate derivatives with sharp via queue, store metadata in DB. Never trust client MIME alone.
Express.js
127 questions
Q1beginnerHow do you create a basic Express server?
```js
const express = require('express');
const app = express();
app.get('/', (req,res)=>res.send('OK'));
app.listen(3000);
``` Separate `app` export from `listen` for testing with Supertest.
Q2beginnerWhat is middleware in Express?
Function `(req, res, next) => {}` that runs in order. Can read/modify req/res, end the response, or call `next()` / `next(err)`. Everything in Express — logging, auth, parsers — is middleware. Error middleware has 4 parameters `(err, req, res, next)`.
Q3beginnerapp.use vs app.get vs app.post?
`app.use` mounts middleware for all methods (optionally on a path). `app.get`/`post` etc. register method-specific route handlers. Order matters: first match wins for routes. `use('/api', router)` mounts a sub-app/router.
Q4beginnerWhat does next() do?
Passes control to the next middleware matching the request. `next('route')` skips to next route. `next(err)` jumps to error-handling middleware. Forgetting next() hangs the request if you didn't send a response.
Q5beginnerRoute parameters vs query vs body?
Params: `/users/:id` → `req.params.id`. Query: `/users?role=admin` → `req.query.role`. Body: JSON/form → `req.body` after parser middleware. Never trust any without validation.
Q6beginnerHow does express.json() work?
Middleware parses `Content-Type: application/json` body into `req.body`. Set `limit` to prevent huge payloads. Must be before handlers needing body. Invalid JSON → 400. Doesn't parse multipart — use multer.
Q7beginnerexpress.urlencoded usage?
Parses HTML form submissions (`application/x-www-form-urlencoded`). `extended: true` uses qs library for nested objects. Needed for traditional form posts; SPAs usually send JSON.
Q8beginnerHow do you serve static files?
`app.use(express.static('public'))` serves files from folder. Place before or after API routes carefully — avoid exposing secrets. Set Cache-Control. For SPAs, fallback to index.html for client routes after API routes.
Q9intermediateError handling middleware pattern?
```js
app.use((err, req, res, next) => {
console.error(err);
res.status(err.status || 500).json({ error: err.message });
});
``` Must have 4 args. Place last. Async errors: pass to next(err) or use wrapper.
Q10intermediateHow do you handle async errors in Express 4?
Express 4 doesn't catch rejected promises in async handlers automatically (unless using Express 5). Wrap: `const wrap = fn => (req,res,next) => Promise.resolve(fn(req,res,next)).catch(next);` or use express-async-errors. Always next(err).
Q11advancedExpress 5 vs Express 4 — notable change for async?
Express 5 improves rejected promise handling in middleware/handlers so fewer wrappers needed. Still know Express 4 patterns — many enterprise apps are on 4.x.
Q12intermediateHow do you implement authentication middleware?
Read Authorization header or cookie → verify JWT/session → attach `req.user` → next(). On failure 401. Separate authorize middleware checks roles → 403. Keep JWT secret in env.
Q13beginner401 vs 403 in Express APIs?
401 Unauthorized: not authenticated (missing/invalid token). 403 Forbidden: authenticated but not allowed. Interviewers watch for this distinction constantly.
Q14intermediateHow do you validate request data?
Use joi, zod, express-validator in middleware before controller. Validate params, query, body. Return 400 with field errors. Don't validate only on frontend.
Q15intermediateCORS with Express?
`const cors = require('cors'); app.use(cors({ origin: 'https://app.example.com', credentials: true }));` Reflecting any Origin is insecure. Handle OPTIONS preflight. Order: cors early.
Q16intermediateRate limiting middleware?
express-rate-limit: windowMs + max requests. For multi-instance use Redis store. Apply globally or per-route (stricter on /login). Return Retry-After header.
Q17beginnerHelmet in Express apps?
`app.use(helmet())` sets security headers. Customize CSP for React apps loading CDNs. One line that shows security awareness in interviews.
Q18beginnermorgan / request logging?
morgan logs HTTP requests (combined/dev formats). Prefer pino-http for JSON production logs with request IDs. Don't log bodies with passwords.
Q19beginnerres.json vs res.send vs res.end?
`res.json` sets Content-Type JSON and stringifies. `res.send` smart about types. `res.end` raw finish. Don't call multiple ending methods — headers already sent error.
Q20beginnerres.status().json() chaining?
Fluent API: `res.status(201).json(created)`. Always set correct status (201 create, 204 no content, 404, etc.). Default 200 if forgotten.
Q21beginnerHow do redirects work?
`res.redirect(302, '/login')` or `res.redirect(301, url)`. Use 302 for temporary. Validate redirect targets to prevent open redirect attacks.
Q22intermediateFile download with Express?
`res.download(path)` or `res.sendFile` with absolute path. Stream large files; set Content-Disposition. Check path traversal. Prefer cloud signed URLs for big assets.
Q23intermediateMulter for uploads — key options?
storage disk/memory, fileFilter MIME, limits fileSize. memoryStorage easy but RAM risk. Always rename files; never use raw user filename on disk.
Q24intermediateCookie-parser and sessions?
cookie-parser reads Cookie header into req.cookies. express-session manages server sessions. Secure cookies in production. Session store outside memory for scale.
Q25advancedCSRF with csurf (legacy) / modern approaches?
Cookie session apps need CSRF tokens. SPAs with Bearer tokens less exposed. SameSite cookies help. Know the threat model for interview.
Q26beginnerHow do you version Express APIs?
`app.use('/api/v1', v1Router)`. Duplicate routers for v2 with changes. Or header-based — less common. Document with Swagger/OpenAPI.
Q27intermediateNested routers example?
`router.use('/:userId/orders', ordersRouter)` — mergeParams: true to access parent params. Useful for resource hierarchies.
Q28intermediateapp.param for loading resources?
`router.param('id', async (req,res,next,id)=>{ req.user = await find(id); next(); })` preloads. Centralizes 404 if missing. Careful with async errors.
Q29intermediateHow to implement RBAC in Express?
After auth, middleware `requireRole('admin')` checks req.user.roles. Prefer permission checks over role-only for flexibility. Enforce on server always.
Q30advancedProxy trust and req.ip?
Behind nginx/ELB, without `app.set('trust proxy', 1)` req.ip is proxy IP. Needed for accurate rate limits and audit logs. Misconfiguration is a security footgun.
Q31beginnerCompression middleware?
`compression()` gzip/brotli responses. CPU tradeoff. Often better at reverse proxy. Don't compress already compressed (images).
Q32beginnerMethod override — when used?
HTML forms only GET/POST; method-override fakes PUT/DELETE. APIs with JSON rarely need it. Know it exists for legacy apps.
Q33intermediateHow do you test Express routes?
Supertest: `request(app).get('/users').expect(200)`. Mock service layer. Integration tests with test DB. Jest + supertest common stack.
Q34beginnerEnvironment-based config in Express?
dotenv in development; config module selecting by NODE_ENV. Never hardcode secrets. Different DB URLs per env. Fail if required env missing.
Q35intermediateCentralized error classes?
Custom `AppError extends Error` with statusCode, isOperational. Error middleware maps to JSON. Unexpected errors → 500 generic message, log stack.
Q36beginner404 handler placement?
After all routes: `app.use((req,res)=>res.status(404).json({error:'Not found'}))`. Before error middleware. Distinguish API 404 vs SPA fallback.
Q37intermediateSPA + API on same Express server?
API routes first, then static, then `app.get('*', send index.html)` for client router. Or separate hosts (preferred). Cache static assets aggressively.
Q38advancedWebSocket with Express?
Share HTTP server: `const server = http.createServer(app);` attach Socket.IO. Express middleware doesn't run on WS upgrade the same way — authenticate on handshake.
Q39advancedStreaming response in Express?
Pipe readable stream to res; set Content-Type. For large CSV/PDF generation. Handle client abort (`req.on('close')`). pipeline for safety.
Q40advancedPrevent blocking in an Express route?
No sync fs/crypto loops; no huge JSON transforms on main thread. Offload to queue/worker. Return 202 for long jobs. Interviewers ask this often.
Q41intermediateInput sanitization vs validation?
Validation: reject bad shape. Sanitization: clean strings (trim, escape). For Mongo, beware operators in query (`$gt`). Use allowlists.
Q42advancedMongoDB injection via Express query?
Passing req.query directly to find can inject operators. Sanitize with express-mongo-sanitize or convert types explicitly. Same idea as SQL injection awareness.
Q43advancedTransaction handling in Express services?
Start DB transaction in service, commit on success, rollback on error. Don't hold transactions open across external HTTP calls. Timeout transactions.
Q44intermediateIdempotent PUT/DELETE design?
PUT same payload → same state. DELETE already-deleted → 204. Helps clients retry safely. POST create often returns 409 on duplicate key.
Q45beginnerPagination middleware pattern?
Parse `page`/`limit` or cursor from query, clamp max limit, attach to req.pagination. Controllers pass to service. Document defaults.
Q46intermediateFiltering and sorting safely?
Allowlist sortable columns — never interpolate user sort string into SQL. Map query fields to columns explicitly.
Q47beginnerFile-based routing vs manual routers?
Express is manual. Frameworks like Nest/Adonis add structure. For interview: show clear router files without magic unless asked.
Q48intermediateHow do you mount multiple apps?
`app.use('/admin', adminApp)` compose. Useful for separating admin API. Shared middleware still applicable at root.
Q49intermediateres.locals usage?
Request-scoped data for views/middleware (e.g., current user for templates). Unlike app.locals which is app-wide. Cleared per request.
Q50intermediateapp.locals vs res.locals?
app.locals: global template variables. res.locals: per-request. Don't put request user on app.locals — race/leak across users.
Q51beginnerTemplate engines with Express?
EJS/Pug/Handlebars via `app.set('view engine')`. SSR server-rendered pages. For React SPAs, usually API-only Express. Escaping on by default — don't use unescaped user HTML.
Q52beginnerHow to set custom headers?
`res.set('X-Request-Id', id)` or `res.set({...})`. Use for correlation IDs, cache control, rate limit remaining. Helmet may override some — order carefully.
Q53intermediateCORS preflight failure debugging?
Check OPTIONS returns 204 with Allow-Headers matching request (Authorization, Content-Type). Credentials need explicit origin. Browser console shows blocked reason.
Q54intermediateexpress-validator chain example?
`body('email').isEmail(), validationResult(req)` → if errors 400. Runs as middleware array on route. Alternative: zod parse in middleware.
Q55intermediateDependency injection with Express?
Factory `createUserRouter({userService})` closes over deps. Avoid importing singleton db everywhere for tests. Nest does this formally.
Q56advancedGraceful shutdown with Express?
On SIGTERM: `server.close()` stops new conns; wait in-flight; close DB; exit 0. Track open sockets if needed. Critical for K8s.
Q57beginnerHealth and readiness routes?
`GET /healthz` always 200 if process up. `/readyz` checks DB pool. Don't require auth on these. Keep fast.
Q58advancedMicroservices: many Express services?
Split by domain; communicate via HTTP/gRPC/events. Shared library for auth/logging. Distributed tracing mandatory. Don't split too early.
Q59intermediateShared types between React and Express?
Monorepo package with zod schemas or OpenAPI codegen. Prevents contract drift. TS end-to-end is a strong interview talking point.
Q60beginnerMultipart + JSON endpoints coexistence?
Different routes/middleware stacks. Don't put multer globally on all routes. JSON routes use express.json only.
Q61intermediateHow to return CSV from Express?
Set Content-Type text/csv, Content-Disposition attachment, stream rows. Escape fields. For large exports use job + download link.
Q62advancedCompression + SSE conflict?
Server-Sent Events often need compression disabled for that route — buffering breaks streaming. Know edge cases.
Q63intermediateExpress behind reverse proxy path prefixes?
`app.use('/api', router)` or `app.set('trust proxy')` + path rewrite at nginx. Asset URLs must include prefix. Subpath deployment common.
Q64intermediateSecurity: mass assignment?
Don't `Model.create(req.body)` blindly — pick allowed fields. Prevents clients setting `role: admin`. Use DTOs/zod pick.
Q65intermediateLogging request ID middleware?
Generate uuid, set `req.id`, `res.setHeader('X-Request-Id')`, put in async local storage for logs. Correlate frontend and backend traces.
Q66intermediateTimeout middleware?
Abort long requests; free resources. `connect-timeout` or custom. Align with load balancer idle timeouts.
Q67beginnerHow do you organize env-specific CORS origins?
Array from env `CORS_ORIGINS=https://a.com,https://b.com`. Reject others. Dev localhost allowed only in development.
Q68intermediateExpress and GraphQL together?
Mount Apollo middleware on `/graphql` alongside REST. Same auth middleware can wrap. Prefer one style per domain if possible.
Q69beginnerWhat is application-level vs router-level middleware?
app.use applies broadly. router.use applies within router mount path. Prefer router-level for feature isolation.
Q70intermediateHow to mock external APIs in Express tests?
nock/msw intercept HTTP. Or inject http client interface. Contract tests for real integrations in CI staging.
Q71intermediateFeature flags in Express?
LaunchDarkly/unleash or env toggles checked in middleware/service. Keep kill switches for risky features.
Q72advancedMulti-tenant Express app patterns?
Tenant from subdomain/header/JWT claim; set DB schema search_path or filter tenant_id every query. Critical not to leak across tenants.
Q73intermediateSoft authentication (optional auth) middleware?
If token present verify and set user; if absent continue anonymous. Useful for public+personalized endpoints.
Q74beginnerHow to handle file size limits?
multer limits + reverse proxy client_max_body_size + express.json limit. Return 413. Document max size in API docs.
Q75advancedExpress performance tips?
async I/O, connection pooling, caching, compression at edge, avoid sync, profiling, cluster/scale out, efficient serializers. Measure with autocannon/k6.
Q76beginnerWhat is body-parser legacy?
Older Express needed body-parser package; modern Express has express.json/urlencoded built-in. Mentions show you know history.
Q77intermediateRoute ordering bug example?
`/:id` before `/me` captures "me" as id. Put specific routes before param routes. Classic interview footgun.
Q78beginnerHow do you implement search endpoint?
Query params q, filters, pagination. Parameterized SQL LIKE/full-text. Debounce on client. Rate limit expensive search.
Q79advancedWebhook receiver best practices?
Verify signatures (HMAC), idempotent processing, respond 200 quickly, async worker for heavy work, raw body for signature verify (express.json breaks it — use verify option).
Q80advancedRaw body for Stripe webhooks?
`express.json({ verify: (req,res,buf)=>{ req.rawBody = buf }})` or separate route with express.raw(). Signature needs exact bytes.
Q81intermediateDTO mapping in controllers?
Map DB models to public JSON — hide passwordHash, internal flags. Consistent serializers. Never dump sequelize instances raw without care.
Q82advancedOptimistic locking with version field?
Update WHERE id AND version; increment version. On 0 rows → 409 Conflict. Prevents lost updates in concurrent edits.
Q83advancedETag / conditional requests in Express?
fresh package or manual ETag; 304 Not Modified. Reduces bandwidth for unchanged GETs. Good caching discussion point.
Q84intermediateHow to deprecate an Express endpoint?
Sunsetting header, docs notice, monitor usage, then 410 Gone. Provide migration path to v2. Communicate with API consumers.
Q85intermediateInternal admin routes protection?
Separate router, IP allowlist, VPN, stronger auth, audit log. Never only 'hide' URL. Defense in depth.
Q86advancedExpress and Redis session store config?
connect-redis with client, secret rotation plan, cookie maxAge, rolling sessions. Fail strategy if Redis down (fail closed for auth).
Q87beginnerWhat to say when asked 'Why Express?'
Mature, simple middleware model, huge ecosystem, easy hiring, enough for most REST APIs. Mention Nest/Fastify when structure or perf needed. Shows balanced judgment.
Q88intermediateEnd-to-end login flow React + Express?
React POST /auth/login → Express validates → sets httpOnly cookie or returns JWT → React stores (memory/cookie) → Authorization on API → refresh rotation → logout clears. CORS credentials if cookie. Mention XSS/CSRF tradeoffs.
Q89intermediateExpress.js practice drill #97: What belongs in middleware vs controller vs service?
Middleware: cross-cutting (auth, logging, parsing, validation). Controller: HTTP concerns (status codes, mapping req/res). Service: business rules and DB calls. This separation is what interviewers mean by clean Express architecture and makes unit testing straightforward.
Q90beginnerExpress.js practice drill #98: What belongs in middleware vs controller vs service?
Middleware: cross-cutting (auth, logging, parsing, validation). Controller: HTTP concerns (status codes, mapping req/res). Service: business rules and DB calls. This separation is what interviewers mean by clean Express architecture and makes unit testing straightforward.
Q91intermediateExpress.js practice drill #99: What belongs in middleware vs controller vs service?
Middleware: cross-cutting (auth, logging, parsing, validation). Controller: HTTP concerns (status codes, mapping req/res). Service: business rules and DB calls. This separation is what interviewers mean by clean Express architecture and makes unit testing straightforward.
Q92beginnerExpress.js practice drill #100: What belongs in middleware vs controller vs service?
Middleware: cross-cutting (auth, logging, parsing, validation). Controller: HTTP concerns (status codes, mapping req/res). Service: business rules and DB calls. This separation is what interviewers mean by clean Express architecture and makes unit testing straightforward.
Q93advancedWhen do you use `express.raw()` for webhooks?
Stripe/GitHub webhooks need the raw Body Buffer to verify HMAC signatures. Use `express.raw({ type: 'application/json' })` on that route before `express.json()` parses it. Keep JSON parser off that path or verify from raw first.
Q94advancedCompression middleware pitfalls with SSE?
Gzip on Server-Sent Events can buffer responses and break streaming. Disable compression for `text/event-stream` routes. Also watch `Content-Length` vs chunked encoding.
Q95advancedHelmet CSP tuning — what to know?
Default CSP may block your CDNs/inline scripts. Set `contentSecurityPolicy` directives explicitly (`scriptSrc`, `imgSrc`, `connectSrc`). Prefer nonces/hashes over `unsafe-inline`. Report-Only mode helps migrate.
Q96intermediatecelebrate/Joi validation pattern?
celebrate wraps Joi schemas for params/query/body and returns structured 400 errors. Keeps validation out of controllers. Alternatives: zod + middleware. Always validate at the boundary.
Q97intermediatePassport strategies overview?
Passport middleware authenticates via strategies: local (username/password), JWT, OAuth (Google/GitHub). `passport.authenticate('jwt')` protects routes. Keep sessions vs JWT tradeoffs clear; serialize user carefully.
Q98advancedWhy `session.regenerate` on login?
Prevents session fixation: attacker sets a session id, user logs in, attacker reuses it. Regenerate session after privilege change and rotate CSRF tokens.
Q99intermediatecookie-parser signed cookies?
`cookieParser(secret)` enables `req.signedCookies`. Signing detects tampering (not encryption). Still mark cookies `httpOnly`, `secure`, `sameSite`. Don't store secrets in cookies.
Q100advanced`trust proxy` hops — why configure?
Behind reverse proxies, `req.ip` and secure cookie logic need `app.set('trust proxy', 1)` (or hop count). Misconfig enables IP spoofing via `X-Forwarded-For`. Know your proxy topology.
Q101intermediate`Router({ mergeParams: true })`?
Child routers don't receive parent route params unless `mergeParams: true`. Needed for `/users/:userId/posts` mounted routers reading `userId`.
Q102beginner`app.route` chaining?
`app.route('/book').get(...).post(...)` chains verbs for one path—cleaner than repeating the path. Same works on Routers.
Q103intermediate`express.static` `maxAge`?
Sets Cache-Control max-age for static assets. Use long maxAge with hashed filenames; short/none for `index.html`. Mis-caching SPAs causes sticky old clients.
Q104intermediateError codes pattern in Express APIs?
Create `AppError` with `status` + machine `code` (`USER_NOT_FOUND`), central error middleware maps to JSON. Don't leak stacks in production. Log with request IDs.
Q105beginnerOrder of middleware — classic interview?
Security/logging → parsers → auth → routes → 404 → error handler. Parsers before handlers needing body. Error middleware is 4-arg `(err,req,res,next)`.
Q106beginnerHow do you structure Express projects?
Layer routes → controllers → services → data access. Keep routers thin. Separate config. Use dependency injection light patterns for testability.
Q107intermediateCORS in Express — key options?
`origin`, `credentials`, `methods`, `allowedHeaders`. If `credentials: true`, cannot use `*` origin. Preflight OPTIONS must succeed. Configure explicitly for SPAs.
Q108intermediateFile uploads with multer pitfalls?
Limit size/MIME, store outside web root or stream to S3, unique names, virus scan async. Memory storage risks RAM; disk storage risks leftover files—clean temp.
Q109advancedSSE with Express?
Set `Content-Type: text/event-stream`, `Cache-Control: no-cache`, keep connection open, write `data: ...\n\n`. Disable compression; handle client disconnect (`req.on('close')`).
Q110beginnerVersioning Express APIs?
Prefix `/api/v1`, or header versioning. Avoid breaking changes; deprecate with docs. Keep routers modular per version when needed.
Q111intermediateHow to test Express apps?
Supertest against `app` without listening, mock services, separate DB for integration. Prefer injecting dependencies over importing singletons.
Q112intermediate`async` route handlers and errors?
Wrap async handlers so rejected promises call `next(err)` (wrapper or Express 5). Unhandled async errors otherwise hang/crash behavior depending on version.
Q113intermediateRate limiting middleware placement?
Early after identity of client is known (IP/user). Different limits for auth vs public. Store counters in Redis for multi-instance.
Q114advancedWhat does `next('route')` do?
Skips remaining handlers in the current route stack and jumps to the next matching route. Niche control-flow tool—don't overuse.
Q115beginnerServing SPA fallback with Express?
Static assets first, then `app.get('*', (req,res)=>res.sendFile(index.html))` for client routes—careful not to mask API 404s. Prefer reverse proxy static in production.
Q116advancedHelmet `crossOriginResourcePolicy` issues?
Can break cross-origin images/fonts if mis-set. Tune CORP/COEP/COOP only when you understand isolation needs (e.g., SharedArrayBuffer).
Q117intermediateSigned URL download pattern?
App authz checks then redirects to short-lived S3 signed URL; Express never streams entire object through Node when avoidable.
Q118intermediateCookie session vs JWT header — Express view?
Cookie sessions with httpOnly suit first-party browsers (CSRF protection needed). JWT bearer suits APIs/mobile. Hybrid possible. Know CSRF for cookie auth.
Q119beginner`express.urlencoded` extended option?
`extended: true` uses qs for nested objects; `false` uses querystring. Limit body size to mitigate DoS. Needed for HTML form posts.
Q120beginnerCentralized logging middleware?
Log method, path, status, duration, request id. Use morgan or custom; structured JSON in prod. Scrub sensitive headers.
Q121beginnerHow do you handle 404 vs 500?
404 middleware after routes: `res.status(404).json({error:'NOT_FOUND'})`. Error middleware last for 500/AppError. Don't `res.send` twice.
Q122beginnerRouter modularization for large apps?
`app.use('/users', usersRouter)` etc. Each module owns validation+routes. Share auth middleware factories.
Q123advancedWebhook idempotency in Express?
Store event IDs processed; return 200 for duplicates. Verify signatures first. Process async via queue for slow work.
Q124beginnerWhat is method-override used for?
Allows PUT/DELETE via forms using headers/query when clients only support POST—less common now with JSON APIs.
Q125intermediateSecurity: mass assignment prevention?
Don't `Model.create(req.body)` blindly—pick allowlisted fields. Validation schemas define permitted keys.
Q126beginner`res.json` vs `res.send`?
`res.json` sets JSON content-type and stringifies; `res.send` guesses type. Prefer `res.status(x).json(...)` for APIs.
Q127intermediateGraceful shutdown with Express server?
`server.close()` stops new connections; track open sockets; close DB. Important under K8s. Combine with health probes.
TypeScript
84 questions
Q1beginnerWhat is TypeScript and why use it with React?
TypeScript is JS + static types. Catches prop/type bugs at compile time, improves IDE autocomplete/refactoring, documents APIs. React+TS (`tsx`) types props and hooks. Compiles to JS; types erased at runtime.
Q2intermediateany vs unknown vs never?
`any` disables checking — avoid. `unknown` must narrow before use — safer. `never` for impossible values (exhaustive switches, always-throw functions).
Q3beginnerinterface vs type alias?
Both describe shapes. Interfaces can merge (declaration merging); types can use unions/intersections more flexibly. Many teams prefer `interface` for objects, `type` for unions. Be consistent.
Q4intermediateWhat are generics?
Type parameters for reusable code: `function identity<T>(x:T):T`. React: `useState<User|null>(null)`. Constrain with `extends`. Avoid over-generic APIs.
Q5beginnerOptional and readonly properties?
`age?: number` optional. `readonly id: string` cannot reassign. `ReadonlyArray<T>` / `Readonly<T>` utility types. Helps immutability intent.
Q6beginnerUnion and intersection types?
`string | number` union — value is one. `A & B` intersection — must satisfy both. Narrow unions with typeof/in/discriminants.
Q7intermediateType narrowing examples?
`typeof x === 'string'`, `x instanceof Date`, `'prop' in obj`, discriminated unions via `kind` field, custom type predicates `isUser(x): x is User`.
Q8intermediateDiscriminated unions?
Shared literal field: `{type:'ok';data:T}|{type:'err';error:string}`. Switch on type for safe access. Excellent for API result modeling.
Q9intermediateEnum vs union of string literals?
String unions (`'a'|'b'`) often preferred — simpler emit. Enums are real runtime objects (unless const enum). Numeric enums have reverse mapping quirks.
Q10intermediateconst assertions?
`as const` makes literals readonly narrowest types — tuple/literal inference. Useful for config objects and Redux action types.
Q11beginnerTyping React props?
`type Props = { title: string; onSave?: () => void }; function Card({title,onSave}: Props)`. Children: `React.ReactNode`. Prefer explicit over React.FC for some teams.
Q12beginnerTyping useState and useRef?
`useState<User|null>(null)`. `useRef<HTMLInputElement>(null)` — `.current` may be null. `useRef(0)` number mutable without render.
Q13beginnerTyping events in React?
`React.ChangeEvent<HTMLInputElement>`, `React.MouseEvent<HTMLButtonElement>`, `React.FormEvent`. Or infer from handler inline.
Q14intermediateUtility types: Partial, Required, Pick, Omit?
`Partial<T>` all optional; `Required` opposite; `Pick<T,'a'|'b'>`; `Omit<T,'a'>`. Compose for DTOs and form state.
Q15intermediateRecord and keyof?
`Record<string, number>` map-like. `keyof T` union of keys. `T[K]` indexed access. Foundation of mapped types.
Q16advancedMapped types briefly?
`{ [K in keyof T]: boolean }` transforms each property. Used to build Partial/Readonly equivalents and API mappers.
Q17advancedConditional types briefly?
`T extends U ? X : Y`. Distributed over unions. `infer` extracts types (ReturnType). Power tools — know existence.
Q18intermediatetypeof and keyof operators in types?
`typeof value` captures value's type. `keyof` keys of type. `typeof config` for config objects without duplicating interface.
Q19intermediateType assertion vs type guard?
`as Type` forces compiler — unsafe if wrong. Type guards/narrowing are safer runtime checks. Prefer guards for external data.
Q20intermediateHow to type API JSON responses?
Define interfaces; validate at boundary with zod/io-ts (`z.infer<typeof schema>`). Don't trust backend blindly — runtime validation + types.
Q21beginnerstrict mode flags that matter?
`strict: true` enables strictNullChecks, noImplicitAny, etc. Catch null bugs early. Turn on for new projects.
Q22beginnernoImplicitAny and why?
Errors when type falls to any implicitly — forces annotations. Improves safety gradually in migrations.
Q23intermediateTyping fetch wrappers?
`async function getJson<T>(url: string): Promise<T>` plus runtime zod parse. Generics at call site: `getJson<User[]>('/users')`.
Q24intermediateDeclaration files .d.ts?
Types for JS libraries. `@types/package` from DefinitelyTyped. `declare module` for untyped pkgs. ambient types.
Q25advancedModule resolution node vs bundler?
Affects how imports resolve paths/extensions. Modern TS + Vite often `moduleResolution: bundler`. Mismatches cause IDE vs build confusion.
Q26advancedsatisfies operator?
Checks value matches type without widening: `const conf = {...} satisfies Config`. Keeps literal inference. TS 4.9+.
Q27intermediateprivate vs #private in TS/JS?
TS `private` compile-time only (erased). `#field` true runtime privacy. Prefer `#` when hard privacy needed.
Q28intermediateabstract classes in TS?
Cannot instantiate; subclasses implement abstract methods. Alternative: interfaces + composition. Less common in React apps.
Q29intermediateTyping Redux Toolkit slices?
createSlice infers actions; RootState and AppDispatch typed hooks `useAppSelector`/`useAppDispatch`. Avoid any in state.
Q30intermediateReact.ComponentProps utility?
Extract props type from a component for wrappers/HOCs. Reduces duplication when enhancing library components.
Q31beginnerChildren typing best practice?
`children?: React.ReactNode` accepts elements, strings, arrays, null. Avoid `JSX.Element` only — too narrow.
Q32intermediateTyping context default value?
`createContext<Auth|null>(null)` then null-check in hook `useAuth` throw if missing provider — clear failure mode.
Q33advancedOverloads in TypeScript?
Multiple call signatures before implementation. Useful for functions with different arg/return pairs. Keep small — prefer unions.
Q34advancedthis parameter typing?
Fake first param `function(this: HTMLElement)` types this without runtime arg. Used in callbacks/event binders.
Q35beginnerTuple types?
`[string, number]` fixed length/types. `as const` often produces readonly tuples. Useful for useState pairs conceptually.
Q36intermediateIndex signatures?
`{ [key: string]: number }` open maps. Conflict with specific props — use carefully or Record.
Q37beginnerUnknown on catch clause?
`catch (e: unknown)` then narrow — TS 4.4+ default in strict. Prevents assuming message exists.
Q38beginnerESLint + TS recommended?
`typescript-eslint` rules for unsafe any, floating promises. Pair with prettier. CI typecheck `tsc --noEmit`.
Q39intermediateMigrate JS to TS strategy?
allowJs, checkJs gradual; rename to tsx; replace any; strict late. Don't big-bang rewrite mid-delivery.
Q40advancedStructural typing vs nominal?
TS is structural — compatible shapes assignable even if different interface names. Nominal via brands/unique symbols if needed.
Q41intermediateExcess property checks?
Object literals checked for unknown props when assigned to typed vars — catches typos. Freshness check.
Q42beginnerTyping CSS modules?
`*.module.css` declaration or typed-css-modules. `styles.button` autocomplete.
Q43beginnerPath aliases in TS?
`paths` in tsconfig `@/` → `src/`. Bundler must mirror (Vite resolve.alias). Interview config awareness.
Q44intermediateReturnType and Parameters utilities?
Extract function return/params types without duplication. Good for wrapping APIs.
Q45intermediateNon-null assertion operator?
`value!` tells compiler non-null — runtime still can be null. Prefer proper narrowing; use sparingly.
Q46intermediateTyping environment variables?
Extend `NodeJS.ProcessEnv` or Vite `ImportMetaEnv`. Validate at startup.
Q47advancedGenerics on React components?
`function List<T>({items, render}:{items:T[]; render:(i:T)=>ReactNode})`. Infers T from items prop.
Q48beginnerWhat TypeScript does NOT do?
No runtime type checks (without extras), no performance optimization by itself, doesn't replace tests. Types are erased.
Q49beginnerts-node/tsx vs compile for prod?
Dev runners execute TS directly. Production: compile to JS for stability/startup. Docker runs node on dist.
Q50advancedWhat are branded types?
Nominal-ish typing via intersection with a unique brand: `type UserId = string & { readonly __brand: 'UserId' }`. Prevents mixing `UserId` and `OrderId` both as strings. Create via controlled constructors. Powerful for domain IDs.
Q51advancedTemplate literal types — example?
Types from string patterns: `type EventName = `on${Capitalize<string>}`;` or `type Api = `/api/${string}`. Combine with unions to encode routes/events. Used heavily in typed routing and CSS-in-TS libraries.
Q52intermediateWhat is `Awaited<T>`?
Recursively unwraps Promise types: `Awaited<Promise<Promise<number>>>` → `number`. Useful for typing async function results and library helpers.
Q53advancedWhat is `NoInfer<T>`?
Blocks inference from a type parameter position so TS infers from elsewhere. Useful in generic APIs where defaults would otherwise be over-inferred. Newer utility—awareness shows modern TS literacy.
Q54advanced`const` type parameters?
`function f<const T>(x: T)` infers literal/readonly tuples more precisely instead of widening. Great for typed route configs and builder APIs.
Q55advanced`satisfies` vs `as`?
`satisfies Type` checks compatibility while preserving the expression's narrower inferred type. `as Type` forces a cast and can lie. Prefer `satisfies` for config objects needing both validation and literal inference.
Q56advancedProject references — why?
`composite` projects with `references` in tsconfig split builds (app/ui/shared) for faster incremental compile and clearer boundaries. Use solution-style tsconfigs in monorepos.
Q57advanced`verbatimModuleSyntax` — what does it do?
Enforces that type-only imports use `import type` / `export type`, matching emit exactly. Prevents runtime imports that disappear after erase. Preferred modern hygiene setting.
Q58advanced`erasableSyntaxOnly` awareness?
Constraint (tooling/TS settings evolving) favoring syntax erasable by stripping types—discourages certain runtime-emitting constructs. Aligns with tools that type-strip without transpile (e.g., some Node pipelines). Awareness-level interview topic.
Q59intermediateReact Hook Form + Zod resolver typing?
`useForm<z.infer<typeof schema>>({ resolver: zodResolver(schema) })` keeps form values aligned with Zod. Infer input/output types carefully when Zod transforms exist (`z.input`/`z.output`). Single schema source of truth for UI+API.
Q60beginner`unknown` vs `any`?
`unknown` forces narrowing before use; `any` disables checking. Prefer `unknown` for external data then validate (zod). Avoid `any` except escape hatches.
Q61intermediateDiscriminated unions pattern?
Common `type` field: `type Shape = {kind:'circle'; r:number} | {kind:'square'; s:number}`. Switch on `kind` for exhaustiveness. Core TS modeling technique.
Q62beginner`strict` flag essentials?
Enables `strictNullChecks`, `noImplicitAny`, etc. Always on for serious projects. Fixes entire classes of bugs at compile time.
Q63intermediateDeclaration merging vs intersection?
Interfaces merge declarations; type aliases don't. Useful for extending library types. Prefer type aliases for unions; interfaces for object shapes that may merge.
Q64beginner`Pick`, `Omit`, `Partial`, `Required`?
Mapped utility types to transform object types. Compose carefully—`Omit` then `Partial` common for update DTOs. Prefer explicit types when utilities obscure meaning.
Q65intermediateGenerics constraints `extends`?
`function f<T extends {id:string}>(x:T)` constrains capabilities. Use defaults `T=string` sparingly. Avoid overly deep generic pyramids.
Q66beginner`readonly` and `as const`?
`as const` deep readonly literals/tuples. `Readonly<T>` / `readonly` props prevent mutation at type level (runtime still mutable unless frozen).
Q67intermediateType narrowing with predicates?
`function isFish(p: Pet): p is Fish` custom guards. Also `in` checks, `typeof`, `instanceof`. Exhaustive `never` checks in switches.
Q68advancedModule augmentation briefly?
Extend existing modules' types (`declare module 'express' { interface Request { user?: User } }`). Keep in `.d.ts` and ensure inclusion in tsconfig.
Q69beginner`eslint` `@typescript-eslint` value?
Catches `any`, floating promises, unsafe assignments beyond tsc. Pair with `strict` TS. Don't disable rules casually.
Q70advancedInfer keyword in conditional types?
`type Elem<T> = T extends (infer U)[] ? U : never` extracts types. Foundation of many utilities (`ReturnType`). Powerful but keep readable.
Q71intermediateEnums vs union literals?
String unions often preferred: tree-shakable, simpler. Numeric enums have quirks (reverse mapping). Const enums have caveats with isolated modules/bundlers.
Q72intermediateTyping `JSON.parse`?
Returns `any` historically—prefer `unknown` wrappers + zod validation. Don't trust network JSON without parsing schemas.
Q73beginner`paths` aliases in tsconfig?
`@/components/*` mapped to `src/components/*`. Must mirror in bundler/vite resolve. Great DX; keep consistent.
Q74advancedFunction overload signatures?
Multiple call signatures + one implementation. Use when return type depends on arguments. Prefer unions/generics when simpler.
Q75advanced`this` parameter typing?
`function f(this: HTMLElement)` types callable `this`. Useful for event method APIs. Not a runtime param.
Q76intermediateDiscriminated error results vs exceptions?
`type Result<T> = {ok:true; value:T} | {ok:false; error:E}` models failures in types. Useful at boundaries; don't replace all exceptions.
Q77beginnerReact props with `Children` typing?
`props: { children: React.ReactNode }` common. Prefer explicit props over `FC` legacy patterns if team style says so. Know `PropsWithChildren`.
Q78intermediateZod `z.infer` vs TypeScript interfaces dual maintenance?
Prefer schema-first: infer types from Zod to avoid drift. If OpenAPI-first, generate types. Dual hand-written types drift.
Q79advanced`exactOptionalPropertyTypes` awareness?
Distinguishes missing vs `undefined` values for optionals—stricter correctness. Can break loose patterns; enable intentionally.
Q80intermediateHow do you type env vars?
Parse `process.env` with zod at startup into a typed config object. Avoid scattering `process.env.X!` assertions.
Q81intermediateTuple types and labeled tuples?
`type Pair = [x: number, y: number]` improves readability. Rest tuples model variadic args. Useful with `as const` configs.
Q82advanced`satisfies` for route maps example intent?
Ensure every key maps to a Component while keeping literal keys for `keyof` navigation—without widening to string indexes via `as`.
Q83beginnerImport type vs value imports?
`import type { Foo }` erased entirely. Prevents accidental runtime cycles and matches `verbatimModuleSyntax`. Use when only types needed.
Q84advancedAssertion functions?
`function assert(x: unknown): asserts x is string` narrows after call. Good for invariants. Throws on failure.
Testing
82 questions
Q1beginnerUnit vs integration vs e2e tests?
Unit: small pure functions/components in isolation (fast). Integration: modules together (API+DB or component+hook). E2E: full UI browser flows (Cypress/Playwright) — slow but high confidence. Pyramid: many unit, fewer e2e.
Q2beginnerVitest vs Jest?
Vitest Vite-native, faster ESM, similar API to Jest. Jest mature ecosystem. Prefer matching project bundler.
Q3intermediateReact Testing Library philosophy?
Test user-visible behavior not implementation — `getByRole`, `getByLabelText` over test IDs when possible. Avoid testing state internals. Encourages accessible markup.
Q4beginnerHow to test a React button click?
`render(<Comp/>); await userEvent.click(screen.getByRole('button',{name:/save/i})); expect(...).toBeInTheDocument()`. Prefer userEvent over fireEvent.
Q5intermediateasync testing with findBy?
`findBy*` returns promise waiting for element — good after fetch. `waitFor` for non-element assertions. Always await.
Q6intermediateMocking fetch in component tests?
`global.fetch = jest.fn().mockResolvedValue({ok:true,json:async()=>({...})})` or MSW intercept. Reset mocks between tests. Assert loading→data transitions.
Q7intermediateWhat is MSW?
Mock Service Worker intercepts network in tests/dev at network level — realistic API mocking without coupling to fetch implementation.
Q8intermediateSnapshot tests pros/cons?
Pros: catch unexpected UI diffs quickly. Cons: large brittle snapshots rubber-stamped. Use sparingly for stable pure UI; prefer explicit assertions.
Q9beginnerCoverage metrics — what matters?
Line/branch coverage helpful but 100% ≠ quality. Prefer critical path coverage (auth, payments). Don't chase vanity coverage.
Q10intermediateSupertest for Express?
`request(app).get('/users').expect(200)` without listening port. Combine with test DB or mocks. Integration-style API tests.
Q11beginnerAAA pattern?
Arrange (setup), Act (call), Assert (expect). Keeps tests readable — mention in interviews.
Q12intermediateTest doubles: mock vs stub vs spy?
Stub: fake return. Mock: also assert calls. Spy: wrap real observing calls. Jest `jest.fn`, `spyOn`.
Q13intermediateFlaky tests causes?
Timers, real network, order dependence, shared state, animations. Fix: fake timers, MSW, isolate, await findBy.
Q14intermediateTesting hooks with renderHook?
`@testing-library/react` renderHook for custom hooks. Act around state updates. Or test via component using the hook.
Q15advancedHow to test error boundaries?
Render child that throws; assert fallback UI. Suppress console error noise carefully. Note boundaries don't catch event handler errors.
Q16beginnerCI testing best practices?
Run lint + unit on PR; e2e on main/nightly; fail on regression; cache deps; parallelize. Keep tests deterministic.
Q17beginnerTDD briefly?
Red-green-refactor: write failing test, implement, clean. Good for algorithms/pure logic; less rigid for exploratory UI.
Q18advancedMutation testing concept?
Tools change code to see if tests fail — measures test effectiveness. Advanced quality topic.
Q19beginnerTesting Redux reducers?
Pure functions: call reducer(state, action) expect next state. Easy unit tests without React.
Q20intermediateHow to fake timers in Jest?
`jest.useFakeTimers();` run debounce tests with `advanceTimersByTime`. Restore real timers after. Prevents slow tests.
Q21intermediateAccessibility testing tools?
jest-axe, eslint-plugin-jsx-a11y, manual keyboard. RTL getByRole encourages a11y.
Q22beginnerPython unittest vs pytest?
pytest simpler assert, fixtures; unittest stdlib class-based. Industry prefers pytest.
Q23intermediateMocking Python requests?
`responses`/`pytest-httpx`/`unittest.mock.patch`. Don't hit real network in unit tests.
Q24beginnerFactory/fixtures for test data?
Build valid objects in helpers; avoid huge duplicated JSON. faker libraries for variety.
Q25intermediateWhat not to test?
Third-party lib internals, trivial getters, implementation details that change often. Focus behavior/contracts.
Q26advancedVisual regression testing?
Chromatic/Percy screenshot diffs. Complements RTL. Optional advanced.
Q27intermediateLoad/performance testing APIs?
k6, autocannon against Express. Separate from unit tests. Mention for backend interviews.
Q28intermediatePlaywright vs Cypress — how do you choose?
Playwright: multi-browser (Chromium/Firefox/WebKit), strong auto-wait, parallel, API testing, good trace viewer. Cypress: excellent DX/time-travel, historically Chrome-first (broader now), opinionated. Pick based on browser matrix, parallel CI needs, and team experience—both excel at e2e.
Q29intermediatetesting-library `userEvent` vs `fireEvent`?
`userEvent` simulates realistic user interactions (typing, tabbing, click sequences) with proper events; `fireEvent` dispatches lower-level events. Prefer `userEvent` for confidence. Use `await userEvent.setup()` patterns in v14+.
Q30beginnerWhat does `jest.spyOn` do?
Wraps an existing method to track calls/restore later: `jest.spyOn(api, 'fetchUser').mockResolvedValue(...)`. Prefer spies over replacing entire modules when possible. Always restore mocks between tests.
Q31beginnerCoverage thresholds in CI?
Configure jest/vitest coverage thresholds (lines/branches/functions) to prevent regressions. Aim meaningful critical-path coverage, not 100% vanity. Enforce in CI as quality gate with pragmatic numbers.
Q32advancedContract tests with Pact — overview?
Consumer-driven contracts: consumer defines expected provider interactions; provider verifies against pact files. Catches breaking API changes before integration. Useful in microservice landscapes; complements—not replaces—e2e.
Q33intermediateVisual regression testing — what and tools?
Compare screenshots against baselines (Playwright screenshots, Chromatic, Percy). Catch unintended UI diffs. Flaky across OS/fonts—stabilize viewports, fonts, and animations (`prefers-reduced-motion`).
Q34intermediatepytest fixtures / parametrize / monkeypatch?
Fixtures provide setup/teardown DI (`@pytest.fixture`). `@pytest.mark.parametrize` runs table-driven cases. `monkeypatch` safely sets env/attrs/dicts for a test. Core of idiomatic pytest.
Q35intermediate`unittest.mock.AsyncMock` when?
Mock async functions/awaitables in Python tests. `AsyncMock` returns awaitable; assert `await` calls with `assert_awaited`. Mixing Mock vs AsyncMock causes `coroutine was never awaited` issues.
Q36beginnerComponent tests vs e2e — when to choose?
Component/integration (Testing Library): fast feedback on UI logic with mocked network (MSW). E2E: critical user journeys on real stack. Follow testing pyramid—many unit/component, fewer e2e. Don't e2e everything.
Q37intermediateMSW handlers — what problem solved?
Mock Service Worker intercepts network in browser/Node tests with realistic handlers—components use real `fetch` without mocking imports. Share handlers between tests and Storybook. Reset handlers per test.
Q38beginnerAAA pattern in tests?
Arrange, Act, Assert—structure clarity. One logical assert theme per test. Better names than `test1`.
Q39intermediateFlaky e2e common causes?
Race conditions, shared state, timezones, animations, network dependency. Fix with auto-waits, test isolation, deterministic seeds, retries sparingly as last resort.
Q40beginnerSnapshot tests pros/cons?
Quick catch of unexpected output changes; can become rubber-stamped noise. Prefer targeted assertions for critical behavior; use snapshots for large stable structures carefully.
Q41intermediateTest doubles: mock vs stub vs fake?
Stub returns canned data; mock verifies interactions; fake is working lightweight implementation (in-memory DB). Prefer fakes for readability when practical.
Q42intermediateHow do you test React hooks?
`renderHook` from testing-library, wrap providers, assert results/rerenders. For hooks tied to UI, prefer testing via component behavior.
Q43advancedCI parallelization strategies?
Shard e2e across runners (Playwright sharding), split unit by timing. Balance setup cost vs parallel gains. Fail fast on unit before heavy e2e.
Q44advancedMutation testing awareness?
Tools alter code to see if tests fail—measures test strength. Expensive; use selectively on critical modules.
Q45beginnerFactory/builder patterns in test data?
Build minimal valid entities with overrides (`makeUser({role:'admin'})`). Avoid giant fixtures that obscure intent.
Q46intermediateHow to test error boundaries?
Render a throwing child (suppress console), assert fallback UI. Keep intentional throws isolated.
Q47intermediateAPI integration tests vs contract tests?
Integration hits real/test DB; contracts verify consumer/provider expectations without full system. Both useful layers.
Q48beginnerVitest vs Jest briefly?
Vitest: Vite-native, fast ESM, Jest-compatible API. Jest: mature ecosystem. Choose based on toolchain (Vite apps often Vitest).
Q49intermediateAccessibility testing in CI?
axe-core integrations (jest-axe, Playwright axe) catch a11y regressions. Complements manual screen reader checks—doesn't replace them.
Q50intermediateTime mocking?
`jest.useFakeTimers()`, sinon clocks, or freezegun in Python. Always restore. Essential for expiry/retry logic.
Q51advancedTesting Redis/DB in integration?
Testcontainers or ephemeral docker services; transactional rollback fixtures; separate DB per CI job. Never hit prod.
Q52beginnerGolden rule of Testing Library queries?
Prefer queries by role/label/text reflecting how users interact; `getByTestId` last resort. Encourages accessible UI.
Q53beginner`findBy` vs `getBy` vs `queryBy`?
`getBy` throws if missing; `queryBy` returns null; `findBy` async waits. Use findBy for appearing elements.
Q54intermediateLoad testing vs functional e2e?
k6/Locust measure performance under concurrency; Playwright validates correctness. Don't conflate—both needed for releases of critical APIs.
Q55intermediateHow do you mock Next.js router?
Use official test utilities or wrap with mocked `useRouter`/`navigation` modules. Prefer integration against real routing when practical.
Q56beginnerCode coverage vs risk coverage?
Lines covered ≠ behaviors covered. Focus tests on business risk, authz, money, data loss paths—not only green percentages.
Q57beginnerPytest `conftest.py` role?
Shared fixtures discovered hierarchically. Keep local fixtures close; put cross-module ones in conftest carefully to avoid mystery fixtures.
Q58advancedContract test failure workflow?
Consumer publishes new pact → provider CI verifies → break fixes negotiated. Versioned pacts prevent surprise prod breaks.
Q59advancedVisual tests and animation?
Disable animations in test env CSS, wait for fonts/networkidle carefully, mask dynamic regions (dates). Stabilize before asserting pixels.
Q60advancedProperty-based testing awareness?
Hypothesis/fast-check generate many inputs to find edge cases. Complements example-based tests for parsers/algorithms.
Q61intermediateSmoke tests in production?
Synthetic monitors hit critical journeys post-deploy. Not a substitute for CI; catches env-specific failures.
Q62beginnerWhy isolate tests?
Shared mutable state causes order-dependent flakes. Each test sets up/cleans its data. Parallel safety matters in CI.
Q63advancedWhat is contract testing?
Contract tests verify that a provider API still meets consumer expectations (endpoints, schemas, status codes) without full end-to-end environments. Pact is a common tool. Catches breaking changes early in microservices. Consumers publish expectations; providers verify them in CI.
Q64advancedConsumer-driven contracts explained?
Consumers define the contract they need; providers run those contracts in their pipeline to ensure compatibility. Flips 'provider docs only' assumptions. Enables independent deployability. Requires discipline in CI ownership.
Q65advancedVisual regression testing deeper dive?
Screenshot comparison tools (Chromatic, Percy, Playwright screenshots) detect unintended UI changes across browsers. Stabilize with locked viewports, fonts, and masking dynamic data. Review diffs intentionally—not every pixel change is a bug. Pair with component tests for logic.
Q66intermediateFlaky visual tests—causes and fixes?
Animations, time-dependent UI, antialiasing, and lazy-loaded images cause flakes. Disable animations, freeze clocks, wait for network idle, and tolerate small diffs carefully. Quarantine flaky tests until fixed. Flakes erode trust in CI.
Q67intermediateContract tests vs e2e tests?
Contracts are fast, focused on integration boundaries; e2e validate whole user journeys slower and more brittle. Use both: contracts for service compatibility, few e2e for critical paths. Avoid duplicating all cases in e2e. Test pyramid still applies.
Q68advancedHow do you version contracts?
Evolve schemas additively when possible; version endpoints or use compatibility checks for breaking changes. Provider CI should test against multiple consumer contract versions during migrations. Communication across teams essential. Treat contracts as APIs.
Q69intermediateStorybook + visual regression workflow?
Build component states in Storybook; run visual diffs on stories per PR. Encourages isolated UI coverage. Catch theme/spacing regressions early. Integrates well with design systems.
Q70intermediateSchema-based API testing?
Validate responses against OpenAPI/JSON Schema in tests to catch field type drifts. Can generate cases from schemas carefully. Complements contract tests. Good safety for public APIs.
Q71advancedCross-browser visual testing considerations?
Different engines render fonts/subpixels differently—baseline per browser or tighten scopes. Prioritize Chromium plus one more if budget-limited. Focus on layout issues over antialiasing noise. Document accepted tolerances.
Q72beginnerWhat to mask in visual snapshots?
Timestamps, avatars from remote URLs, ads, and rotating carousels. Masking focuses diffs on meaningful UI. Over-masking hides real bugs—be deliberate. Same for dynamic charts.
Q73advancedProvider verification in Pact?
Provider replays recorded consumer interactions against a running provider (often with test doubles for deps). Failures mean a breaking change for that consumer. Runs in provider CI on each change. Heart of consumer-driven contracts.
Q74intermediateTesting webhooks with contracts?
Define expected payload shapes and verify both sender and receiver sides. Use signed test payloads. Prevents silent integration breakage. Often overlooked vs request/response APIs.
Q75intermediateAccessibility checks in visual pipelines?
Pair visual diffs with axe checks on Storybook/pages. Visual sameness does not imply accessible names/contrast. Shift-left a11y. Fail PRs on serious violations.
Q76intermediateHow do feature flags affect visual tests?
Pin flag states in test environments so snapshots are deterministic. Test critical flag combinations explicitly. Undeclared flags cause random diffs. Coordinate with flag defaults in CI.
Q77advancedPerformance of visual test suites?
Parallelize, shard, and reuse story builds. Full-page e2e screenshots are costlier than component stories. Keep a lean critical set blocking merges; broader set nightly. Budget CI minutes consciously.
Q78advancedContract testing for async messaging?
Message contracts define published event schemas; consumers verify they can handle them. Prevents poison messages after producer changes. Growing practice with event-driven systems. Same consumer-driven idea, different transport.
Q79beginnerWhen visual regression is the wrong tool?
Highly dynamic canvases/games or intentionally randomized UIs yield noise. Prefer unit tests for logic and limited e2e assertions. Do not force screenshots everywhere. Choose tools matching stability of UI.
Q80beginnerGolden file testing relation?
Snapshots of UI or JSON outputs act as golden files reviewed on change. Visual regression is golden images for UI. Discipline in review prevents rubber-stamping. Same pros/cons as Jest snapshots.
Q81intermediateBreaking change communication with contracts?
When providers must break, version and dual-run, notify consumers, and only remove old contracts after migration. Contracts make breakage visible before production. Process + tooling. Mature platform teams excel here.
Q82intermediateCombining Playwright e2e with visual checks?
Use Playwright for flows; assert screenshots on key stable pages. Keep assertions sparse. Share auth/setup fixtures. Powerful but maintain carefully to avoid flake farms.
REST API / HTTP
155 questions
Q1beginnerWhat is REST and its core constraints?
Representational State Transfer: client-server, stateless, cacheable, uniform interface (resources identified by URIs, representations via HTTP verbs), layered system. Not a protocol—a style using HTTP features. HATEOAS (hypermedia) is optional maturity level rarely fully implemented.
Q2intermediateSafe vs idempotent HTTP methods?
Safe: GET, HEAD, OPTIONS—no server state change expected. Idempotent: repeat request same effect—GET, PUT, DELETE, HEAD, OPTIONS. POST neither safe nor idempotent (creates new resources). PATCH may not be idempotent depending implementation.
Q3intermediateWhen use POST vs PUT vs PATCH?
POST: create subordinate resource or actions (`/orders/{id}/cancel`). PUT: replace entire resource at URI (client supplies full representation). PATCH: partial update JSON Patch or merge patch. PUT idempotent if same body replayed; POST creates new each time.
Q4beginnerHTTP status codes: 200, 201, 204, 400, 401, 403, 404, 409, 422, 429, 500?
200 OK body; 201 Created + Location; 204 No Content success no body. 400 bad request client; 401 unauthenticated; 403 forbidden authenticated no permission; 404 not found; 409 conflict duplicate; 422 semantic validation (common APIs); 429 rate limit; 500 server fault.
Q5intermediateRequest and response header essentials?
Request: Authorization, Content-Type, Accept, If-None-Match, Idempotency-Key. Response: Content-Type, Cache-Control, ETag, Location, Retry-After. CORS response: Access-Control-Allow-Origin etc.
Q6advancedHTTP/1.1 vs HTTP/2 vs HTTP/3?
HTTP/2 multiplexing single connection header compression server push limited use. HTTP/3 QUIC UDP faster handshake lossy networks. REST semantics unchanged—transport optimization.
Q7intermediateContent negotiation Accept header?
Client sends Accept application/json vs application/xml server picks representation 406 if none match. API versioning sometimes Accept vendor media type.
Q8beginnerScenario: DELETE returns 204 vs 200?
204 no body typical delete success. 200 may return deleted entity or metadata. Be consistent; clients handle both if documented.
Q9beginnerResource naming conventions?
Plural nouns `/users`, `/users/{id}/orders` nested max 2 levels prefer `/orders?user_id=`. Verbs in URLs avoided except actions modeled as sub-resources `/payments/{id}/capture`. Lowercase hyphen multi-word.
Q10intermediatePagination patterns cursor vs offset?
Offset/limit simple poor performance large offsets inconsistent with live inserts. Cursor/keyset `?after=cursor` stable for feeds. Return next_cursor has_more metadata.
Q11intermediateFiltering sorting sparse fieldsets?
Query params `?status=active&sort=-created_at&fields=id,name` reduces payload. Document allowed filters prevent unindexed queries.
Q12intermediateVersioning strategies?
URL path `/v1/` explicit; Accept header vendor type; rarely query param. Breaking changes new version maintain old deprecation timeline. Prefer additive non-breaking changes when possible.
Q13intermediateError response body structure?
Consistent JSON `{ "error": { "code": "VALIDATION", "message": "...", "details": [{"field":"email"}] } }` map to HTTP status. RFC 7807 Problem Details standard optional.
Q14advancedHATEOAS example?
Response includes `_links: { "self": "...", "cancel": { "href": "...", "method": "POST" } }` client discovers actions. Rare full adoption; OpenAPI more common contract.
Q15advancedBulk operations API design?
POST `/batch` with array partial success 207 Multi-Status or transaction all-or-nothing document semantics. Idempotency per item keys.
Q16intermediateOpenAPI/Swagger role?
Machine-readable contract generates docs clients mocks validation. Single source truth CI breaking change detection.
Q17intermediateSession cookie vs JWT bearer?
Session: server stores state cookie session id HttpOnly Secure SameSite. JWT: stateless signed claims client stores—rotation revocation harder short TTL refresh tokens. SPAs often HttpOnly cookie session or BFF pattern.
Q18advancedOAuth2 authorization code flow outline?
User redirects authorize server approves code exchanged server-side for access token refresh token never expose client secret browser. PKCE public clients SPAs mobile.
Q19intermediateCORS preflight when triggered?
Non-simple methods PUT PATCH DELETE custom headers Content-Type not application/x-www-form-urlencoded multipart text/plain. OPTIONS request Access-Control-Allow-Methods Headers Origin credentials.
Q20intermediateSameSite cookie Lax Strict None?
Lax default blocks cross-site POST cookies CSRF help. Strict all cross-site. None requires Secure cross-site embed SSO.
Q21beginnerHTTPS TLS why mandatory?
Encrypts transit prevents MITM stealing tokens cookies. HSTS header force HTTPS. Cert pinning mobile optional.
Q22intermediateRate limiting strategies?
Token bucket leaky bucket fixed window sliding log Redis store 429 Retry-After. Per IP per API key user tier.
Q23advancedIdempotency-Key header purpose?
Client sends unique key POST payment server stores result replay same response prevents double charge network retries.
Q24intermediateAPI key vs OAuth scopes?
API key simple server-to-server low granularity rotate manually. OAuth scopes delegated user permission fine-grained third party apps.
Q25intermediateCache-Control directives?
max-age public private no-store no-cache must-revalidate. CDN respects s-maxage. no-store sensitive data never cache.
Q26intermediateETag and If-None-Match flow?
Server ETag hash representation client sends If-None-Match on GET match 304 Not Modified save bandwidth body.
Q27advancedLast-Modified vs ETag?
Last-Modified second precision weak if rapid updates. ETag strong hash preferred conflict detection If-Match optimistic locking PUT.
Q28intermediateCDN cache invalidation?
Purge URL tag API deploy versioned assets filename hash cache bust query string v=2 discouraged long cache immutable.
Q29advancedStale-while-revalidate?
Serve stale cache background fetch fresh—smooth UX static assets service workers similar pattern.
Q30intermediateHTTP caching private authenticated APIs?
Cache-Control private max-age short or no-store default sensitive. Vary Authorization header if shared cache edge rare.
Q31intermediateScenario: GET cacheable but user-specific?
Usually not cache shared—private browser only or no-store. ETag per user still validates 304 private cache.
Q32advancedReverse proxy caching nginx?
proxy_cache_path key uri args headers bypass POST Set-Cookie auth locations.
Q33intermediateDesign CRUD for `/articles` endpoints.
GET list paginated; GET id; POST create 201 Location; PUT replace; PATCH partial; DELETE 204. Validation 422 business rules 409 slug exists.
Q34advancedLong running job API pattern?
POST returns 202 Accepted job id poll GET /jobs/{id} status or webhook callback SSE stream progress.
Q35intermediateFile upload REST approaches?
multipart form direct POST; presigned S3 URL client PUT then POST metadata; tus resumable large files.
Q36advancedWebhook delivery guarantees?
At-least-once retry exponential backoff signature HMAC idempotency event id consumer dedupe store processed ids.
Q37intermediateGraphQL vs REST when choose?
GraphQL flexible queries single endpoint mobile variable shapes N+1 risk complexity. REST simple cache HTTP tooling CRUD services public APIs. Hybrid common.
Q38advancedgRPC vs REST?
gRPC protobuf HTTP/2 streaming strong typing internal microservices. REST JSON browser friendly public. Gateway translate grpc-gateway.
Q39advancedScenario: 404 vs 403 hiding existence?
Security: return 404 unauthorized resource existence leak vs 403 policy choice document consistently admin vs public.
Q40beginnerHEAD request use?
Same as GET no body check existence headers ETag size before download.
Q41beginnerFetch vs axios differences?
fetch native Promise no timeout until AbortSignal axios interceptors timeout transform automatic JSON node browser.
Q42advancedHandling 401 refresh token flow client?
Queue requests refresh endpoint once retry original avoid storm single flight mutex logout if refresh fails.
Q43intermediateRequest timeout and retry best practices?
Set connect read timeouts retry idempotent GET not POST blindly respect Retry-After jitter backoff.
Q44intermediateCompression gzip brotli?
Accept-Encoding Content-Encoding reduce JSON payload CDN origin negotiate brotli better ratio.
Q45intermediateKeep-Alive connection reuse?
HTTP/1.1 default persistent reduces TLS handshake cost connection pool clients httpx requests session.
Q46advancedTrace context distributed tracing headers?
W3C traceparent tracestate propagate across services logs correlate request id X-Request-ID.
Q47intermediateScenario: Multipart form field file together?
Content-Type multipart/form-data boundary separate parts JSON metadata plus binary file stream.
Q48intermediateHTTP OPTIONS CORS response?
Server returns allowed methods headers max-age preflight cache duration.
Q49beginnerShould APIs use verbs in URL?
Avoid `/getUser` use nouns and HTTP methods except RPC-style actions clearly documented sub-resource.
Q50beginnerDate time format in JSON APIs?
ISO 8601 UTC Z suffix `2024-01-15T10:30:00Z` avoid ambiguous local strings.
Q51intermediateNull vs omit field absent optional?
Document contract PATCH omit means ignore null means clear field JSON merge semantics.
Q52intermediateEnvelope wrapping `{data: ...}` pros cons?
Pros meta pagination consistent; cons extra nesting breaks HTTP cache some tools prefer top-level array headers Link.
Q53intermediateHealth check endpoint?
GET /health live process up; /ready dependencies DB pass for k8s probes separate.
Q54beginnerAPI documentation beyond OpenAPI?
Examples changelog deprecation policy rate limits auth guide sandbox Postman collection.
Q55intermediateBreaking vs non-breaking change examples?
Non-breaking add optional field new endpoint. Breaking remove rename field change type require v2.
Q56advancedContract testing consumer driven?
Pact verify provider meets consumer expectations CI prevent drift microservices.
Q57advancedScenario: Implement optimistic locking REST.
Client sends If-Match ETag on PUT mismatch 412 Precondition Failed refresh merge.
Q58intermediateScenario: Search endpoint GET vs POST?
GET bookmarkable simple filters POST body complex query avoid long URL 414 limit.
Q59advancedScenario: Partial success batch import 100 records.
207 Multi-Status per-item status or transactional rollback single error document.
Q60intermediateScenario: API gateway responsibilities?
Auth rate limit SSL termination routing aggregation protocol translation logging.
Q61beginnerCompare 401 vs 403 with example.
401 no valid credentials login; 403 logged in cannot delete others post admin only.
Q62intermediateScenario: Pagination total count expensive?
Omit total estimate approximate cursor only next page exists flag.
Q63intermediateScenario: Deprecate endpoint gracefully.
Sunset header Link successor version docs metrics traffic 410 Gone after deadline.
Q64advancedScenario: Handle duplicate POST create.
Idempotency-Key store hash response 24h client retries same key same 201 body.
Q65advancedHTTP CONNECT method purpose?
Proxy tunnel HTTPS less common app dev knowledge.
Q66beginnerScenario: Return 200 with error field anti-pattern?
Mixes success failure breaks HTTP semantics clients middleware use 4xx 5xx proper status.
Q67intermediateScenario: Content-Type application/problem+json?
RFC 7807 type title status detail instance structured errors parsers.
Q68intermediateScenario: API versioning sunset communication?
Email changelog response header Deprecation Link migration guide monitor 404 spike old version.
Q69advancedLink header pagination RFC 5988?
Link rel=next prev first last URL in header machine readable alternative JSON meta offset cursor.
Q70advancedConditional POST idempotent retry network?
Idempotency-Key store hash body response 24h gateway duplicate POST safe payment APIs.
Q71beginnerMIME type application/json charset utf-8?
Always specify UTF-8 JSON default unicode escape rarely needed Content-Type header required.
Q72advancedHTTP range requests partial content 206?
Resume download video streaming Accept-Ranges bytes Content-Range segment large files CDN.
Q73advancedUpgrade header WebSocket handshake?
GET Switching Protocols 101 Connection Upgrade Sec-WebSocket-Accept derived key REST adjacent real-time.
Q74advancedTrailer headers HTTP/1.1 chunked?
Headers after body checksum grpc trailers metadata status late information.
Q75intermediateScenario: API gateway rate limit 429 body?
Retry-After seconds JSON error code RATE_LIMITED client exponential backoff respect header.
Q76advancedScenario: Binary protobuf REST coexistence?
Same resource Accept application/protobuf vs json content negotiation version schema protobuf smaller internal.
Q77intermediateSafe method cacheability?
GET HEAD cacheable unless Cache-Control no-store response marked. POST uncacheable typically.
Q78intermediateRedirect 301 vs 302 vs 307 vs 308?
301 308 permanent method preserved 308 POST stays POST. 302 307 temporary historical 302 changed method GET bug use 307 explicit.
Q79intermediateContent-Length vs Transfer-Encoding chunked?
Length known upfront vs streaming unknown size chunked encoding HTTP/1.1 disable HTTP/2 multiplex.
Q80intermediateDuplicate Content-Type missing?
Server infer sniff security risk X-Content-Type-Options nosniff client must send correct type.
Q81beginnerHost header importance?
Virtual hosting required HTTP/1.1 wrong host wrong site SNI TLS similar concept.
Q82intermediateUser-Agent usage today?
Feature detect discouraged privacy reduction Client Hints Sec-CH-UA replacing some use cases logging only.
Q83beginnerScenario: HEAD before GET large file?
Check Content-Length ETag Last-Modified decide download cache validate.
Q84beginnerScenario: 204 vs 200 empty body DELETE?
204 no content standard success DELETE 200 optional confirmation body consistency API contract.
Q85intermediateAPI changelog communication?
Deprecate header sunset date email docs version telemetry adoption before removal.
Q86beginnerSandbox vs production keys?
Separate credentials data isolation rate limit test cards stripe pattern rotate keys leak blast radius.
Q87intermediateRequest correlation id propagation?
X-Request-ID client or gateway generate log all services trace support ticket debug.
Q88intermediatePayload size limits?
Reject 413 Too Large early nginx client_max_body_size DoS prevention streaming alternative multipart.
Q89intermediateAPI monetization rate tiers?
Plan quota headers X-RateLimit-Remaining Reset upgrade path 429 business logic.
Q90advancedJSON schema validation gateway?
Central reject malformed before microservices reduce duplicate validation OpenAPI generate schema.
Q91intermediateScenario: Internal vs public API surface?
Public stable semver internal breaking ok gateway separate auth network VPC private.
Q92intermediateScenario: Mock server contract dev?
Prism WireMock OpenAPI examples parallel frontend backend development unblock.
Q93advancedMutual TLS mTLS API?
Client cert server validates both sides TLS common service mesh internal zero trust.
Q94intermediateJWT claims exp iss aud?
Validate expiry issuer audience signature algorithm allowlist reject none alg.
Q95advancedOWASP API top risks?
Broken auth excessive data exposure lack rate limit mass assignment injection misconfig.
Q96intermediateAPI key rotation procedure?
Dual key period old new accept revoke old monitor 401 spike clients update.
Q97intermediateBearer token storage SPA?
Memory only best HttpOnly cookie BFF avoid localStorage XSS steal.
Q98intermediateCORS credentials mode?
fetch credentials include cookies Access-Control-Allow-Credentials true specific origin not star.
Q99advancedSubresource Integrity SRI?
Script link integrity hash crossorigin CDN compromise detect tamper.
Q100intermediateSecurity headers API responses?
X-Content-Type-Options nosniff Cache-Control sensitive no-store Content-Security-Policy if HTML.
Q101advancedWhat is HATEOAS?
Hypermedia as the Engine of Application State: responses include links describing available next actions (`_links`). Clients navigate APIs dynamically. Rare in pragmatic JSON APIs but shows REST maturity awareness (Richardson level 3).
Q102advancedIdempotency-Key header — why?
Clients send a unique key on POSTs (payments); server stores response for that key so retries don't double-charge. Essential for at-least-once networks. Keys expire after a TTL; scope per user/operation.
Q103intermediateRFC 7807 `problem+json`?
`Content-Type: application/problem+json` with fields like `type`, `title`, `status`, `detail`, `instance`. Standardizes error shape across APIs. Better than ad-hoc `{error: string}` for clients.
Q104advancedWhat is mTLS?
Mutual TLS: both client and server present certificates—common for service-to-service zero-trust. Stronger than API keys alone for machine identity. Requires cert provisioning/rotation.
Q105intermediateAPI keys vs OAuth2/OIDC flows?
API keys identify a project/client simply (server-side, rotated). OAuth2 delegates authorization; OIDC adds identity (id_token). Use auth code + PKCE for SPAs/mobile; client credentials for M2M. Don't put long-lived secrets in browsers.
Q106intermediateRate limit headers commonly used?
`RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` (IETF draft) or legacy `X-RateLimit-*`. On 429 include `Retry-After`. Clients should backoff respectfully.
Q107intermediateConditional GET with ETag?
Server sends `ETag`; client later sends `If-None-Match`. If unchanged, 304 Not Modified saves bandwidth. Pair with `Cache-Control`. Strong vs weak ETags matter for ranges.
Q108advancedPATCH: JSON Merge Patch vs JSON Patch?
Merge Patch (RFC 7396): partial JSON object semantics (null deletes). JSON Patch (RFC 6902): ops array (`add`/`remove`/`replace`/`move`) with paths. Choose Merge for simple partial updates; JSON Patch for precise/conflict-aware edits.
Q109advancedGraphQL N+1 and DataLoader?
Resolvers that query per field cause N+1. DataLoader batches/caches loads per request tick. Also use query complexity limits and persisted queries for prod safety.
Q110intermediategRPC vs REST — choose when?
gRPC: efficient HTTP/2 protobuf, strong contracts, great internal microservices/streaming. REST/JSON: browser-friendly, cacheable, universal debugging. Gateways often translate externally to REST while internal uses gRPC.
Q111advancedWebhook signature verification pattern?
Provider sends HMAC header of raw body with shared secret. Compute on raw bytes before JSON parse; constant-time compare; reject mismatch. Replay-protect with timestamps/nonces.
Q112intermediateRetry-After and client retries?
Honor `Retry-After` seconds/HTTP-date on 429/503. Use exponential backoff + jitter; don't retry non-idempotent POSTs without Idempotency-Key. Cap attempts.
Q113beginnerSafe vs idempotent HTTP methods?
Safe: no state change (GET/HEAD). Idempotent: same effect if repeated (GET/PUT/DELETE). POST not idempotent by default. PATCH may or may not be depending on semantics.
Q114beginnerREST resource naming basics?
Nouns/plural `/users/1/orders`, avoid verbs in paths, use HTTP verbs for actions. Nested resources sparingly. Query for filters, not for mutations.
Q115intermediateHTTP caching: `Cache-Control` directives?
`no-store`, `no-cache`, `private`, `public`, `max-age`, `stale-while-revalidate`. Choose carefully for personalized data (`private`).
Q116intermediateContent negotiation?
`Accept` header selects representation (`application/json` vs `csv`). Server may respond `406` if it can't satisfy. Versioning sometimes via Accept profiles.
Q117beginner401 vs 403?
401 unauthenticated/missing-invalid credentials (with WWW-Authenticate). 403 authenticated but not allowed. Don't leak whether a resource exists if that is sensitive—sometimes 404.
Q118intermediateAPI pagination styles?
Offset/limit simple but unstable under inserts; cursor/keyset stable for feeds. Return `next_cursor`. Always cap page size.
Q119beginnerIdempotent PUT example?
PUT `/resources/{id}` replaces with client-known id—repeating yields same state. Good for upserts when IDs are client-generated.
Q120beginnerCORS preflight purpose?
Browser sends OPTIONS to check if cross-origin request with custom headers/methods is allowed before the real call. Servers must handle OPTIONS correctly.
Q121intermediateWhat is an API gateway responsibility?
Routing, authn/z, rate limit, TLS termination, request logging, sometimes aggregation. Keeps cross-cutting concerns off every service.
Q122intermediateVersioning strategies tradeoffs?
URL path `/v1` explicit; headers cleaner but harder to explore; content-type versioning niche. Communicate deprecation windows.
Q123advancedBulkheads for APIs?
Isolate thread pools/connections per dependency so one slow downstream doesn't exhaust the whole service. Pair with timeouts/circuit breakers.
Q124beginnerOpenAPI benefits?
Contract, codegen clients/servers, docs, mocking. Single source of truth when enforced in CI.
Q125intermediateWhen is GraphQL a bad fit?
Simple CRUD with heavy HTTP caching needs, file upload-heavy APIs, or teams without query cost controls. Complexity moves to the server.
Q126intermediateHTTP/2 multiplexing benefit for APIs?
Multiple streams over one connection reduce HOL blocking vs many HTTP/1.1 connections. Still design payloads carefully.
Q127intermediateSigned upload URLs flow?
Client asks API for permission; API returns short-lived signed URL to blob storage; client uploads directly. API never proxies large bytes.
Q128advancedOptimistic concurrency with `If-Match`?
Client sends ETag via `If-Match`; server updates only if matches—else 412. Prevents lost updates without heavy locks.
Q129advancedgRPC status codes vs HTTP?
gRPC has its own codes (`NOT_FOUND`, `UNAVAILABLE`) mapped at gateways to HTTP. Know mapping loosely for debugging.
Q130intermediateWebhook delivery guarantees?
Usually at-least-once with retries; receivers must be idempotent. Dead-letter after N fails; monitoring on failure rates.
Q131beginnerWhat is content hashing for downloads?
Provide checksums (SHA-256) for large artifacts; clients verify integrity. Related to SRI on the web.
Q132beginnerSOAP vs REST one-liner?
SOAP: XML protocol with strict WS-* standards; REST: architectural style over HTTP/resources usually JSON. Modern public APIs are mostly REST/gRPC/GraphQL.
Q133advancedRate limit algorithms brief?
Token bucket, leaky bucket, fixed/sliding window. Sliding window smoother; redis used for distributed counters.
Q134beginnerWhy avoid chatty APIs?
Many small calls hurt mobile/latency. Offer batch endpoints or GraphQL carefully; balance with caching.
Q135intermediateSecurity: mass assignment via JSON?
Clients send extra fields (`isAdmin:true`). Allowlist fields server-side; never bind raw JSON to privileged models.
Q136intermediateWhat is the GraphQL N+1 problem?
Resolvers that fetch a child resource per parent item cause one query for parents plus N queries for children. It devastates latency under nested queries. Classic GraphQL performance footgun. Spot it in logs as repeated similar queries.
Q137advancedHow does DataLoader fix N+1?
DataLoader batches and caches loads within a single request tick—collecting IDs then issuing one `WHERE id IN (...)` query. Per-request caching avoids cross-user leaks. Use in GraphQL resolvers for relationships. Still design SQL carefully for complex graphs.
Q138advancedJWT access vs refresh token rotation?
Short-lived access tokens authorize APIs; refresh tokens obtain new access tokens. Rotation issues a new refresh token and invalidates the old one on each use, limiting stolen refresh replay. Detect reuse as theft signal and revoke families. Store refresh tokens carefully.
Q139advancedExplain OAuth2 authorization code with PKCE.
Public clients (SPAs/mobile) start auth code flow with a code_challenge derived from a secret verifier; the token request proves the verifier. PKCE blocks intercepted authorization codes from being exchanged by attackers. Preferred over implicit flow. Use exact redirect URI allowlists.
Q140intermediateWhy was implicit flow deprecated for SPAs?
Implicit flow returned tokens in URL fragments, increasing leakage via history/logs/referrers and lacking client authentication patterns PKCE provides. Auth code + PKCE is current best practice. Interviewers expect this update. Migrate legacy implicit apps.
Q141advancedGraphQL persisted queries benefit?
Clients send query IDs instead of full query text—reduces bandwidth and lets servers allowlist known queries for security/DoS control. Useful in production mobile apps. Requires coordination of query catalogs. Complements depth limiting.
Q142advancedHow do you authorize GraphQL fields?
Enforce authz in resolvers or field middleware—not only at the HTTP endpoint—because clients choose fields. Hide sensitive fields from unauthorized callers. Test nested access paths. GraphQL makes over-fetching of secrets easier if unchecked.
Q143advancedRefresh token theft detection pattern?
If a rotated refresh token is reused, assume compromise, revoke the token family, and force re-login. Requires server-side refresh session storage. More secure than immortal refresh tokens. Pair with device binding when feasible.
Q144intermediateWhen choose GraphQL over REST?
When clients need flexible field selection and fewer round-trips for nested data, with strong schema tooling. REST/JSON may be simpler for uniform CRUD and caching. Hybrid exists (BFF GraphQL over REST services). Decide via client needs, not fashion.
Q145intermediateHTTP caching with authorization headers?
Authenticated responses are often private—`Cache-Control: private` and careful Vary. Shared caches must not store personalized data. CDNs need explicit rules. Mis-caching auth content is a severe leak class.
Q146intermediateIdempotency keys for POST payments?
Clients send a unique key; servers store the first result and replay it on retries, preventing duplicate charges. Essential for flaky networks. Expire keys thoughtfully. REST write safety pattern.
Q147beginnerProblem with tokens in query strings?
They leak via logs, Referer headers, proxies, and browser history. Prefer Authorization headers or secure cookies. Scrub logs. OAuth best practices forbid tokens in URLs for this reason.
Q148advancedGraphQL depth and complexity limits?
Attackers can craft deeply nested queries that explode resolver work. Enforce max depth/cost analysis and timeouts. Pair with auth and rate limits. Production GraphQL hardening essential.
Q149intermediateOIDC vs OAuth2 one-liner?
OAuth2 delegates authorization; OpenID Connect adds an identity layer (ID token) for authentication on top of OAuth2. Login 'Sign in with X' usually means OIDC. Do not confuse access tokens with proof of identity alone.
Q150advancedDevice authorization flow awareness?
Used for devices without rich browsers (TVs)—user approves on another device with a code. Niche but appears in API design talks. Still protect codes from brute force. Shows OAuth breadth.
Q151intermediateHow do you version GraphQL APIs differently than REST?
Often evolve a single schema carefully with additive changes and deprecations instead of `/v2` URLs. Breaking changes need coordinated clients. Schema registry tooling helps. Philosophy differs from REST versioning.
Q152intermediateBearer token validation checklist?
Verify signature, `exp`, `iss`, `aud`, algorithm allowlist, and revoke lists if used. Reject none/alg confusion. Clock skew tolerance should be small. Every API gateway should enforce this consistently.
Q153beginnerCORS preflight caching (`Access-Control-Max-Age`)?
Browsers cache preflight results for a time to reduce OPTIONS chatter. Set thoughtfully; too long delays policy changes. Does not replace server authz. Performance detail for SPA APIs.
Q154beginnerRate limit headers convention?
Often return `X-RateLimit-Limit/Remaining/Reset` or `Retry-After` on 429. Helps clients back off politely. Document policies. Edge gateways frequently implement this.
Q155intermediateWebhooks signing best practice?
Sign payloads with HMAC secrets; receivers verify signatures and timestamps to prevent forgery/replay. Provide rotation guidance. Essential for Stripe-like integrations. Never trust unsigned webhook traffic.
Backend Concepts
155 questions
Q1intermediateMonolith vs microservices tradeoffs?
Monolith: simpler deploy debug transaction single codebase scales vertically team small. Microservices: independent deploy scale technology isolation failures blast radius smaller complexity ops distributed tracing data consistency harder. Start monolith split when boundaries clear.
Q2beginnerWhat is a reverse proxy?
Sits before app servers nginx HAProxy route load balance SSL terminate cache static rate limit. Client sees proxy not origin IPs.
Q3intermediateLoad balancing algorithms?
Round robin least connections IP hash sticky sessions health checks passive active remove unhealthy nodes.
Q4beginnerHorizontal vs vertical scaling?
Vertical bigger machine limits cost downtime. Horizontal more nodes stateless session store Redis load balancer database scaling harder shard replicate.
Q5intermediate12-factor app principles summary?
Codebase config env dependencies backing services build release run processes port binding concurrency disposability dev/prod parity logs admin processes.
Q6advancedBFF pattern Backend for Frontend?
Separate API tailored mobile web aggregating microservices reduces over-fetching client complexity team owns BFF schema.
Q7advancedEvent-driven architecture basics?
Producers emit events broker Kafka RabbitMQ consumers react decouple async eventual consistency saga patterns.
Q8advancedCQRS overview?
Command Query Responsibility Segregation separate write read models optimize each event sourcing optional complexity justified high scale read write asymmetry.
Q9intermediateConnection pooling why?
Opening DB connection expensive pool reuse max connections prevent exhaust timeout queue pgbouncer RDS proxy serverless.
Q10intermediateORM vs raw SQL tradeoffs?
ORM productivity migrations dialect abstraction N+1 risk complex queries awkward. Raw SQL performance control report queries hybrid.
Q11advancedDatabase migration strategy zero downtime?
Expand contract migrate dual write backfill switch read contract remove old column phases reversible steps.
Q12intermediateRead replica use cases?
Offload analytics reporting read-heavy API eventual lag acceptable route SELECT replica sticky write master.
Q13advancedSharding vs replication?
Replication copies data availability read scale. Sharding partitions rows different nodes write scale cross-shard queries hard.
Q14intermediateACID recap backend perspective?
Atomicity all or nothing transaction. Consistency constraints Isolation concurrent levels Durability commit survives crash backend must choose isolation vs perf.
Q15intermediateOptimistic vs pessimistic locking?
Optimistic version column retry conflict update. Pessimistic SELECT FOR UPDATE holds row bank transfer prevent race.
Q16intermediateSoft delete pattern?
deleted_at timestamp filter queries preserve audit restore GDPR complicates true delete index partial where deleted_at is null.
Q17intermediateCache-aside pattern?
App check cache miss load DB set cache TTL return. Invalidate on write update delete stale risk TTL bounds.
Q18intermediateRedis use cases?
Cache session rate limit pub sub leaderboard sorted sets distributed lock not primary durable DB persistence options AOF RDB.
Q19advancedCache stampede mitigation?
Lock single flight recompute jitter TTL probabilistic early expiration request coalescing.
Q20intermediateMessage queue vs task queue?
Queue async work Celery RQ SQS decouple workers retry DLQ. Ordering guarantees partition key Kafka consumer groups.
Q21advancedAt-least-once vs exactly-once delivery?
Most MQ at-least-once duplicate idempotent consumer. Exactly-once hard Kafka transactions stream processing cost.
Q22intermediateDead letter queue purpose?
Failed messages after max retry inspect fix replay poison message isolation.
Q23intermediatePub sub vs point to point?
Pub sub fanout many subscribers topic. Point queue one consumer work distribution.
Q24advancedWrite-through vs write-back cache?
Write-through sync update cache and DB consistent latency. Write-back async speed risk loss on crash.
Q25beginnerPassword storage best practice?
bcrypt argon2 scrypt salt per user never plaintext SHA alone pepper optional HSM.
Q26intermediateRBAC vs ABAC?
Role based admin editor viewer simple. Attribute based policy engine fine grained resource owner department dynamic.
Q27advancedJWT refresh token rotation?
Short access 15m long refresh HttpOnly rotate refresh detect reuse revoke family stolen token.
Q28advancedSSO SAML vs OIDC?
SAML XML enterprise legacy OIDC JSON OAuth2 layer modern apps identity provider Google Okta.
Q29advancedMulti-tenant data isolation?
Separate DB schema row level tenant_id column filter middleware strict compliance separate instance.
Q30intermediateAPI authentication methods summary?
API key HMAC signature mTLS OAuth2 JWT mutual TLS high security service mesh.
Q31intermediateBrute force protection?
Rate limit captcha account lockout exponential delay audit log IP block WAF.
Q32intermediateSecrets management?
Vault AWS Secrets Manager env inject rotation never git KMS encrypt CI masked variables.
Q33advancedCircuit breaker pattern?
Fail fast after threshold open half-open probe recovery prevent cascade Hystrix resilience4j opossum naming.
Q34intermediateRetry with idempotency?
Transient network blip retry bounded idempotent ops POST with key safe duplicate handling.
Q35intermediateHealth liveness readiness probes?
K8s restart pod if live broken remove traffic if not ready DB migration warmup complete.
Q36intermediateStructured logging fields?
JSON timestamp level message trace_id user_id request_id searchable ELK Loki Datadog correlation.
Q37advancedMetrics RED USE method?
RED rate errors duration services. USE utilization saturation errors resources dashboards alerting SLO.
Q38intermediateSLA SLO SLI difference?
SLI measured metric availability latency. SLO target 99.9%. SLA contract breach consequences error budget.
Q39intermediateGraceful shutdown?
SIGTERM stop accept finish in-flight drain connections k8s preStop hook timeout before kill.
Q40intermediateBlue green vs canary deploy?
Blue green switch traffic instant rollback old stack idle. Canary gradual percentage new version monitor metrics rollback fast.
Q41beginnerDocker image vs container?
Image immutable layered filesystem template. Container running instance isolated namespaces cgroups.
Q42intermediateDockerfile best practices?
Multi-stage build small image non-root USER .dockerignore pin versions COPY package before code layer cache scan vulnerabilities.
Q43intermediateContainer orchestration why Kubernetes?
Schedule replicas self-heal rolling update service discovery config maps secrets HPA scale ingress network policies.
Q44intermediatePod Service Deployment Ingress?
Pod smallest unit one or more containers shared network. Service stable ClusterIP LoadBalancer. Deployment manages ReplicaSet rolling. Ingress HTTP routing rules.
Q45beginnerEnvironment config 12 factor?
Config in env not image ConfigMap Secret inject runtime same image all envs.
Q46advancedStatefulSet vs Deployment?
StatefulSet stable network id ordered persistent volume databases Kafka brokers Deployment stateless horizontal.
Q47intermediateResource requests limits?
Request schedule guarantee CPU memory limit cap OOMKill throttle prevent noisy neighbor capacity planning.
Q48advancedSidecar pattern?
Auxiliary container logging proxy mesh envoy same pod lifecycle share network volume.
Q49intermediateRepository pattern?
Abstraction data access swap implementation test mock ORM hide query details domain layer clean.
Q50intermediateDependency injection containers?
Wire interfaces implementations lifecycle singleton request scope test override FastAPI Depends Spring.
Q51advancedSaga distributed transaction?
Sequence local transactions compensating rollback choreographed events orchestrator microservices no 2PC.
Q52advancedOutbox pattern?
Write business row outbox table same transaction relay publish MQ avoid dual write inconsistency.
Q53advancedStrangler fig migration?
Gradually replace legacy route proxy new service incrementally reduce monolith risk.
Q54advancedAPI gateway vs service mesh?
Gateway edge north-south client to cluster. Mesh east-west service to service mTLS observability sidecar.
Q55intermediateFactory vs strategy pattern backend?
Factory creates appropriate handler payment type. Strategy interchangeable algorithm tax shipping interchangeable runtime.
Q56intermediateObserver pattern event bus?
Domain events decouple modules order placed notify inventory email analytics subscribers.
Q57advancedCAP theorem practical meaning?
Partition tolerance mandatory distributed choose CP consistency sacrifice availability or AP availability eventual consistency partition. Real systems tunable spectrum.
Q58intermediateEventual consistency examples?
DNS CDN S3 cross region replication social like count acceptable delay strong consistency checkout inventory payment.
Q59advancedDistributed lock Redis Redlock caveats?
Clock drift TTL fencing token Martin Kleppmann critique use consensus etcd zookeeper critical correctness.
Q60advancedTwo-phase commit limitation?
Blocking coordinator failure participants stuck rare modern avoid microservices prefer saga outbox.
Q61intermediateIdempotent consumer design?
Store processed message id unique constraint business natural key upsert safe replay.
Q62advancedBackpressure handling?
Slow consumer queue grows limit buffer drop throttle producer reactive streams bounded queue HTTP 503 retry.
Q63intermediateThundering herd on cache expiry?
Probabilistic early expiration lock recompute single flight stagger TTL.
Q64advancedSplit brain scenario?
Network partition two nodes both think primary data diverge quorum raft leader election fencing.
Q65beginnerSQL injection prevention?
Parameterized queries ORM bind never string concat input validation least privilege DB user.
Q66advancedSSRF server-side request forgery?
Validate URL block internal metadata IP 169.254.169.254 allowlist domains fetch user supplied URL feature.
Q67intermediateRate limiting distributed?
Redis sliding window token bucket per key IP user API key sync edge CDN WAF.
Q68beginnerInput validation server side always?
Client bypass trivial never trust frontend validate type length sanitize encode context output.
Q69intermediatePII handling GDPR basics?
Minimize collect encrypt rest transit retention policy right erasure audit access consent lawful basis.
Q70intermediateDependency vulnerability scanning?
Dependabot Snyk CI fail build critical CVE pin update SBOM supply chain Sigstore.
Q71intermediateDefense in depth layers?
WAF network firewall app auth validation DB encryption monitoring incident response.
Q72advancedTiming attack password compare?
Use constant-time compare hmac.compare_digest not early exit string equals.
Q73advancedScenario: Design URL shortener backend.
Hash base62 key collision check redirect 301 analytics count Redis cache hot URLs SQL shard scale read replicas rate limit create.
Q74advancedScenario: Handle payment webhook duplicate events.
Idempotent store event id processed table business logic once acknowledge 200 quickly queue async processing.
Q75intermediateScenario: Email send on signup failure rollback?
Outbox or after commit queue saga compensate delete user if email critical optional async retry DLQ manual.
Q76advancedScenario: Upload 5GB file architecture.
Presigned multipart S3 client chunk resume virus scan async metadata DB CDN serve not through app server memory.
Q77intermediateScenario: Scheduled daily report job.
Cron k8s CronJob Celery beat idempotent date parameter object storage email link timezone explicit UTC.
Q78advancedScenario: Multi region active active database?
Conflict resolution CRDT last write wins avoid user sticky region replication lag read local write global hard.
Q79intermediateCompare sync REST vs async message for order fulfillment.
REST simple immediate response queue decouple inventory shipping retry peak load user gets 202 track job.
Q80intermediateScenario: Debug slow API endpoint approach?
APM trace logs DB query explain index missing N+1 external call waterfall metrics p95 baseline compare deploy correlation.
Q81intermediateScenario: Feature flag rollout backend?
LaunchDarkly Unleash config evaluate user percentage kill switch without deploy database migration paired.
Q82advancedScenario: Zero trust internal services?
mTLS service identity short lived cert network policy no flat VPC trust verify every call.
Q83intermediateWebhook signature verification HMAC?
Server shared secret hash body timestamp constant time compare reject replay window.
Q84intermediateScenario: Choose PostgreSQL vs MongoDB?
Postgres relational ACID joins transactions reporting schema enforced. Mongo flexible schema document horizontal nested optional transactional multi doc now.
Q85advancedOpenTelemetry traces spans?
Instrument HTTP DB spans context propagate W3C traceparent vendor agnostic export Jaeger Tempo.
Q86intermediateLog aggregation vs metrics vs traces?
Logs discrete events metrics aggregated numbers traces request flow triage together correlated IDs.
Q87intermediateAlert fatigue prevention?
SLO based alerts actionable runbooks severity page only user impact not CPU 80 alone.
Q88intermediateFeature flag observability?
Expose evaluation reason variant metrics compare error rate canary decision.
Q89intermediatePostmortem blameless culture?
Timeline root cause contributing factors action items system fix not person punishment learning.
Q90intermediateRunbook on-call essentials?
Service owner dashboard links rollback steps escalation contacts dependency map known issues.
Q91intermediateSynthetic monitoring?
Probe external uptime API journey login scheduled alert before user flood detects regional outage.
Q92intermediateDatabase slow query log?
log_min_duration_statement pg_stat_statements index review periodic EXPLAIN ANALYZE production safe.
Q93advancedHorizontal pod autoscaler HPA?
K8s scale replicas CPU memory custom metrics prometheus adapter queue depth.
Q94intermediateDatabase connection storm?
Too many app instances exhaust max connections pooler pgbouncer limit per instance sizing.
Q95intermediateSticky sessions pros cons?
Session affinity load balancer state local memory problem node loss prefer Redis session external.
Q96advancedBulkhead pattern?
Isolate thread pools per dependency failure one service not exhaust all threads.
Q97advancedLeader election distributed?
Single writer coordinator raft etcd zookeeper cron job one active scheduler.
Q98intermediateCold start serverless?
Provision concurrency min instances VPC latency optimize package size init reuse.
Q99advancedMulti-tenant noisy neighbor?
Rate limit per tenant resource quota fair scheduling separate queues enterprise tier.
Q100intermediateDisaster recovery drill?
Restore backup new region RTO RPO documented runbook game day practice.
Q101advancedKafka vs classic pub/sub — interview framing?
Kafka is a durable distributed log: consumers track offsets, replay possible, high throughput, partitioned ordering per key. Classic pub/sub (SNS) fans out messages with less emphasis on long replay. Choose Kafka for event streaming/pipelines; simpler brokers for low-volume notifications.
Q102intermediateL4 vs L7 load balancers?
L4 (transport) balances TCP/UDP connections by IP/port—fast, simple. L7 (application) understands HTTP: path-based routing, header routing, TLS terminate, WAF. APIs often L7; raw sockets/DB sometimes L4.
Q103beginnerCDN role in architecture?
Caches static assets (and sometimes HTML/API via edge) near users, reducing origin load and latency. Configure TTLs, cache keys, purge on deploy. Origin shield and signed URLs for private content.
Q104intermediateDocker multi-stage builds — why?
Build in a fat image with compilers, copy artifacts into a slim runtime image. Smaller attack surface and faster pulls. Example: build Node/Go stage → final distroless/alpine stage with binary only.
Q105intermediateKubernetes pods and services brief?
Pod: smallest deployable unit (one/more containers sharing network). Service: stable virtual IP/DNS load-balancing across pod endpoints. Deployments manage replica pods; Ingress exposes HTTP. Probes for health.
Q106intermediateRedis pub/sub vs Redis as cache?
Cache: GET/SET with TTL/eviction for speed. Pub/sub: ephemeral messaging (no persistence of messages). For durable queues prefer Redis Streams/Lists or Kafka. Don't confuse cache aside with message durability.
Q107advancedCQRS brief?
Command Query Responsibility Segregation: separate write models from read models optimized for queries. Useful when read/write scale or shapes differ. Adds complexity—avoid for simple CRUD.
Q108advancedSaga pattern?
Distributed transaction alternative: sequence of local transactions with compensations on failure (choreography or orchestration). Used when 2PC is too brittle across services. Design compensations carefully (not always perfect undo).
Q109intermediateCircuit breaker pattern?
Stop calling a failing dependency after threshold; fail fast; half-open probe to recover. Prevents cascading failures and thread exhaustion. Pair with timeouts, retries (limited), fallbacks.
Q110advancedBulkhead pattern?
Isolate resources (pools/threads/queues) per dependency or tenant so one failure doesn't sink the ship. Inspired by ship compartments. Combine with circuit breakers.
Q111intermediateBlue-green vs canary deployments?
Blue-green: two full environments, switch traffic at once—fast rollback. Canary: gradual % of traffic to new version—observe metrics then promote. Canary reduces blast radius; needs good observability.
Q112intermediateHorizontal Pod Autoscaling basics?
HPA scales replica count based on CPU/memory/custom metrics (RPS, queue depth). Need resource requests set correctly. Doesn't fix DB bottlenecks alone—scale the right tier.
Q113intermediateConnection pooling why?
Creating DB connections is expensive. Pools reuse connections with max size limits. Mis-sized pools cause latency or DB overload (app instances × pool size!). Prefer PgBouncer for many app pods.
Q114intermediateRead replicas — uses and caveats?
Scale reads by replicating asynchronously. Caveat: replication lag—stale reads. Route write-after-read carefully (primary or session stickiness). Not a HA write solution alone.
Q115advancedCAP theorem statement?
Under network partition, a distributed system must choose consistency or availability (plus partition tolerance always for distributed). CP vs AP tradeoffs (e.g., ZooKeeper-ish CP vs Dynamo-style AP). Nuanced in practice with timeouts.
Q116intermediateBASE vs ACID?
ACID: strong transactional guarantees on a single DB. BASE: Basically Available, Soft state, Eventual consistency—common in distributed NoSQL. Choose per domain invariants (money vs social likes).
Q117beginnerEventual consistency example?
User updates profile photo; some CDN edges show old image briefly until cache expires/propagates. Design UX for staleness (refresh, versioning). Conflict resolution strategies matter (LWW, CRDTs).
Q118intermediateMessage queue vs event log?
Queue: compete consumers, message removed when acked—task distribution. Log (Kafka): retained, many consumer groups independently read—event sourcing/stream processing.
Q119intermediateIdempotent consumers?
At-least-once delivery ⇒ duplicates. Use idempotency keys/unique constraints so reprocessing doesn't double effects.
Q120beginnerObservability three pillars?
Logs, metrics, traces. Correlate with request IDs. SLOs/error budgets guide reliability work.
Q121advancedBackpressure in systems?
Slow consumers signal producers to slow down (TCP windows, reactive streams, queue length limits). Drop/shed load when overwhelmed—better than OOM.
Q122advancedSidecar pattern?
Helper container beside app (envoy proxy, log shipper) sharing pod network. Used by service meshes. Separates concerns at cost of resources.
Q123beginnerTwelve-factor config?
Store config in environment, treat backing services as attached resources, disposability, logs as event streams. Classic cloud-native checklist.
Q124advancedSharding strategies?
Hash/range/geo keys across DB shards. Rebalancing is hard—plan carefully. Hot keys need special handling.
Q125advancedCache stampede prevention?
When popular key expires, many requests hit DB. Use locking, early refresh, or probabilistic regeneration. Soft TTLs help.
Q126advancedOutbox pattern?
Write DB change + outbox row in one transaction; publisher relays to Kafka. Avoids dual-write inconsistency between DB and bus.
Q127intermediateRate limiting at gateway vs service?
Gateway protects globally; service enforces business quotas per user/tenant. Both often needed.
Q128beginnerStateful vs stateless services?
Stateless app tiers scale horizontally easily; push state to DB/Redis. Sticky sessions complicate scaling—avoid when possible.
Q129beginnerGraceful degradation examples?
If recommendations fail, show bestsellers; if ads fail, render page without them. Prioritize core user journeys.
Q130advancedMulti-region active-active challenges?
Conflict resolution, data residency, latency, and testing failover. Often active-passive first for simplicity.
Q131intermediateFeature flags in backend?
Decouple deploy from release; canary by user segment; kill switches. Ensure flags don't become permanent tech debt.
Q132advancedWhat is a service mesh briefly?
Infrastructure layer (Istio/Linkerd) for mTLS, retries, observability between services via proxies. Powerful ops control—adds complexity.
Q133beginnerObject storage vs block/file?
S3-like object storage for blobs at scale (images, backups). Block for disks/DBs; file for shared POSIX needs. Web apps usually objects for user media.
Q134advancedZero-downtime migration techniques?
Expand-contract: add new column/write both, backfill, switch reads, remove old. Avoid incompatible flips without dual-write periods.
Q135intermediateCapacity estimation interview tip?
State assumptions, estimate QPS, payload sizes, storage growth, and bandwidth. Round powers of 10; show back-of-envelope math clearly.
Q136advancedClean Architecture layers in practice?
Entities/domain at center; use cases/application services around them; adapters for UI/DB/web at edges. Dependencies point inward. Enables testing domain without Express/ORM. Keep it pragmatic—avoid pure ceremony for tiny apps.
Q137advancedHexagonal architecture ports and adapters?
Ports are interfaces the domain needs; adapters implement them for tech details (Postgres, HTTP, SMTP). Swap adapters without changing domain. Synonymously called ports & adapters. Great mental model for NestJS modules.
Q138beginnerNestJS overview for interviews?
NestJS is a Node framework inspired by Angular—modules, controllers, providers, and DI via decorators. Encourages structured backends with testable services. Supports Express/Fastify under the hood. Good when teams want opinionated architecture.
Q139intermediateNestJS modules and providers?
Modules encapsulate related providers/controllers; providers (services) are injectable dependencies. `exports` share providers across modules. Avoid circular module imports with forwardRef carefully. Composition root is the AppModule.
Q140intermediateNestJS pipes, guards, interceptors?
Pipes validate/transform input; guards handle authz; interceptors wrap request/response (logging, mapping). Middleware also exists for lower-level concerns. Together they form a clear request pipeline. Map them to cross-cutting patterns in interviews.
Q141intermediateDomain-driven design ubiquitous language?
Team shares the same terms in code and conversation as the business domain. Reduces translation bugs. Bounded contexts separate divergent meanings. Useful even without full DDD ceremony.
Q142advancedApplication service vs domain service?
Application services orchestrate use cases/transactions; domain services hold domain logic that does not naturally sit on one entity. Keep controllers thin. Naming clarity prevents logic in the wrong layer.
Q143intermediateHow does hexagonal help testing?
Replace adapters with fakes at ports—in-memory repos, fake clocks, fake payment providers. Tests run fast without DB. Forces explicit boundaries. Strong argument in architecture discussions.
Q144beginnerNestJS configuration patterns?
Use `@nestjs/config` with env validation (Joi/Zod) at bootstrap; inject `ConfigService` rather than reading `process.env` everywhere. Fail fast on missing secrets. Separate config modules per domain if large.
Q145advancedCQRS in NestJS awareness?
Nest offers CQRS module with commands/queries/events and handlers. Useful for complex domains; overkill for CRUD. Mentions show framework breadth. Start simple before CQRS.
Q146intermediateMapping DTOs at boundaries?
Convert API DTOs to domain models and persistence models deliberately. Prevents leaking ORM entities to clients. Use class-validator/Zod at the edge. Critical Clean Architecture hygiene.
Q147beginnerWhat belongs in controllers?
HTTP concerns: status codes, DTO validation, calling application services, mapping responses. Not business rules or SQL. Thin controllers are a recurring interview ideal. NestJS controllers follow this if services are used well.
Q148advancedOutbox pattern awareness?
Persist domain events alongside state changes in the same transaction, then publish asynchronously—avoids dual-write inconsistency. Common in reliable messaging. Pairs with hexagonal adapters for bus publishing.
Q149advancedAnti-corruption layer example?
Translate legacy CRM payloads into your domain types inside an adapter so legacy field names never enter core code. Enables gradual replacement. Hexagonal staple. Interview-friendly concrete story.
Q150intermediateModular monolith vs microservices?
Modular monolith keeps one deployable with strong internal module boundaries—often better until scaling/org needs demand services. Hexagonal modules fit modular monoliths well. Avoid distributed systems overhead prematurely.
Q151intermediateNestJS testing with TestingModule?
Create isolated DI modules, mock providers, and test controllers/services without full HTTP. Mirrors Angular TestBed ideas. Encourages constructor injection. Shows practical Nest knowledge.
Q152intermediateDependency rule violations symptoms?
Domain importing Prisma/Express types; inability to unit test without DB; circular imports across layers. Fix by introducing ports. Architecture reviews look for this. Refactor incrementally.
Q153intermediateUse-case driven API design?
Shape endpoints around application actions (`POST /checkout`) rather than only bare CRUD tables. Aligns API with Clean Architecture use cases. Reduces chatty clients. Good backend design signal.
Q154beginnerWhen NOT to use NestJS?
Tiny scripts, extreme minimal latency prototypes, or teams preferring minimal Express may skip Nest's ceremony. Nest pays off with larger teams/codebases. Be honest about tradeoffs. Framework choice is contextual.
Q155intermediateHexagonal vs layered—short contrast?
Layered organizes by technical role (controller/service/repo); hexagonal organizes by domain with swappable adapters emphasizing boundaries. They can coexist pragmatically. Focus on dependency direction either way.
Web Security
102 questions
Q1beginnerWhat is the OWASP Top 10 and why do interviewers ask about it?
The OWASP Top 10 is a periodically updated consensus list of the most critical web application security risks. Interviewers use it as a shared vocabulary to check whether you think beyond features into abuse cases. You do not need to recite numbers perfectly, but you should explain each risk class with a concrete mitigation. Treat it as a checklist for threat modeling, code review, and secure design discussions.
Q2intermediateExplain Broken Access Control (A01) and how you prevent it.
Broken access control means users can act outside their permissions—viewing another user's invoice, calling admin APIs, or escalating roles. Prevent it by enforcing authorization on every request server-side, using deny-by-default policies, and testing IDOR paths explicitly. Never rely on hiding UI buttons as security. Log and alert on repeated authorization failures.
Q3intermediateWhat is Cryptographic Failures (A02) in OWASP terms?
This covers weak or missing encryption: plaintext passwords, obsolete algorithms (MD5/SHA1 for passwords), HTTP for sensitive data, or hard-coded keys. Use TLS everywhere, store passwords with bcrypt/argon2, manage keys in a secrets manager, and prefer modern ciphers. Encrypt sensitive fields at rest when regulations or threat models require it. Rotate keys and certificates on a schedule.
Q4beginnerExplain Injection (A03) beyond just SQL.
Injection occurs when untrusted input is interpreted as code or commands—SQL, NoSQL operators, OS shell, LDAP, or template engines. Prevent it with parameterized queries, safe ORMs, allowlists, and never concatenating user input into interpreters. Escape/encode for the correct context when you must interpolate. Treat every external input as hostile until proven otherwise.
Q5advancedWhat is Insecure Design (A04)?
Insecure design is a missing or flawed security control in the architecture—not just a buggy implementation. Examples: no rate limits on login, trusting client-side prices, or lacking abuse cases in threat models. Fix with secure design reviews, threat modeling (STRIDE), and building controls early. Interviews reward candidates who discuss design-time security, not only patches.
Q6intermediateExplain Security Misconfiguration (A05).
Default passwords, verbose errors in production, open cloud buckets, unnecessary HTTP methods, and missing security headers all count. Harden baselines with infrastructure as code, disable debug modes, and scan configs continuously. Apply least privilege to services and storage ACLs. Misconfiguration is often the easiest win for attackers and the easiest prevention with checklists.
Q7beginnerWhat are Vulnerable and Outdated Components (A06)?
Using libraries or base images with known CVEs exposes you even if your code is clean. Pin versions, run npm audit/pip-audit/Snyk/Dependabot, and patch regularly. Prefer maintained packages and minimize dependency surface. Have a process for emergency upgrades when critical CVEs drop.
Q8intermediateExplain Identification and Authentication Failures (A07).
Weak passwords, missing MFA, session fixation, credential stuffing without rate limits, and exposing session IDs in URLs all fall here. Use proven auth libraries, salted password hashing, short-lived tokens, and secure cookie flags. Enforce MFA for privileged accounts. Monitor for anomalous login patterns.
Q9advancedWhat is Software and Data Integrity Failures (A08)?
This covers unsigned updates, insecure CI/CD, trusting unverified plugins, and deserialization of untrusted data. Verify package integrity (lockfiles, signatures), protect build pipelines, and avoid unsafe pickle/YAML loaders. Supply-chain attacks like malicious npm packages fit here. Treat build artifacts and auto-updates as attack surfaces.
Q10intermediateExplain Security Logging and Monitoring Failures (A09).
Without useful logs and alerts, breaches go unnoticed. Log auth failures, access-control denials, and admin actions—but redact secrets and PII. Ship logs to a central SIEM, set alerts, and rehearse incident response. Logging alone is not enough; someone must watch and act.
Q11advancedWhat is Server-Side Request Forgery — SSRF (A10)?
SSRF tricks your server into making HTTP requests to attacker-chosen URLs, often hitting internal metadata services or admin panels. Validate and allowlist outbound destinations, block link-local/metadata IPs, and avoid passing raw URLs from users to fetchers. Use network egress controls in cloud VPCs. Webhooks and preview-link features are common SSRF vectors.
Q12beginnerWhat is XSS and what are the main types?
Cross-Site Scripting injects attacker script into pages viewed by other users. Reflected XSS bounces from a request; stored XSS persists in a database; DOM-based XSS mutates the page via unsafe client-side JS. Impact ranges from session theft to full account takeover. Always encode output for the HTML/JS/URL context and prefer safe APIs like textContent over innerHTML.
Q13intermediateHow do you prevent XSS in a React app?
React escapes text children by default, which blocks many classic XSS cases. Avoid dangerouslySetInnerHTML unless content is sanitized (e.g., DOMPurify). Be careful with href=`javascript:` URLs and unsanitized markdown renderers. CSP as defense-in-depth further reduces impact if a bug slips through.
Q14intermediateHow does CSP help against XSS?
Content-Security-Policy restricts which scripts, styles, and origins can load. A strict policy with nonces or hashes blocks inline and injected scripts even if HTML injection occurs. Start in report-only mode, then enforce. CSP is not a substitute for output encoding—use both.
Q15intermediateWhat is CSRF and how do you stop it?
Cross-Site Request Forgery tricks a logged-in browser into sending an authenticated request to your site from another origin. Mitigate with SameSite cookies, anti-CSRF tokens synchronized with sessions, and checking Origin/Referer on state-changing requests. Prefer POST/PUT/DELETE for mutations and avoid relying only on secret cookies without CSRF defenses for cookie-based sessions.
Q16beginnerExplain SQL injection with a safe fix.
Attackers append SQL via string concatenation like `WHERE id='` + userInput. Use parameterized queries or prepared statements so input is never executable SQL. ORMs help when used correctly—raw string interpolation in ORM APIs is still dangerous. Least-privilege DB accounts limit blast radius if injection occurs.
Q17intermediateHow does NoSQL injection differ from SQL injection?
In MongoDB-style APIs, attackers may inject operators like `$gt` or `$ne` if you pass request JSON directly into queries. Validate types, allowlist fields, and avoid mixing user objects into query documents unchecked. Use schema validation (Joi/Zod) before the database layer. Parameterization concepts still apply—never trust structured input blindly.
Q18advancedWhat is remote code execution (RCE) in web apps?
RCE means an attacker runs arbitrary code on your server—via unsafe deserialization, template injection, eval of user input, or vulnerable native libraries. Never eval user data; avoid dangerous deserializers; sandbox carefully if you must execute user code. Patch aggressively and isolate services with least privilege and containers.
Q19intermediateExplain path traversal attacks.
Attackers use `../` sequences to read files outside the intended directory, e.g., `/static/../../etc/passwd`. Resolve paths, ensure the canonical path stays under an allowlisted root, and never concatenate user filenames unchecked. Prefer storing uploads with generated IDs, not user-supplied paths. Disable serving arbitrary filesystem paths from APIs.
Q20beginnerWhat is clickjacking and how do headers stop it?
Clickjacking embeds your site in a hidden iframe so users click disguised UI. Defend with `Content-Security-Policy: frame-ancestors 'none'|allowlist` or legacy `X-Frame-Options: DENY/SAMEORIGIN`. Also consider UX confirmations for sensitive actions. Do not rely only on JavaScript frame-busting scripts.
Q21intermediateWhat does HSTS do?
HTTP Strict Transport Security tells browsers to use HTTPS only for your domain for a period, reducing SSL-stripping attacks. Send `Strict-Transport-Security` with a suitable max-age over HTTPS first. Include subdomains carefully and understand preload lists are hard to undo. HSTS complements—not replaces—correct TLS configuration.
Q22beginnerExplain Secure, HttpOnly, and SameSite cookie attributes.
Secure sends cookies only over HTTPS. HttpOnly blocks document.cookie access, mitigating some XSS session theft. SameSite=Lax/Strict reduces CSRF by controlling cross-site cookie sends; None requires Secure. Set all appropriately for session cookies. Mis-set cookies are a frequent audit finding.
Q23advancedWhat JWT threats should you mention in interviews?
Classic issues: accepting `alg: none`, confusing public/private key algorithms, weak shared secrets, putting secrets in the client, and storing JWTs in localStorage where XSS steals them. Prefer short-lived access tokens, rotate refresh tokens, validate issuer/audience/exp, and store tokens carefully (often HttpOnly cookies). Never trust JWT payload without signature verification.
Q24beginnerWhy prefer bcrypt or argon2 over hashing passwords with SHA-256?
SHA-256 is fast—attackers try billions of guesses per second with GPUs. bcrypt and argon2 are deliberately slow and salted, raising brute-force cost. Prefer argon2id for new systems when available; bcrypt remains widely accepted. Always salt uniquely per password; never store reversible encryption of passwords.
Q25intermediateSession fixation vs session hijacking?
Fixation forces a victim to use an attacker-known session ID before login; mitigate by regenerating session IDs after authentication. Hijacking steals a valid session (XSS, network sniffing, malware). Use HTTPS, HttpOnly Secure cookies, idle timeouts, and re-auth for sensitive actions. Both are session-lifecycle threats, different root causes.
Q26advancedWhat is a dangerous CORS misconfiguration?
Reflecting arbitrary `Origin` headers with `Access-Control-Allow-Credentials: true` lets malicious sites read authenticated responses. Allowlist exact trusted origins; never use `*` with credentials. Validate CORS on the server deliberately—browsers enforce CORS for JS, not for curl or non-browser clients. CORS is not an authz mechanism.
Q27intermediateExplain IDOR with an example.
Insecure Direct Object Reference: changing `/api/orders/1001` to `/api/orders/1002` reveals another user's order if the server only checks 'is logged in'. Always verify the resource belongs to the principal or that they have a role. Use opaque IDs carefully still with authz checks—obscurity is not authorization. Automated IDOR testing is common in pen tests.
Q28intermediateWhat is mass assignment?
Binding request JSON wholesale onto a model lets attackers set fields like `isAdmin=true` or `balance=99999`. Use allowlists/DTOs that expose only intended fields. Frameworks (Rails, Nest, ORMs) historically had this class of bug. Explicit mapping beats automatic binding for security-sensitive models.
Q29beginnerHow does rate limiting help against brute force?
Limiting login or OTP attempts per IP/account slows credential stuffing and password guessing. Combine with lockouts, CAPTCHA after thresholds, MFA, and anomaly detection. Apply limits at API gateway and application layers. Return generic errors to avoid user-enumeration side channels when possible.
Q30advancedDescribe file upload attack risks and defenses.
Risks include malware uploads, polyglot files, path traversal in filenames, oversized DoS, and executing uploaded scripts if stored in web roots. Validate content type by magic bytes, rename files, store outside the web root or in object storage, scan when needed, and serve with safe Content-Type/CSP. Never trust client Content-Type alone.
Q31intermediateWhat is an open redirect and why is it dangerous?
An endpoint that redirects to a user-supplied URL can be used in phishing: your trusted domain forwards victims to a malicious site. Allowlist destinations or use relative paths only. Open redirects also amplify OAuth token theft flows. Treat redirect targets as untrusted input.
Q32beginnerHow do you talk about dependency vulnerabilities and npm audit?
Explain that transitive packages introduce CVEs; `npm audit`/`npm audit fix`, Dependabot, and lockfiles help. Triage severity and exploitability—not every advisory is equally urgent. Prefer well-maintained libraries and fewer dependencies. Mention CI gates that fail builds on critical vulnerabilities.
Q33beginnerWhat is good secrets management practice?
Never commit API keys or passwords to git. Use environment variables injected at runtime, or AWS Secrets Manager/HashiCorp Vault, with rotation. Scope credentials narrowly and audit access. If a secret leaks, rotate immediately and review logs—do not only delete the commit.
Q34intermediateExplain least privilege in application security.
Grant users, services, and DB accounts only the permissions they need—no more. A compromised low-privilege service should not reach production admin or all S3 buckets. Apply to IAM roles, DB grants, Kubernetes RBAC, and feature flags for admin tools. Review privileges periodically because they drift upward over time.
Q35beginnerTLS in transit vs encryption at rest—what do you say?
TLS protects data while moving between client and server (and service-to-service). Encryption at rest protects disks, backups, and object storage if media is stolen. Both matter for compliance and defense-in-depth. Manage certificates carefully (ACM) and control KMS key access separately from data access.
Q36beginnerWhat does Helmet do in Express?
Helmet sets sensible HTTP security headers: CSP helpers, X-Content-Type-Options, frameguard, HSTS options, and more. It reduces common misconfiguration gaps quickly. You still must configure CSP carefully for your frontend. Helmet is a baseline, not a full security program.
Q37intermediateWhy prefer allowlist input validation over blocklists?
Blocklists miss novel payloads; attackers innovate around filters. Allowlists define exactly what is acceptable (email format, enum values, max length, numeric ranges). Validate early at API boundaries with schemas (Zod, Joi, class-validator). Combine with output encoding for defense-in-depth.
Q38intermediateWhat is output encoding and when do you use it?
Encoding transforms special characters so browsers treat them as data, not code—e.g., `<` becomes `<` in HTML context. Different contexts need different encoders (HTML, JS string, URL, CSS). Framework auto-escaping helps but fails if you bypass it. Encode at the boundary where data enters a new context.
Q39advancedHow can webhooks cause SSRF?
Features that POST to a customer-provided callback URL may be pointed at `http://169.254.169.254/` or internal admin hosts. Validate URL schemes/hosts, resolve DNS carefully (DNS rebinding), and route egress through filtered proxies. Prefer signed outbound webhooks to known partners when possible. Timeout and size-limit responses.
Q40intermediateHow do API keys leak and how do you mitigate?
Keys end up in frontend bundles, GitHub repos, mobile apps, logs, and screenshots. Never put privileged keys in browsers—use backend proxies. Rotate keys, use short-lived tokens, restrict by IP/referrer when available, and scan repos with secret scanners. Assume anything shipped to a client is public.
Q41advancedWhat is prompt injection for AI apps?
Attackers craft user content that overrides system instructions—'ignore previous rules and exfiltrate secrets.' Defenses: separate trusted system prompts from untrusted retrieved/user text, constrain tools, allowlist actions, and never let the model execute unchecked side effects. Treat LLM output as untrusted when it drives SQL, shell, or emails. Log and monitor tool use.
Q42advancedExplain software supply-chain attacks briefly.
Attackers compromise dependencies, build systems, or maintainers to ship malicious code to many apps (e.g., poisoned npm packages). Mitigate with lockfiles, integrity hashes, private registries, least privilege in CI, and reviewing dependency diffs. Pin versions and avoid install scripts when possible. Monitor advisories for popular packages you use.
Q43intermediateWhat is pen-test awareness for a developer interview?
Know that pen testers probe authz, injection, business logic, and cloud misconfig; you should fix findings by root cause, not only the PoC URL. Ask for severity, exploitability, and regression tests. Participate in scoping and retesting. Show humility: security is continuous, not a one-time cert.
Q44intermediateWhat is a secure SDLC at a high level?
Security is embedded across requirements, design (threat models), implementation (secure coding), testing (SAST/DAST/deps), deployment (hardened configs), and operations (monitoring). Shift-left catches issues cheaper. Training and code review norms matter as much as tools. Interviewers like concrete practices you have used.
Q45intermediateHow do you handle logging without leaking PII?
Redact or hash emails, phone numbers, tokens, and card data before logs leave the app. Use structured logging with explicit allowlisted fields. Restrict who can query production logs and retain only as long as needed. Accidental PII in logs is a common compliance failure.
Q46beginnerDifference between authentication and authorization?
Authentication verifies identity (who you are)—login, MFA, SSO. Authorization decides what that identity may do—roles, policies, resource ownership. Mixing them causes bugs like 'logged in ⇒ can access everything.' Design both explicitly on every sensitive endpoint.
Q47beginnerWhat is defense in depth?
Multiple overlapping controls so one failure does not equal breach: WAF + input validation + parameterized queries + least privilege + monitoring. No single silver bullet. Explain with a layered example in interviews. It also guides prioritization when budget is limited.
Q48intermediateExplain security headers you would enable on an API/SPA.
Common set: CSP, HSTS, X-Content-Type-Options=nosniff, Referrer-Policy, Permissions-Policy, and frame-ancestors/X-Frame-Options. APIs may emphasize CORS correctly and cache-control for sensitive responses. Test headers with security scanners. Tune CSP to avoid breaking legitimate assets.
Q49intermediateWhat is cookie theft via XSS and how do HttpOnly cookies help?
Malicious script reads `document.cookie` and exfiltrates session IDs. HttpOnly prevents JS access to that cookie, reducing this vector. XSS can still act as the user (session riding) even with HttpOnly—so prevent XSS and use CSRF defenses. Prefer short sessions and re-auth for critical actions.
Q50advancedHow would you securely design a password reset flow?
Use single-use, time-limited, high-entropy tokens stored hashed server-side; send links over TLS email. Do not reveal whether an email exists if user enumeration matters. Invalidate tokens after use and rotate sessions post-reset. Rate-limit requests to slow abuse.
Q51advancedWhat is XXE and when does it appear?
XML External Entity attacks exploit XML parsers that resolve external entities, leaking files or causing SSRF. Disable external entity resolution in XML parsers; prefer JSON APIs when possible. Legacy SOAP/XML uploads are classic targets. Mention it as a parser-hardening issue.
Q52advancedExplain insecure deserialization briefly.
Deserializing untrusted data with powerful formatters (Java serialization, Python pickle) can execute code. Prefer JSON with schema validation and avoid native object deserialization from users. Digitally sign serialized blobs if you must. This maps to OWASP integrity and injection themes.
Q53advancedHow do you prevent host-header attacks?
Apps that trust the Host header for password-reset links can generate poisoned URLs. Configure allowed hostnames at the web server/framework and ignore untrusted Host values for absolute URL generation. Behind proxies, validate X-Forwarded-* carefully. Tie password resets to canonical configured domains.
Q54intermediateWhat is privilege escalation in web apps?
A normal user gains admin or another tenant's powers via flaws in roles, JWT claims, or horizontal/vertical access bugs. Test every role boundary and never take roles from client input without server verification. Use server-side policy engines when complexity grows. Audit admin endpoints separately.
Q55advancedHow should multi-tenant SaaS enforce data isolation?
Every query must be scoped by tenant_id from the authenticated context, not from a client-supplied header alone. Consider row-level security in Postgres and automated tests for cross-tenant access. Mis-tenanting is a critical incident class. Review background jobs and exports for tenant filters too.
Q56beginnerWhat is a WAF and what should you not expect from it?
A Web Application Firewall filters common exploits at the edge (SQLi/XSS signatures, rate patterns). It is a safety net, not a replacement for secure code. Tuned WAFs reduce noise and block commodity attacks. Overreliance creates false confidence.
Q57intermediateExplain SameSite=None vs Lax vs Strict for cookies.
Strict sends cookies only for same-site navigations—strong CSRF protection, may break some flows. Lax sends on top-level GET navigations cross-site but not on POSTs from other sites—balanced default. None allows cross-site sends and requires Secure—needed for some cross-site embeds. Choose based on CSRF risk and UX.
Q58advancedHow do you store refresh tokens securely in a SPA?
Prefer HttpOnly Secure SameSite cookies via a BFF/backend to avoid localStorage XSS theft. Rotate refresh tokens on use and revoke on logout. Keep access tokens short-lived. If you must use browser storage, harden XSS ruthlessly—still riskier.
Q59intermediateWhat is OAuth token leakage via referrer or logs?
Tokens in URL query strings leak via Referer headers, browser history, and server logs. Use POST body or headers, Prefer Authorization code + PKCE for public clients. Never put access tokens in URLs. Scrub logs of Authorization headers.
Q60intermediateExplain content-type sniffing risk and nosniff.
Browsers may interpret a response as HTML/JS even if served as another type, enabling XSS from uploaded content. `X-Content-Type-Options: nosniff` stops MIME sniffing. Serve user uploads with safe types and Content-Disposition: attachment when appropriate. Combine with CSP.
Q61advancedHow do you secure server-side templates against SSTI?
Server-Side Template Injection happens when user input is evaluated as template code (e.g., `{{7*7}}`). Never concatenate user input into template source; pass as data only. Sandbox engines carefully or avoid user-controlled templates. SSTI often leads to RCE.
Q62advancedWhat is business logic abuse vs classic OWASP bugs?
Business logic flaws misuse legitimate features—negative quantities, coupon stacking, race conditions on wallet debit—without classic injection. Prevent with clear invariants, transactions, idempotency keys, and abuse-case testing. Interviewers love race-condition checkout examples.
Q63advancedHow do race conditions create security bugs?
Two parallel requests may both pass a balance check before either debit lands, overspending credits. Use database transactions, row locks, atomic updates, or idempotency keys. Test with concurrent clients. Especially relevant for inventory, coupons, and one-time tokens.
Q64intermediateWhat should a security-focused code review look for?
Authz on every handler, injection sinks, secret handling, dangerous APIs (eval, innerHTML, child_process), SSRF-prone URL fetches, and logging of secrets. Check new dependencies and cloud IAM changes. Require tests for negative/unauthorized cases. Be constructive and specific.
Q65beginnerExplain HTTPS certificate validation basics.
Clients verify the server certificate chains to a trusted CA and matches the hostname. Disabling verification (common in rushed code) enables MITM. Use modern TLS versions and strong ciphers. Pinning is rare for general web but appears in some mobile apps.
Q66advancedWhat is certificate pinning tradeoff?
Pinning trusts specific certs/keys to defeat rogue CAs/MITM, but breaks when certs rotate if apps aren't updated. Most public websites rely on standard PKI + CAA/HSTS instead. Mention awareness without recommending pinning for typical web apps.
Q67intermediateHow do you protect admin panels?
Separate auth with MFA, IP allowlists or VPN, rate limits, detailed audit logs, and no shared accounts. Do not expose admin on the public internet without extra controls. Use short sessions and step-up auth. Alert on unusual admin actions.
Q68beginnerWhat is security.txt / responsible disclosure awareness?
Projects publish a security contact so researchers can report vulnerabilities privately. Companies should have a intake process, SLA, and non-punitive disclosure policy. Shows maturity beyond 'hope nobody finds bugs.' Mention briefly in culture discussions.
Q69advancedExplain HTTP Parameter Pollution briefly.
Duplicate parameters may be interpreted differently by proxies, apps, and WAFs—e.g., `id=1&id=2`. Normalize input parsing and define whether first/last wins. Can bypass filters inconsistently. Validate after framework parsing.
Q70intermediateHow does Subresource Integrity (SRI) help?
SRI lets browsers verify CDN scripts/styles match a cryptographic hash, mitigating compromised CDN content. Use `integrity` and appropriate `crossorigin` attributes. Combine with CSP. Useful when loading third-party static assets.
Q71beginnerWhat is a secure default posture for new APIs?
Deny by default, authenticate every route unless explicitly public, validate schemas, rate-limit, use HTTPS, structured logs with redaction, and security headers. Add authorization tests in CI. Prefer short-lived tokens and least-privilege DB users from day one.
Q72intermediateHow do you mitigate account enumeration?
Use identical responses/timing for 'user exists' vs not on login and password reset where feasible. Generic error messages reduce phishing aid and targeted attacks. Balance against UX needs—sometimes product requires existence checks. Rate-limit either way.
Q73intermediateExplain JWT storage: localStorage vs cookies.
localStorage is easy for SPAs but readable by any XSS. HttpOnly cookies resist JS theft but need CSRF protections. Many teams use BFF patterns with cookies. There is no perfect browser storage—reduce XSS and token lifetime either way.
Q74advancedWhat is 'alg:none' JWT attack?
Some libraries accepted tokens with algorithm set to none and empty signature, treating them as valid. Always explicitly allowlist algorithms (e.g., RS256/HS256) and verify signatures with the correct key type. Keep JWT libraries updated. Never let the header alone choose verification logic unsafely.
Q75advancedHow can a leaked JWT secret be catastrophic?
With HS256, anyone holding the shared secret can forge arbitrary tokens as any user. Store secrets in a vault, rotate, use strong entropy, and prefer asymmetric keys (RS256) so verification keys can be public. Monitor for anomalous identity claims. Treat JWT secrets like production root passwords.
Q76intermediateWhat is clickjacking vs CSRF—how do you contrast them?
CSRF forges requests using the victim's cookies without needing UI deception in an iframe; clickjacking UI-redresses your pages so victims click real controls. CSRF defenses focus on request authenticity; clickjacking defenses focus on framing policies. Both abuse browser trust features differently.
Q77advancedHow do you secure GraphQL against abuse?
Limit query depth/complexity, disable dangerous introspections in production if needed, enforce authz per field/resolver, and prevent N+1 data leaks of unauthorized fields. Validate inputs and rate-limit. GraphQL's flexibility can amplify DoS and over-fetching risks.
Q78advancedWhat is prototype pollution in JavaScript?
Attackers merge `__proto__` or `constructor.prototype` properties into objects, changing application behavior globally. Avoid unsafe deep merges of user JSON; use `Object.create(null)` where appropriate; update Lodash/jQuery-era utilities. Can lead to XSS or RCE in Node depending on gadgets.
Q79intermediateExplain secure file download patterns.
Authorize access before streaming; use object-storage pre-signed URLs with short expiry; set Content-Disposition and safe content types. Do not pass raw filesystem paths from clients. Log downloads of sensitive documents. Scan or watermark when policy requires.
Q80advancedWhat is mTLS and when is it used?
Mutual TLS authenticates both client and server with certificates—common for service meshes and partner APIs. It strengthens service identity beyond IP allowlists. Operational cost includes cert issuance/rotation. Mention as a zero-trust building block.
Q81advancedHow do you approach dependency confusion attacks?
Attackers publish public packages with internal names hoping builds fetch the public malicious version. Use private registries, scope packages, pin versions, and configure npm to prefer private feeds. Verify package provenance in CI. Especially relevant in monorepos with internal library names.
Q82beginnerWhat logging should you always avoid?
Passwords, session tokens, API keys, full credit card numbers, raw government IDs, and auth headers. Prefer correlation IDs and user IDs over PII. Truncate or hash when you must retain identifiers. Debug logs in production often cause accidental leaks.
Q83advancedExplain 'confused deputy' in web security terms.
A privileged service is tricked into misusing its authority on behalf of an attacker—classic in SSRF and OAuth misbinding. Mitigate by verifying caller intent, audience restrictions, and not blindly forwarding authority. Think carefully when one service calls another with broad credentials.
Q84intermediateHow do feature flags relate to security?
Flags can accidentally expose unfinished admin features or leak entitlements if evaluated only on the client. Enforce entitlements server-side; treat flags as hints for UX, not authz. Lock down flag admin consoles. Audit who can enable production flags.
Q85intermediateWhat is a secure approach to CORS preflight?
Respond to OPTIONS with explicit allowed methods/headers/origins; avoid reflecting arbitrary headers. Keep preflight caches reasonable. Remember simple requests may skip preflight—still enforce authz. Misunderstanding preflight leads to both breakage and false security.
Q86intermediateHow would you threat-model a new endpoint quickly?
List assets (data), actors (user, admin, anon, other services), entry points, and trust boundaries. Ask STRIDE questions: spoofing, tampering, repudiation, info disclosure, DoS, elevation. Pick mitigations and tests for top risks. Ten minutes of threat modeling beats days of incident response.
Q87advancedWhat is CSP nonce-based script loading?
Each response includes a random nonce; only `<script nonce=...>` matching the policy executes. Blocks injected scripts without nonces. Requires server-rendered nonces per request—harder for purely static hosting. Strong XSS mitigation when implemented correctly.
Q88beginnerExplain referrer policy for privacy/security.
`Referrer-Policy` controls how much URL info is sent on navigation/requests, reducing token leakage via query strings. Prefer `no-referrer` or `strict-origin-when-cross-origin` for many apps. Complements avoiding secrets in URLs. Small header, real impact.
Q89advancedHow do you secure WebSockets?
Authenticate the handshake (cookies/tokens), authorize per message, validate origin, and use `wss://`. Do not assume first-login auth lasts forever without revalidation. Rate-limit messages and handle reconnects safely. Treat WS as another API surface.
Q90beginnerWhat is safe error handling in production APIs?
Return generic messages to clients; log detailed stack traces internally with correlation IDs. Verbose DB/ORM errors leak schema and injection hints. Differentiate 401 vs 403 carefully without oversharing. Never return exception messages directly from frameworks in prod.
Q91intermediateHow does infrastructure security intersect with app security?
Open security groups, public S3 buckets, and overbroad IAM dwarfing careful app code. Collaborate with DevOps on private subnets, WAF, secrets, and patching. Interviews often expect full-stack awareness of cloud basics. Secure apps on insecure infra still fail.
Q92beginnerWhat is 'security through obscurity' and why is it insufficient?
Hiding admin URLs or using obscure IDs without real authz fails once discovered. Obscurity can be a minor layer but never the control. Pair unpredictability with strong authentication and authorization. Interviewers use this to probe maturity.
Q93advancedExplain how to rotate secrets without downtime.
Support dual keys during rotation: accept old and new, deploy new writers, then retire old. Use secrets managers with versioning. Coordinate JWT signing key rotation with `kid` headers. Practice rotation before incidents force it.
Q94beginnerWhat client-side security limits should you acknowledge?
Anything in the browser can be modified—hidden fields, disabled buttons, client-only validation. Server must revalidate prices, roles, and quotas. Client checks are UX, not security. This is a classic interview trap for juniors.
Q95advancedHow do you prevent email header injection?
If user input is placed into email headers, newlines can inject BCC/subject lines. Strip CR/LF from header fields and use well-tested mail libraries. Prefer APIs that set headers structurally, not via string templates. Still relevant in contact forms.
Q96intermediateWhat is a secure SDLC 'definition of done' security checklist item?
Example: authz tests for the new endpoint, dependency scan clean for critical CVEs, secrets not in code, and logging without PII. Team agrees features are not done without these. Makes security measurable in Agile delivery. Keep the checklist short enough that teams actually use it.
Q97beginnerHow do you respond if asked about a past security incident?
Use STAR: situation, your actions (contain, patch, root cause), and lessons (tests, tooling, process). Focus on learning and systems thinking, not blame. If you lack a production incident, describe a near-miss or lab finding responsibly. Never invent confidential details.
Q98intermediateExplain allowlisting redirect URIs in OAuth.
OAuth clients must pre-register exact redirect URIs so authorization codes are not sent to attacker sites. Loose prefixes or open wildcards cause token theft. Match exactly including path and scheme. Critical for any SSO integration work.
Q99beginnerWhat is the difference between hashing and encryption?
Hashing is one-way (passwords, integrity checks); encryption is reversible with a key (confidentiality). You verify passwords by hashing input and comparing digests, not decrypting. Confusing them is a common junior mistake. Mention salts/peppers for password hashes.
Q100advancedHow do you secure CI/CD against compromise?
Protect secrets in OIDC/role-based cloud auth rather than long-lived keys, restrict who can change workflows, sign artifacts, and isolate runners. Require reviews on workflow files. A poisoned pipeline can push malware to production as 'legitimate' deploys.
Q101intermediateWhat is browser sandboxing awareness for web developers?
Browsers isolate origins via the same-origin policy, limiting how sites read each other's data. Understanding SOP, CORS, and cookies explains many web security boundaries. Native RCE in browsers is rare for app devs; logic bugs across origins are common. Design assuming SOP is your friend—do not disable it casually.
Q102beginnerGive a concise secure coding mantra for interviews.
Validate inputs with allowlists, encode outputs by context, authenticate and authorize every request, keep secrets out of code, patch dependencies, and log safely with monitoring. Prefer proven libraries over home-grown crypto. Security is a property of the system, not a feature bolted on at the end.
Cloud & DevOps
100 questions
Q1beginnerWhat is AWS EC2 at a high level?
EC2 provides resizable virtual machines in AWS—you choose AMI, instance type, storage, and networking. You manage the OS patching unless using managed alternatives. Use security groups as virtual firewalls and IAM instance roles instead of embedding keys. Good for custom runtimes and lift-and-shift workloads.
Q2beginnerWhat is Amazon S3 used for?
S3 is object storage for files/blobs with high durability—static sites, backups, data lakes, and user uploads. Organize with buckets and keys; set least-privilege bucket policies and block public access by default. Use versioning and lifecycle rules for cost/safety. It is not a POSIX filesystem.
Q3beginnerExplain Amazon RDS briefly.
RDS is managed relational databases (Postgres, MySQL, etc.) with automated backups, patching, and Multi-AZ options. You trade some deep OS control for operational ease. Still design indexes, schema, and connection pooling yourself. Prefer private subnets and security groups locking access to app tiers.
Q4beginnerWhat is AWS Lambda?
Lambda runs code in response to events without managing servers—API Gateway, S3, SQS triggers are common. You pay per invocation/duration; cold starts and timeouts are tradeoffs. Package dependencies carefully and assign least-privilege IAM roles. Great for spiky or event-driven workloads.
Q5intermediateIAM users vs roles vs policies?
Users are long-lived identities for people (prefer SSO now); roles are assumable identities for services/people with temporary credentials; policies JSON-document permissions. Attach least-privilege policies to roles for EC2/Lambda. Avoid access keys on servers—use roles. Interviewers almost always ask this.
Q6beginnerWhat is a VPC?
A Virtual Private Cloud is your isolated network in AWS with CIDR ranges, subnets, route tables, and gateways. Place public resources in public subnets and databases in private ones. Control egress with NAT and security groups/NACLs. Network design is foundational cloud security.
Q7intermediatePublic subnet vs private subnet vs NAT?
Public subnets have routes to an Internet Gateway; private ones do not. Instances in private subnets reach the internet outbound via a NAT Gateway in a public subnet. Databases usually stay private. This pattern reduces direct attack surface on data tiers.
Q8beginnerWhat does an ALB do?
Application Load Balancer distributes HTTP/HTTPS traffic across targets (EC2, IPs, Lambda) with path/host routing and health checks. Terminate TLS on the ALB with ACM certificates commonly. Use target groups and sticky sessions only when needed. Essential for scalable web tiers.
Q9beginnerWhat is CloudFront?
CloudFront is AWS's CDN—caches content at edge locations to cut latency and origin load. Often fronts S3 or ALB with HTTPS. Configure cache behaviors, origin access controls, and WAF integration carefully. Great for static assets and global audiences.
Q10intermediateSQS vs SNS?
SQS is a queue for competing consumers processing messages asynchronously (decoupling). SNS is pub/sub fan-out to multiple subscribers (email, SQS, Lambda, HTTP). Common pattern: SNS fans out to multiple SQS queues. Both improve resilience versus synchronous coupling.
Q11intermediateWhat is DynamoDB?
DynamoDB is a managed NoSQL key-value/document store with seamless scaling and single-digit millisecond performance at any size when modeled well. You design partition keys carefully to avoid hot partitions. Offers on-demand or provisioned capacity. Not a drop-in SQL replacement—query patterns drive schema.
Q12beginnerGive an Azure one-liner awareness answer.
Azure is Microsoft's cloud with analogs like VMs, Blob Storage, Azure SQL, Functions, Entra ID (IAM), and AKS for Kubernetes. Concepts map closely to AWS with different names and admin UIs. Enterprises often choose Azure for Microsoft ecosystem alignment. Knowing the mapping shows cloud fluency.
Q13beginnerGive a GCP one-liner awareness answer.
Google Cloud offers Compute Engine, Cloud Storage, Cloud SQL, Cloud Functions, GKE, and IAM with strong data/ML services (BigQuery). Same shared responsibility and networking ideas as AWS. Mention GKE and BigQuery as common differentiators. Cross-cloud vocabulary matters more than memorizing every product.
Q14beginnerWhat is a Docker image vs container?
An image is an immutable packaged filesystem + metadata; a container is a running instance of an image with its own isolated processes. Images layer via union filesystems for reuse. Containers share the host kernel—lighter than VMs. Build once, run consistently across environments.
Q15intermediateWhat belongs in a good Dockerfile?
Start FROM a minimal trusted base, install only needed deps, copy code late for cache efficiency, run as non-root, and set clear ENTRYPOINT/CMD. Pin versions and scan images. Avoid secrets in layers—pass at runtime. Keep images small for faster pulls and smaller attack surface.
Q16intermediateExplain multi-stage Docker builds.
Multi-stage builds use one stage to compile/build and a final stage that copies only artifacts into a slim runtime image. This drops compilers and npm caches from production. Common for Go, Java, and Node builds. Improves security and image size simultaneously.
Q17beginnerDocker volumes vs bind mounts?
Volumes are managed by Docker for persistent data surviving container recreation; bind mounts map host paths directly—handy for dev, riskier in prod. Use volumes for databases and uploads. Remember permissions and backup strategies. Stateless app containers + external persistence is the usual pattern.
Q18beginnerWhat are Docker networks for?
They let containers communicate on isolated virtual networks by service name while controlling exposure. Bridge networks are common on single hosts; overlay networks appear in Swarm/K8s-like setups. Do not publish every port to the host. Network segmentation is part of container security.
Q19beginnerWhat is a Kubernetes Pod?
A Pod is the smallest deployable unit—usually one container, sometimes sidecars sharing network/storage. Pods are ephemeral; controllers recreate them. Address services via stable Services, not Pod IPs. Understanding Pods is step one of Kubernetes interviews.
Q20intermediateService vs Deployment vs Ingress in Kubernetes?
Deployment declares desired replicas and rolling updates for Pods. Service provides stable networking to Pods (ClusterIP/NodePort/LoadBalancer). Ingress routes external HTTP to Services with host/path rules and TLS. Together they form the basic app exposure model.
Q21intermediateConfigMap vs Secret in Kubernetes?
ConfigMaps hold non-sensitive config as key/value; Secrets hold sensitive data (base64-encoded by default—not strong encryption without extra setup). Mount as env vars or files. Prefer external secret managers for production. Never commit Secret YAML with real values to git.
Q22intermediateWhat is HPA?
Horizontal Pod Autoscaler adjusts replica counts based on CPU/memory or custom metrics. It scales out under load and in when quiet, within min/max bounds. Needs resource requests set correctly. Complements—not replaces—good performance engineering.
Q23beginnerCI vs CD in one minute?
Continuous Integration automatically builds and tests every change to catch breaks early. Continuous Delivery/Deployment automatically releases validated artifacts to environments. Together they reduce manual toil and cycle time. Pipelines as code (GitHub Actions, Jenkins, GitLab CI) implement them.
Q24beginnerGitHub Actions awareness?
Workflows in `.github/workflows` run jobs on events (push, PR) using runners and actions. Use secrets carefully, pin action versions, and prefer OIDC to cloud roles over long-lived keys. Matrix builds and caches speed feedback. Extremely common in modern full-stack teams.
Q25beginnerJenkins vs GitLab CI one-liners?
Jenkins is a flexible, plugin-rich automation server often self-hosted with Jenkinsfiles. GitLab CI integrates pipelines tightly with GitLab repos via `.gitlab-ci.yml`. Both can build, test, and deploy; choice is often organizational. Focus on pipeline design over tool dogma.
Q26intermediateBlue-green deployment?
Run two environments (blue live, green idle); deploy to green, test, then switch traffic. Instant rollback by switching back. Costs extra capacity during cutover. Reduces downtime versus in-place upgrades.
Q27intermediateWhat is a canary release?
Ship a new version to a small percentage of traffic/users, watch metrics/errors, then gradually increase. Limits blast radius compared to big-bang deploys. Needs good observability and automated rollback criteria. Popular with service meshes and progressive delivery tools.
Q28intermediateWhat is Infrastructure as Code and Terraform awareness?
IaC defines infra in versioned files reviewed like code. Terraform is a popular declarative tool using providers for AWS/Azure/GCP with plans and applies. State management and blast-radius control matter. Interviewers want why IaC beats click-ops: repeatability and auditability.
Q29intermediateCloudWatch vs Prometheus vs Grafana?
CloudWatch is AWS-native metrics/logs/alarms. Prometheus scrapes time-series metrics, common on Kubernetes. Grafana visualizes metrics from many backends with dashboards/alerts. Typical stack: Prometheus+Grafana on K8s, CloudWatch on pure AWS. Pick based on platform.
Q30beginnerWhat is the ELK stack for?
Elasticsearch, Logstash/Fluentd, and Kibana centralize log ingestion, search, and visualization. Helps debug distributed systems and security investigations. Watch costs and retention; redact PII. Alternatives include Loki, CloudWatch Logs, Datadog.
Q31intermediateHow should apps get secrets in AWS?
Prefer AWS Secrets Manager or SSM Parameter Store with IAM roles granting least privilege—not baked into images. Rotate secrets and audit access. Inject at runtime into ECS/EKS/Lambda. Never commit `.env` production secrets to git.
Q32intermediateList key 12-factor app ideas relevant to interviews.
Store config in the environment, treat backing services as attached resources, build/release/run separation, stateless processes, port binding, logs as event streams, and disposability. Guides cloud-native design. Deviations exist, but vocabulary shows maturity.
Q33beginnerHow do you manage environment configs safely?
Separate dev/stage/prod values; inject via env/secret stores; never hardcode prod URLs/keys. Use different cloud accounts or projects when possible. Document required variables. Fail fast on missing critical config at startup.
Q34intermediateWhat makes a good rollback strategy?
Keep previous artifacts immutable, automate redeploy of last known good, and use DB migrations that are backward compatible (expand/contract). Feature flags can disable bad code paths quickly. Practice rollbacks in drills. Monitoring must detect need to rollback early.
Q35intermediateHealth checks: liveness vs readiness?
Liveness asks 'should we restart this process?'; readiness asks 'should we send traffic?' A process can be alive but not ready (warming cache). Misconfigured probes cause restart loops or black-holing traffic. Essential Kubernetes/ALB knowledge.
Q36beginnerHorizontal vs vertical scaling?
Horizontal adds more instances; vertical grows CPU/RAM on one instance. Horizontal scales further and improves redundancy; vertical is simpler until hardware limits. Cloud favors horizontal with load balancers. Stateless apps scale horizontally more easily.
Q37intermediateServerless pros and cons?
Pros: no server patching, auto-scale, pay-per-use. Cons: cold starts, execution time limits, vendor constraints, local testing friction, and tricky networking/VPC configs. Great for event spikes; less ideal for long-running CPU-heavy jobs. Choose deliberately.
Q38beginnerHow do you show cloud cost awareness?
Right-size instances, use autoscaling, lifecycle old S3 data, prefer serverless/spot where fit, turn off idle non-prod, and set billing alarms. Tag resources for chargeback. Cost is a design constraint alongside latency and reliability.
Q39beginnerWhat is a CDN in one minute?
A Content Delivery Network caches static (and sometimes dynamic) content near users to cut latency and origin load. CloudFront, Cloudflare, Fastly are examples. Configure TTLs and cache keys carefully for correctness. Essential for global web performance.
Q40beginnerRoute 53 awareness?
Route 53 is AWS DNS—hosted zones, records, health checks, and routing policies (latency, failover, weighted). DNS TTL affects cutover speed. Often pairs with ALB/CloudFront aliases. DNS mistakes take sites down globally—treat changes carefully.
Q41beginnerWhat is ACM?
AWS Certificate Manager issues and renews TLS certificates for AWS-integrated services like ALB and CloudFront—often free public certs. Automates renewal pain. Validate domains via DNS/email. Prefer ACM over manually copying private keys around.
Q42beginnerIAM roles vs users—when prefer roles?
Prefer roles for applications and human SSO sessions—temporary credentials reduce leak impact. Users with long-lived access keys are discouraged for workloads. Instance profiles and Lambda execution roles are standard. Least privilege policies still apply.
Q43beginnerWhat is ECR?
Elastic Container Registry stores Docker images in AWS with IAM controls and vulnerability scanning options. CI pushes images; ECS/EKS pulls them. Tag immutably (git SHA) rather than only `latest`. Private registries are part of supply-chain hygiene.
Q44intermediateContainers vs VMs—orchestration angle?
VMs virtualize hardware with separate kernels; containers share a kernel and package apps lightly. Orchestrators (Kubernetes) schedule containers, restart failures, and scale services. VMs still useful for strong isolation or custom kernels. Many stacks run containers on VMs underneath.
Q45advancedWhat is GitOps briefly?
Desired cluster state lives in git; controllers sync the cluster to match (Argo CD, Flux). Changes go through PRs with audit history. Improves consistency and rollback via git revert. Requires discipline around secrets and progressive delivery.
Q46intermediateFeature flags in DevOps context?
Flags decouple deploy from release—ship dark code and enable gradually. Supports canaries and kill switches. Manage flag debt; remove stale flags. Server-side evaluation needed for security-sensitive features.
Q47advancedSLI vs SLO vs SLA vs error budget?
SLI is a measured indicator (availability, latency). SLO is the target for that SLI. SLA is the contractual promise, often with penalties. Error budget is allowed unreliability before freezing risky changes—SRE core idea. Shows reliability engineering literacy.
Q48beginnerWhat is shared responsibility in the cloud?
Cloud provider secures the cloud (hardware, facilities, foundational services); you secure in the cloud (data, IAM, OS on EC2, app config). Misunderstanding this causes security gaps. Model differs for SaaS vs IaaS. Always clarify who patches what.
Q49intermediateExplain infrastructure observability three pillars.
Metrics (numeric time series), logs (event details), and traces (request journeys across services). Together they diagnose latency and failures in distributed systems. OpenTelemetry is a common instrumentation standard. Without observability, cloud scale becomes guesswork.
Q50beginnerWhat is an AMI?
Amazon Machine Image is a template for EC2 instances—OS and often preinstalled software. Golden AMIs bake hardening and agents. Prefer immutable infra: new AMIs rather than SSH snowflake changes. Combine with configuration management carefully.
Q51intermediateECS vs EKS awareness?
ECS is AWS-native container orchestration; EKS is managed Kubernetes. ECS is simpler if you are all-in on AWS APIs; EKS offers Kubernetes portability and ecosystem. Choose based on team skills and lock-in tolerance. Both need IAM, networking, and observability design.
Q52intermediateWhat is Infrastructure drift?
Manual console changes make reality diverge from IaC state, causing surprise outages and insecure configs. Detect with Terraform drift tools and deny manual prod changes via policy. Reconcile by importing or reverting. Drift is why click-ops fails at scale.
Q53intermediateHow do you design for multi-AZ high availability?
Run load-balanced instances across Availability Zones; use Multi-AZ RDS; replicate critical data. Survive single-AZ failure without hard downtime. Balance cost vs redundancy. Test failover—untested HA is fiction.
Q54advancedWhat is a security group vs NACL?
Security groups are stateful virtual firewalls on ENIs (instance/task level); NACLs are stateless subnet-level filters. Most app control uses security groups; NACLs for coarse subnet rules. Default-deny with explicit allows is safest. Confused layering causes outages and holes.
Q55beginnerExplain rolling updates.
Gradually replace instances/Pods with new versions while keeping service available. Kubernetes Deployments do this with maxUnavailable/maxSurge. Monitor error rates during rollout. Faster than blue-green on capacity, slightly more risk mid-rollout.
Q56intermediateWhat is immutable infrastructure?
Rather than patching live servers, you bake new images/artifacts and replace instances. Improves consistency and rollback. Pairs with cattle-not-pets mindset. Requires automation and good config externalization.
Q57intermediateHow do health checks interact with autoscaling?
Unhealthy instances are removed from load balancers and replaced by ASGs/K8s controllers. Bad health checks cause flapping. Define what 'healthy' means for your app carefully (dependencies vs process up). Tie alarms to customer-facing SLIs too.
Q58intermediateWhat is a canary metric you would watch?
Error rate (5xx), latency p95/p99, saturation (CPU/memory), and key business KPIs (checkout success). Compare canary vs baseline. Automated rollback if thresholds breach. Vanity metrics waste the canary.
Q59advancedExplain DNS TTL tradeoffs in cutovers.
Low TTL allows faster failover but increases DNS query load; high TTL caches longer and slows changes. Lower TTL before planned migrations, then raise after. Clients with sticky caches still lag. Coordinate with load balancer cutovers.
Q60beginnerWhat is infrastructure tagging strategy?
Tag resources with owner, env, service, cost-center for billing and automation. Enforce required tags via policies. Untagged resources become zombie spend. Simple practice, high operational payoff.
Q61advancedHow do you run database migrations in CI/CD safely?
Prefer backward-compatible migrations, expand/contract patterns, and migrate before app code that depends on new schema—or carefully ordered pipelines. Avoid long locks in prod. Have a rollback or forward-fix plan. Test migrations on production-like data volumes.
Q62advancedWhat is chaos engineering awareness?
Deliberately inject failures (kill Pods, add latency) to verify resilience assumptions. Start in non-prod with clear blast radius. Complements monitoring and runbooks. Netflix popularized; SRE teams adopt carefully.
Q63intermediateExplain container resource requests and limits.
Requests guide scheduling guarantees; limits cap usage to protect neighbors. Setting them wrong causes throttling or OOMKills. Right-sizing needs metrics. Critical for noisy-neighbor control on Kubernetes.
Q64intermediateWhat is a sidecar pattern?
A helper container alongside the app container in a Pod—proxy, log shipper, or secrets agent. Shares network namespace. Used heavily in service meshes. Keep sidecars lean to avoid resource bloat.
Q65advancedService mesh awareness (Istio/Linkerd)?
A mesh adds mTLS, retries, traffic shaping, and telemetry via proxies without changing app code much. Adds operational complexity and latency. Adopt when many services need uniform policy. Overkill for small systems.
Q66intermediateHow do you secure SSH access to cloud VMs?
Prefer SSM Session Manager or bastion with MFA over open port 22 to the world. Use short-lived certificates or IAM-based access. Disable password auth; patch OS. Record sessions for audit when required.
Q67intermediateWhat is spot/preemptible capacity?
Discounted instances that can be reclaimed with short notice. Great for fault-tolerant batch/CI; risky for single-node stateful prod without design. Use diversified pools and interruption handling. Cost awareness signal in interviews.
Q68beginnerExplain backup vs disaster recovery briefly.
Backups copy data; DR is the plan/process to restore service including RTO/RPO targets. Test restores regularly—untested backups fail when needed. Multi-region DR is expensive; match to business criticality. Document runbooks.
Q69intermediateRTO vs RPO?
RTO is how fast you restore service after disaster; RPO is how much data loss (time) is acceptable. They drive backup frequency and HA architecture. Product owners set targets; engineering designs to meet them. Clarify both in design interviews.
Q70advancedWhat is infrastructure policy as code?
Tools like OPA/Conftest or cloud SCPs enforce rules—no public S3, required tags, approved instance types. Prevents insecure resources before deploy. Complements IaC reviews. Shows enterprise cloud maturity.
Q71advancedHow do you structure cloud accounts?
Separate prod/non-prod and sometimes data/logging accounts via AWS Organizations. Limits blast radius and clarifies billing. Centralize security tooling accounts. Landing zone patterns encode this.
Q72intermediateWhat is an AMI pipeline / golden image?
Automated builds produce hardened base images with patches and agents, scanned and versioned. Instances launch from known-good AMIs. Reduces configuration drift. Pair with frequent rebuilds for patching.
Q73advancedExplain egress control importance.
Unrestricted outbound traffic enables data exfiltration and SSRF impact. Use NAT, proxy allowlists, and VPC endpoints for AWS APIs. Least privilege applies to network egress too. Often neglected until an incident.
Q74beginnerWhat is CloudFormation vs Terraform?
CloudFormation is AWS-native IaC; Terraform is multi-cloud with a large provider ecosystem. Both declarative with state/planning concepts (CFN manages state for you). Team skills and multi-cloud needs drive choice. Focus on IaC principles over brand.
Q75intermediateHow do you handle secrets in GitHub Actions?
Store in GitHub Secrets or OIDC-federated cloud roles; mask outputs; restrict which workflows can access environments. Never echo secrets. Prefer short-lived credentials. Review fork PR trust models carefully.
Q76intermediateWhat is progressive delivery?
Umbrella term for canaries, feature flags, and gradual rollouts guided by metrics. Reduces risk of continuous deployment. Requires automated analysis, not only gut feel. Modern CD beyond 'deploy all at once.'
Q77intermediateExplain sticky sessions and when to avoid them.
Load balancers pin a client to one instance—useful for legacy in-memory sessions. Avoid by storing sessions in Redis/DB so any instance works. Stickiness reduces resilience and uneven load. Prefer stateless app tiers.
Q78advancedWhat is an origin shield / cache hierarchy?
CDN features that reduce load on origin by collapsing requests through intermediate caches. Helps during traffic spikes. Tune with TTLs and cache keys. Performance topic adjacent to CloudFront.
Q79beginnerHow do you debug 'works on my machine' in containers?
Match base image, env vars, and architecture (ARM vs AMD); check volume mounts and network; reproduce with the same image tag in CI. Immutable images shrink the gap. Logging and health endpoints accelerate diagnosis.
Q80intermediateWhat is capacity planning awareness?
Estimate load, headroom, and scaling triggers using historical metrics and load tests. Cloud elasticity helps but quotas and warm pools matter. Plan for launches and seasonal peaks. Under-planning causes outages; over-planning wastes money.
Q81beginnerExplain ephemeral vs persistent compute.
Ephemeral instances/tasks are disposable and replaceable; persistent machines hold unique state. Cloud-native favors ephemeral compute + durable managed storage. Pets vs cattle metaphor applies. Design for termination anytime.
Q82intermediateWhat metrics indicate saturation?
CPU throttling, memory near limits, disk IOPS/latency, queue depth, and thread pool exhaustion. Saturation precedes latency spikes. Golden signals include latency, traffic, errors, saturation. Watch queues for async systems.
Q83beginnerHow does CDN HTTPS work with certificates?
CDN terminates TLS at the edge using managed certs; connection to origin may re-encrypt. Configure modern TLS policies. Certificate automation (ACM) removes manual renewals. Misconfigured origin HTTPS breaks fetches.
Q84advancedWhat is warm pool / provisioned concurrency idea?
Keep pre-initialized capacity to reduce cold starts (Lambda provisioned concurrency, ASG warm pools). Trades cost for latency predictability. Use for latency-sensitive serverless. Measure before paying.
Q85beginnerExplain artifact versioning best practice.
Tag images/packages with git SHA or semver; avoid mutable `latest` in prod. Promote the same artifact across envs. Enables exact rollbacks and provenance. Core to trustworthy CD.
Q86beginnerWhat is a runbook?
A documented procedure for operating/incident response—restart steps, dashboards, escalation contacts. Living docs tested during drills. Reduces MTTR and bus factor. SRE culture staple.
Q87advancedHow do you prevent noisy neighbor issues?
Set resource limits, isolate critical tenants, use dedicated nodes/instances when needed, and monitor per-tenant usage. Shared clouds amplify contention. Quality of service policies help. Design multi-tenant systems with isolation in mind.
Q88intermediateWhat is continuous deployment vs continuous delivery?
Continuous delivery keeps main always releasable with manual prod approval often; continuous deployment automatically releases every green build to prod. Both need strong tests and observability. Choose based on risk tolerance and domain.
Q89advancedExplain why health check endpoints should be lightweight.
Heavy dependency checks on every probe can overload DBs and cause cascading failures. Split shallow liveness from deeper readiness/startup probes. Cache dependency status briefly if needed. Thoughtful probes stabilize orchestration.
Q90intermediateWhat is AWS well-architected lens awareness?
AWS Well-Architected Framework covers operational excellence, security, reliability, performance efficiency, cost optimization, and sustainability. Useful checklist vocabulary in architecture reviews. Shows structured thinking. Not AWS-only ideas—portable principles.
Q91advancedHow do you approach zero-downtime deploys with schema changes?
Use expand/contract: add new columns/tables compatible with old code, deploy app, then remove old fields later. Avoid destructive migrations in the same release as breaking code. Feature flags help dual-write periods. Practice on staging with prod-like data.
Q92intermediateWhat is edge computing awareness?
Running logic closer to users (CloudFront Functions, Cloudflare Workers) cuts latency for simple tasks. Constraints on runtime/CPU apply. Good for auth redirects, A/B, and header rewrites. Keep heavy business logic centralized.
Q93intermediateExplain container image scanning in the pipeline.
Scan images for CVEs before promoting to prod registries; fail builds on critical issues. Combine with base-image updates. Scanning is necessary but not sufficient—runtime policies matter. Part of supply-chain security.
Q94intermediateWhat is idempotent deployment?
Running the deploy repeatedly yields the same end state without harmful side effects. IaC applies and Kubernetes reconciler loops embody this. Non-idempotent scripts cause snowflake failures. Design installers and migrations with idempotency in mind.
Q95advancedHow do you separate build and runtime IAM permissions?
CI roles can push artifacts; runtime roles only read what the app needs—no deploy permissions in the app role. Limits blast radius if the app is compromised. OIDC federation helps. Classic least-privilege design.
Q96beginnerGive a crisp 'why containers' interview answer.
Containers package apps with dependencies for consistent deploys, faster startups than many VMs, and denser packing. Orchestrators add healing and scaling. They do not magically secure apps—you still harden images and IAM. Ideal for microservices and CI artifacts.
Q97beginnerWhat operational metric is MTTR?
Mean Time To Recovery measures how quickly you restore service after incidents. Improve with detection, runbooks, rollbacks, and practice. Pair with change failure rate in DORA metrics. Reliability is as much process as technology.
Q98advancedExplain DORA metrics briefly.
Deployment frequency, lead time for changes, change failure rate, and time to restore service. Elite teams ship often with low failure and fast recovery. Use as directional health, not vanity targets. Popular in DevOps interviews.
Q99intermediateWhat is a load balancer health check grace period for?
New instances may need time to warm caches or establish connections before receiving traffic. Grace/deregistration delays prevent premature kill or connection draining issues. Tune based on real startup times. Mis-tuned grace causes flapping or dropped requests during deploys.
Q100beginnerHow do you explain infrastructure 'cattle not pets'?
Treat servers as replaceable cattle numbered and rebuilt, not unique pets with loving hand care. Enables autoscaling and immutable deploys. Store state outside instances. Core cultural shift for cloud operations success.
System Design
110 questions
Q1beginnerDesign a URL shortener — clarify requirements first?
Ask: read/write QPS, URL length, custom aliases, expiry, analytics, auth, abuse. Estimate 100M new URLs/month → ~40 writes/sec average with peaks. Reads dominate (100:1). Need unique short codes, redirect 302/301, and durable storage. Start single region then scale.
Q2intermediateURL shortener: how do you generate short codes?
Base62 encode a unique counter (Redis INCR / DB sequence) or hash+truncate with collision retry. Counter is simple and collision-free; hash needs uniqueness checks. Avoid predictable sequential IDs if enumeration is a concern—add salted hash or permission checks for private links.
Q3intermediateURL shortener: data model essentials?
Table/collection: short_code (PK), long_url, created_at, expire_at, owner_id, click_count. Secondary index on owner. Cache hot short_code→url in Redis with TTL. Redirect path must be ultra-fast: cache → DB → 404.
Q4intermediateURL shortener: 301 vs 302 redirects?
301 permanent can be cached aggressively by browsers/CDNs—bad if you need to change destination or track every click. 302/307 keep hitting your servers for analytics control. Choose based on analytics vs cache efficiency.
Q5advancedURL shortener: scale reads?
CDN/edge cache for redirects if destinations stable, Redis for hot keys, read replicas. Shard by short_code hash when data grows. Rate-limit scrapers. Partition analytics writes asynchronously via queue so redirect path stays lean.
Q6beginnerDesign chat (WhatsApp lite) — core features?
1:1 messaging, delivery states (sent/delivered/read), online presence, media later, push notifications. Non-functional: low latency, ordering per conversation, durability, multi-device sync. Clarify group chat scope for v1.
Q7intermediateChat: how do messages flow?
Client → websocket gateway → chat service → persist message → push to recipient connections (and push notification if offline). Fanout for groups. Use conversation_id + monotonic message_id/timestamp for ordering.
Q8intermediateChat: WebSocket vs long polling?
WebSockets: full-duplex low latency for online users. Long polling: simpler fallback through proxies. Many systems support both. Sticky sessions or shared pub/sub (Redis) so any gateway can notify the right connection.
Q9advancedChat: offline delivery and sync?
Store undelivered messages; on reconnect, client syncs since last cursor. Multi-device: each device has its own cursor or server maintains per-device ack. Idempotent message IDs prevent duplicates.
Q10advancedChat: read receipts at scale?
Update receipt state asynchronously; don't block send path. Collapse receipts (last read watermark per conversation) instead of per-message DB writes when possible. Eventual consistency acceptable for receipts.
Q11advancedDesign news feed — fanout on write vs read?
Fanout-on-write: precompute timeline lists for followers (fast read, heavy write for celebrities). Fanout-on-read: pull recent posts from followees at read time (cheap write, heavier read). Hybrid: fanout normal users; pull for celebrities (Twitter-style).
Q12intermediateNews feed ranking signals?
Recency, affinity, engagement probability, content type, diversity. Offline ML scoring + real-time features. Cache ranked home timeline per user with incremental updates.
Q13intermediateNews feed storage sketch?
Posts service (post_id, author, content, media refs); graph service (follow edges); timeline cache (Redis lists/ZSETs of post_ids per user). Object store for media. CDN for media delivery.
Q14intermediateDesign a rate limiter — algorithms?
Token bucket (burst + steady rate), leaky bucket, fixed window (simple, burst at edges), sliding window log/counter. Distributed: Redis INCR + TTL or Lua for atomicity. Return 429 + Retry-After.
Q15advancedRate limiter placement?
API gateway/edge for global IP limits; service layer for per-user/per-API-key business quotas. Different limits for auth vs expensive endpoints. Fail-open vs fail-closed policy when Redis down—product decision.
Q16intermediateRate limiter: Redis key design?
`rl:{user}:{route}:{window}` counters with EXPIRE. For token bucket store tokens+timestamp. Use MULTI/Lua to avoid races. Shard Redis if QPS extreme.
Q17beginnerDesign a caching layer — strategies?
Cache-aside (app loads on miss), read-through, write-through, write-back. TTL + explicit invalidation on writes. Prevent stampede with single-flight/locks. Choose Redis/Memcached; consider eviction LRU.
Q18intermediateCache consistency patterns?
Invalidate on write; version keys; short TTL soft consistency. For strong needs, skip cache or use transactional outbox to invalidate. Never assume cache equals source of truth.
Q19advancedHot key and large value problems?
Hot keys: local cache + split keys + replicas. Large values: compress, store elsewhere, cache pointers. Monitor hit ratio and eviction causes.
Q20beginnerHow does a CDN help a full-stack app?
Edge caches static assets (JS/CSS/images) near users; TLS termination; DDoS absorption; sometimes edge compute. Configure cache-control, hashed filenames, purge on release. Origin shield reduces origin storms.
Q21advancedCDN for dynamic HTML?
Possible with short TTL/stale-while-revalidate or edge SSR. Personalized pages often `private, no-store`. Signed cookies/URLs for private content.
Q22beginnerDesign an auth service — responsibilities?
Register/login, credential hashing (argon2/bcrypt), session/JWT issuance, refresh rotation, MFA, password reset, OAuth social login, audit logs. Separate from product APIs. Rate-limit auth endpoints.
Q23intermediateJWT vs server sessions?
JWT: stateless, scalable, harder revoke (use short TTL + blocklist/version). Sessions: server store, easy revoke, sticky affinity or shared Redis. Prefer httpOnly cookies for browsers; bearer for mobile carefully.
Q24advancedOAuth2 authorization code + PKCE why?
Safe for public clients (SPAs/mobile): no client secret, code interceptor mitigated by PKCE. Prefer over implicit flow (deprecated).
Q25advancedSSO with OIDC briefly?
OIDC adds id_token identity layer on OAuth2. Enterprise SSO via SAML/OIDC with IdP. Auth service validates tokens/JWKS.
Q26intermediateDesign file upload at scale?
Client requests upload permission → server returns signed URL to object storage → client PUTs directly → webhook/callback confirms → virus scan + thumbnail workers. Store metadata in DB. Limit size/MIME; multipart for large files.
Q27advancedFile upload security concerns?
Validate types by sniffing not extension alone; separate bucket; no executable serving from user bucket; signed short-lived URLs; malware scanning; per-user quotas; CSRF protection on credentialed APIs.
Q28intermediateDesign a notification system?
Ingest events → preference service (channels/quiet hours) → template render → providers (email/SMS/push) via workers with retries. Deduplicate by event_id. Priority queues for OTP vs marketing.
Q29beginnerPush notification delivery path?
Store device tokens; send via FCM/APNs; handle invalid token cleanup; collapse keys for noisy updates. Prefer async queue from product services.
Q30advancedDesign search autocomplete?
Prefix search via trie/Redis ZSET per prefix, or search engine edge n-grams (Elasticsearch/OpenSearch). Rank by popularity + personalization. Cache top prefixes at CDN/edge. Debounce client requests; limit suggestions.
Q31advancedAutocomplete under heavy QPS?
Aggressive caching of popular prefixes, read replicas, precompute top queries, rate-limit per IP. Avoid hitting primary DB on each keystroke.
Q32beginnerDesign Twitter lite — core entities?
Users, tweets, follows, timelines, likes/retweets. APIs: post tweet, follow, get home timeline, get user timeline. Media via object storage. Rate limits for posting.
Q33advancedTwitter lite celebrity problem?
Hybrid timeline fanout; don't fanout to millions of followers on write—pull celebrity posts at read time and merge. Cache aggressively.
Q34intermediateDesign Instagram lite — feed & media?
Photo upload pipeline (compress variants), feed ranking similar to news feed, stories with TTL, CDN for images. Metadata DB + blob storage separation essential.
Q35advancedWhatsApp lite group chat fanout?
For small groups, write message once and push to online members; store in group history. Large groups: similar optimizations as celebrity (don't block on all ACKs). Encrypt at rest; e2e is advanced scope—mention awareness.
Q36beginnerAPI gateway responsibilities in system design?
Routing, authn, rate limit, TLS, request logging/tracing, WAF, API versioning, sometimes aggregation/BFF. Keep business logic in services. Avoid god-gateway bloating.
Q37intermediateBFF pattern?
Backend-for-Frontend: per-client (web/mobile) aggregation layer tailored responses—reduces chatty mobile calls. Don't duplicate domain rules everywhere—call domain services.
Q38intermediateDesign observability for microservices?
Structured logs with request_id, metrics (RED/USE), distributed traces (OpenTelemetry), dashboards + alerts on SLOs. Central store (ELK/Prom/Grafana/Tempo). Sample traces under load.
Q39beginnerGolden signals?
Latency, traffic, errors, saturation (Google SRE). Alert on user pain not just CPU. Error budgets guide release velocity.
Q40beginnerCapacity estimation: steps?
Clarify DAU/QPS, read/write ratio, payload size, retention. Compute storage = objects × size × replicas × growth. Bandwidth = QPS × size. Round to orders of magnitude; state assumptions aloud.
Q41intermediateExample: estimate storage for 10M users photos?
Assume 20% upload 5 photos/day × 200KB avg ≈ 2M photos/day × 200KB ≈ 400GB/day raw; × versions/replicas CDN origin policy. Show the multiplication clearly; refine assumptions with interviewer.
Q42beginnerEstimate QPS from DAU?
DAU × actions/day / 86400 for average; multiply by peak factor 2–5×. Example: 10M DAU × 20 actions / 86400 ≈ 2300 RPS avg.
Q43beginnerWhen SQL vs NoSQL in design interviews?
SQL: relational integrity, complex queries, transactions (payments, inventory). NoSQL: massive scale simple access patterns, flexible docs, high write throughput (feeds, sessions). Many systems polyglot—use both.
Q44intermediateScenario: shopping cart — SQL or Redis?
Often Redis for ephemeral hot carts + SQL/NoSQL for durable orders. Checkout transaction in SQL. Don't store payments only in cache.
Q45advancedScenario: social graph — storage?
Follow edges in graph DB or sharded SQL/NoSQL (follower_id, followee_id) with indexes both directions. Cache follower counts. Avoid unbounded unbounded arrays in single documents for celebrities.
Q46beginnerHorizontal scaling checklist for a web app?
Stateless app servers, external session store, DB replicas, connection pooling, cache, CDN, queue for async, autoscaling, health checks, idempotent workers, observe bottlenecks before sharding.
Q47advancedWhen to shard a database?
When single primary can't handle data size or write QPS after indexing/caching/replicas. Sharding adds operational pain—postpone until needed. Choose shard key carefully (avoid hotspots).
Q48beginnerVertical vs horizontal scaling?
Vertical: bigger machine—simple limits. Horizontal: more nodes—needs statelessness and distributed data design. Prefer horizontal for cloud elasticity.
Q49beginnerDesign a pastebin?
Similar to URL shortener + larger text blob (object storage or DB text with size limit), optional expiry, syntax highlight client-side, rate limits, spam detection.
Q50advancedDesign a web crawler — basics?
URL frontier queue, politeness per domain, fetcher workers, content store, seen-URL Bloom/DB, robots.txt respect. Distributed frontier with priorities. Dedupe canonical URLs.
Q51advancedDesign typeahead trending topics?
Stream clicks/posts into counters (Kafka→Flink/Spark), maintain top-K per window in Redis ZSET, expire windows, serve cached lists. Anti-abuse filtering.
Q52advancedDesign ticket booking (movie seats)?
Seat inventory with strong consistency: `SELECT FOR UPDATE` or atomic hold with TTL, payment, confirm. Prevent double booking via unique seat-show constraints. Cache seat maps carefully with invalidation.
Q53advancedDesign ride-hailing matching lite?
Drivers publish geo location (Redis geo); riders request; matcher finds nearby drivers, offers with timeout; trip state machine. Separate services: location, matching, trips, payments.
Q54advancedDesign collaborative document editing awareness?
OT or CRDT for concurrent edits, websocket sync, persistent snapshots, presence. Hard problem—scope carefully in interviews; mention conflict-free approaches.
Q55advancedDesign metrics/analytics ingestion?
Client events → gateway → Kafka → stream processors → OLAP (ClickHouse/BigQuery) + real-time counters. Batch vs stream; schema registry; sampling.
Q56intermediateDesign email OTP login?
Generate OTP, store hashed with expiry/attempt counters in Redis, send via notification service, verify atomically, issue session. Rate-limit by IP/email to stop bombing.
Q57intermediateDesign feature flag service?
Store flags/rules; SDKs poll or stream updates; percentage rollouts; targeting by user attributes; audit changes. Cache aggressively locally in each service.
Q58advancedDesign multi-tenant SaaS data isolation?
Tenant_id on every row (pooled), schema-per-tenant, or DB-per-tenant for strong isolation. Encrypt, rate-limit per tenant, careful backup restores. Index tenant_id leading.
Q59intermediateDesign search for e-commerce?
Index products in Elasticsearch with facets; async index updates from catalog CDC; autocomplete separate; relevance tuning; CDN for assets; SQL source of truth for inventory.
Q60intermediateDesign leaderboard?
Redis ZSET score→user for top-K fast; periodic snapshot to DB; shard by game/season; handle ties; anti-cheat validation server-side.
Q61advancedDesign distributed job scheduler?
DB/queue of jobs with run_at; workers claim with locking (FOR UPDATE SKIP LOCKED / Redis); retries/backoff; at-least-once + idempotent handlers; avoid single cron server SPOF.
Q62beginnerDesign image thumbnail service?
Upload event → queue → workers (sharp) generate sizes → store variants → update metadata. Idempotent on asset_id+size. Dead-letter failures.
Q63advancedDesign API for mobile offline sync?
Client change log with versions; server accepts batches with conflict policy (LWW/CRDT); return server cursor. Prefer incremental sync endpoints.
Q64advancedDesign payment checkout orchestration?
Create order intent, call PSP, webhook confirms, mark paid idempotently, fulfill via queue. Never trust client 'paid' flag. Strong audit trail.
Q65intermediateSQL vs NoSQL for order management?
Prefer SQL for ACID inventory/orders/payments consistency. Cache product catalog reads. Outbox for events after commit.
Q66intermediateDesign logging pipeline?
App → agent → Kafka → processing → cold storage (S3) + searchable (OpenSearch). Retention tiers; PII scrubbing; sampling high-volume debug.
Q67beginnerDesign session store?
Redis with TTL for sessions; sticky optional; rotate session IDs on login; store minimal data; regenerate on privilege change.
Q68intermediateDesign content moderation workflow?
User report → queue → automated classifiers → human review tool → actions (hide/ban) with audit. Appeals flow. Separate hot path from review path.
Q69advancedHandle flash sales inventory?
Precompute stock; atomic decrements (Redis+DB reconciliation); queue purchasers; fairness rate limits; cache product pages at CDN with careful inventory API freshness.
Q70advancedDesign multi-region active-passive?
Primary takes writes; async replicate; health DNS failover; accept RPO data loss window. Test failover drills. Sticky sessions complications.
Q71advancedDesign GraphQL at scale concerns?
Persisted queries, depth/cost limits, DataLoader batching, authz per field, caching carefully (POST). Gateway timeout budgets.
Q72intermediateDesign webhook delivery platform?
Store subscriptions; on event enqueue deliveries; sign payloads; exponential retries; disable poisoned endpoints; observability per destination.
Q73intermediateBack-of-envelope: bandwidth for video streaming?
Concurrent viewers × bitrate. 100k viewers × 5Mbps ≈ 500Gbps—needs CDN, not origin streaming. Show units carefully.
Q74advancedDesign ID generation (Snowflake)?
Time-ordered 64-bit IDs: timestamp | worker | sequence—avoid DB sequences bottleneck. Clock skew handling; alternative UUIDv7.
Q75advancedConsistent hashing for cache cluster?
Map keys to cache nodes on ring; virtual nodes; on node add/remove remap fraction. Client libraries or proxy (mcrouter).
Q76advancedDesign AB testing platform lite?
Experiment configs; deterministic user hashing into buckets; exposure logging; metric analysis pipeline. Avoid imbalance and peeking pitfalls.
Q77beginnerHow do you approach any system design interview?
Clarify requirements → estimate scale → high-level diagram → deep dive bottlenecks (DB, cache, queues) → failures/consistency → summarize tradeoffs. Drive the conversation; state assumptions.
Q78beginnerSingle points of failure checklist?
Single primary DB, single Redis, single AZ, single DNS, sticky sessions without drain. Mitigate: replicas, multi-AZ, health checks, graceful degradation.
Q79intermediateMessage ordering guarantees?
Per-partition key ordering in Kafka; global order expensive. Pick partition key (conversation_id) for chat. Consumers must be idempotent.
Q80intermediateDesign CDN cache purge strategy?
Hashed asset URLs (immutable cache forever); purge only HTML/config. Soft purge / surrogate keys for related objects.
Q81intermediateDesign rate-limited login + CAPTCHA?
Progressive delays, IP/email limits, device fingerprinting, CAPTCHA after threshold, anomaly detection. Balance UX vs bots.
Q82beginnerObject storage vs DB for large blobs?
Never store large media in OLTP DB—use S3/GCS with metadata in DB. Backups and replication differ.
Q83intermediateDesign presence system (online status)?
Heartbeat via websocket; Redis TTL keys per user; privacy settings; last-seen eventual. Don't write DB every heartbeat—aggregate.
Q84advancedFan-out push for notifications storm?
Queue per user shards; rate-limit sends; collapse updates; priority lanes; backpressure when providers throttle.
Q85beginnerDesign audit trail?
Append-only event log with actor, action, before/after, timestamp; immutable storage; query indexes. Required for compliance domains.
Q86advancedCQRS applied to feeds?
Writes to post service; async projections update read-optimized timelines. Lag acceptable if UX shows pending state.
Q87intermediateHow to migrate traffic with canary?
Deploy v2 to 1% → watch error/latency → ramp → full. Automatic rollback on SLO burn. Sticky canary by user-id hash.
Q88intermediateDesign secrets management?
Vault/KMS/cloud secret manager; short-lived credentials; no secrets in images/env logs; rotate; audit access.
Q89beginnerGraceful degradation for homepage?
If personalization fails, show cached popular content; if ads fail, omit; if search fails, browse categories. Prioritize core read path.
Q90advancedDesign CORS and cookie auth across APIs?
First-party cookies with SameSite; CSRF tokens for state-changing; careful subdomain cookie scopes. Prefer BFF same-origin when possible.
Q91advancedEstimate connections for chat gateways?
Concurrent online × 1 connection; each gateway holds N (100k order depending on HW). Horizontal shard users via consistent hash/pub-sub. Memory per connection matters.
Q92advancedDesign search index update pipeline?
CDC from DB (Debezium) → Kafka → indexer workers → search cluster. Eventual consistency; versioning documents; dead-letter poison messages.
Q93beginnerSLA vs SLO vs SLI?
SLI measured indicator (latency p99); SLO target; SLA contractual consequences. Design monitoring around SLOs.
Q94advancedDesign multi-step saga for order+inventory+payment?
Orchestrator: reserve inventory → charge payment → confirm; compensations: release stock / refund on failures. Idempotent steps; timeouts.
Q95beginnerWhy queues between API and workers?
Absorb spikes, retries, isolation of slow IO, prioritization. API returns 202 + job id for long tasks. Observability on queue depth.
Q96advancedDesign geo-distributed reads?
Read replicas in regions; CDN; edge caches. Writes to primary or regional with CRDTs—product decides conflict rules.
Q97intermediateSecurity threat modeling basics (STRIDE awareness)?
Spoofing, Tampering, Repudiation, Info disclosure, DoS, Elevation. Apply to each design: authn, integrity, audit, encryption, rate limits, least privilege.
Q98beginnerDesign pagination for feed APIs?
Cursor-based (timestamp+id) over offset for large feeds; stable under inserts. Return next_cursor opaque token.
Q99advancedAvoid thundering herd on cache expiry?
Soft TTL with background refresh; probabilistic early expire; request coalescing; staggered TTLs.
Q100intermediateDesign admin analytics dashboard?
Don't query OLTP; use warehouse aggregates refreshed periodically; precompute KPIs; cache dashboards; RBAC for access.
Q101intermediateMobile push vs websocket for notifications?
Websocket when app open; OS push when backgrounded. Unified notification service decides channel based on presence + preferences.
Q102beginnerDesign short-lived previews for docs (paste expiry)?
TTL fields + async sweeper / Redis TTL; signed links; optional one-time read. Legal retention exceptions.
Q103intermediateCapacity: DB connections estimate?
App instances × pool size must stay under DB max_connections. Use PgBouncer. Common production outage cause.
Q104intermediateDesign idempotent POST /orders?
Require Idempotency-Key; store key→response; unique constraints on business keys; clients retry safely.
Q105advancedBlue-green for stateful systems?
Harder than stateless: ensure DB migrations compatible both versions; expand/contract. Switch traffic only when schemas dual-compatible.
Q106advancedDesign media streaming lite?
Chunk/transcode to HLS/DASH, store segments on object storage, CDN delivery, auth tokens for URLs, adaptive bitrate.
Q107beginnerWhat to put on the whiteboard first?
Clients → load balancer → app servers → DB/cache; then add queue/CDN as needed. Narrate data flow for primary use case before secondary features.
Q108intermediateDesign spam detection for messaging?
Rate limits, content classifiers, reputation scores, graph signals, quarantine queues, human review. Feedback loop from user reports.
Q109intermediateDesign health checks vs readiness?
Liveness: process up; readiness: can serve (DB pool ok). K8s uses both so traffic only hits ready pods. Avoid dependencies in liveness that cause restart storms.
Q110advancedEnd-to-end: URL shortener redirect path optimized?
Edge/PoP cache → Redis → DB; async click event to Kafka; 302; connection keepalive; metric latency histograms. Aim sub-10ms in-region cache hits.
AI / ML / GenAI
124 questions
Q1beginnerAI vs ML vs DL vs GenAI?
AI is the broad field of machines performing tasks that seem intelligent. ML is a subset where systems learn patterns from data instead of only hand-coded rules. Deep learning uses multi-layer neural nets for complex patterns (vision, speech, NLP). Generative AI creates new content (text, images, code) via models like LLMs and diffusion. In interviews, give a crisp hierarchy and one example each.
Q2beginnerSupervised vs unsupervised vs reinforcement learning?
Supervised learning trains on labeled examples (email → spam/ham). Unsupervised finds structure without labels (clustering customers). Reinforcement learning learns by rewards/penalties from actions (game playing, robotics). Most business prediction tasks are supervised; clustering/segmentation often unsupervised. RL is rarer in typical CRUD product features.
Q3beginnerTrain, validation, and test sets?
Train fits parameters; validation tunes hyperparameters and catches overfitting during development; test is a final holdout for unbiased performance. Never peek at test to make modeling decisions. Time-series needs time-aware splits. Common mistake: leaking test information through preprocessing fit on all data.
Q4intermediateOverfitting vs underfitting?
Overfitting: model memorizes training noise—high train accuracy, poor generalization. Underfitting: model too simple—poor on train and test. Fix overfit with more data, regularization, dropout, simpler models, early stopping. Fix underfit with richer features/models and longer training. Bias-variance framing helps explain the tradeoff.
Q5intermediateBias vs variance?
High bias: systematic errors from overly simple models (underfit). High variance: sensitive to training sample fluctuations (overfit). Total error balances both. Ensemble methods often reduce variance. Interviewers like this vocabulary when discussing model selection.
Q6beginnerClassification vs regression?
Classification predicts discrete classes (fraud/not). Regression predicts continuous values (price, demand). Metrics differ: accuracy/F1 vs MAE/RMSE. Logistic regression is classification despite the name. Choose loss and metrics matching the problem.
Q7beginnerWhat are features and labels?
Features (X) are input variables the model uses; labels (y) are the targets to predict in supervised learning. Feature engineering transforms raw data into useful signals. Garbage features dominate model quality more than algorithm choice in many business problems. Leakage features accidentally include future info—dangerous.
Q8beginnerLinear regression in one minute?
Predicts a continuous target as a weighted sum of features plus bias. Trained by minimizing squared error. Interpretable coefficients. Assumes roughly linear relationships. Baseline model before complex ML—strong interview signal when you start simple.
Q9beginnerLogistic regression?
Predicts class probability via a linear model passed through a sigmoid. Used for binary classification; softmax extends to multiclass. Despite the name, it is classification. Regularized logistic regression remains a strong baseline for tabular data.
Q10intermediateDecision trees and random forests?
Trees split features to separate targets—interpretable but overfit easily. Random forests average many trees on bootstrap samples/feature subsets—strong tabular baseline with less tuning. They handle nonlinearities and mixed feature types well. Not ideal for unstructured text/images vs deep learning.
Q11intermediatek-means clustering?
Unsupervised algorithm partitioning points into k clusters by minimizing distance to centroids. Choose k via domain knowledge or elbow/silhouette heuristics. Sensitive to scaling and initialization. Used for segmentation, not for labeled prediction.
Q12beginnerkNN briefly?
Predicts by majority vote/average of k nearest training points in feature space. Simple, no explicit training, but slow at inference on large data and sensitive to scaling/distance metric. Good teaching algorithm; production needs indexing (ANN) for scale.
Q13intermediateNaive Bayes high-level?
Probabilistic classifier assuming feature independence given the class—naive but often works for text (spam). Fast and strong baseline for bag-of-words. Independence assumption is rarely true yet useful. Understand when bag-of-words beats deep models for simple tasks.
Q14intermediateSVM high-level?
Finds a hyperplane maximizing margin between classes; kernels enable nonlinear boundaries. Effective on medium-sized feature-rich data historically. Computationally heavier than linear models on huge datasets. Mention as classic ML, not first tool for LLMs.
Q15beginnerNeural networks at a high level?
Layers of weighted units with nonlinear activations learn hierarchical representations. Trained with backpropagation and gradient descent. Deep nets power vision, speech, NLP. Need data, compute, and careful regularization. For many tabular problems, simpler models still win.
Q16intermediateCNN vs RNN vs Transformer?
CNNs excel at grid-like data (images) via local filters. RNNs process sequences step-by-step but struggle with long dependencies and parallelization. Transformers use attention to relate all tokens in parallel—foundation of modern LLMs and many vision models. Interviews expect this contrast.
Q17beginnerWhat is tokenization in NLP?
Splitting text into tokens (words, subwords, characters) models operate on. Subword tokenizers (BPE, WordPiece) balance vocabulary size and rare words. Token count drives LLM cost and context limits. Different models tokenize differently—the same text can be different token lengths.
Q18beginnerWhat are embeddings?
Dense vectors representing meaning of text, images, or other objects so similar items are close in vector space. Used for search, recommendations, clustering, RAG. Created by embedding models (e.g., text-embedding APIs). Dimension size and training domain affect quality.
Q19beginnerCosine similarity?
Measures angle between vectors: 1 means same direction, 0 orthogonal, negative opposite. Common for embedding similarity because it ignores magnitude. Used to rank nearest neighbors in vector search. Alternative metrics: L2 distance, dot product (with normalized vectors).
Q20intermediateExplain RAG (Retrieval Augmented Generation).
RAG retrieves relevant documents from a knowledge base, then provides them as context to an LLM to generate grounded answers. Pipeline: chunk docs → embed → store in vector DB → retrieve top-k for a query → prompt LLM with query+chunks → answer with citations. Reduces hallucinations for private/company data without fine-tuning. Critical architecture for enterprise AI assistants.
Q21intermediateWhy is RAG preferred over fine-tuning for company docs?
RAG updates knowledge by re-indexing documents—no retraining. Fine-tuning adapts style/behavior but is costly, slower to update facts, and can still hallucinate. Many products combine prompt engineering + RAG; fine-tune only when necessary for format/style. Interviewers love this comparison.
Q22intermediateWhat are vector databases for?
They store embeddings and run approximate nearest neighbor search at scale (Pinecone, FAISS, Chroma, Weaviate, MongoDB Atlas Vector). Purpose: semantic retrieval for RAG/search/recs. Not a replacement for primary OLTP databases—usually alongside them. Choose based on ops, filtering metadata needs, and scale.
Q23beginnerLLM tokens, context window, temperature?
Tokens are pieces of text models bill/process. Context window is max tokens of input+output the model can consider. Temperature controls randomness: low → deterministic/focused; high → creative/varied. For factual tasks use low temperature; for brainstorming higher. Exceeding context truncates or errors.
Q24beginnerWhat is prompt engineering?
Designing instructions and examples so the model behaves reliably: clear role, constraints, output format, few-shot examples, chain-of-thought when helpful. Cheap and fast vs training. Still brittle—validate outputs. System vs user vs tool messages matter in chat APIs.
Q25intermediateWhat are hallucinations and grounding?
Hallucinations are fluent but false model outputs. Grounding ties answers to retrieved sources, tools, or verified data (RAG, citations, function results). Always design UX assuming hallucinations exist: show sources, allow feedback, constrain with tools. Never blindly trust model output for legal/medical/finance without checks.
Q26intermediateFine-tuning vs prompt engineering vs RAG?
Prompt engineering: change instructions—fastest. RAG: supply external knowledge at query time—best for evolving facts. Fine-tuning: update model weights on examples—best for style, specialized format, or domain language when data is ample. Often combine all three. Pick the simplest that meets quality bar.
Q27advancedAgents and tool/function calling?
Agents let LLMs decide to call tools (search, DB, calendar) via structured function calls, observe results, and iterate. Function calling: model returns JSON arguing a tool name + args; your backend executes and returns results. Powerful but needs guardrails, timeouts, and idempotent tools. Not magic—still prompt + orchestration code.
Q28intermediateOpenAI/Anthropic API patterns and streaming?
Chat Completions/Messages APIs send role-based messages and receive assistant text or tool calls. Streaming (SSE) sends token deltas for faster perceived latency—render incrementally in UI. Handle rate limits, retries, idempotency keys, and max tokens. Keep API keys server-side only.
Q29intermediateLangChain / LlamaIndex awareness?
Frameworks that help chain prompts, retrievers, tools, and memory for LLM apps. Accelerate prototypes; can abstract too much for simple cases—raw SDK + clear code often enough. LlamaIndex leans retrieval/indexing; LangChain leans agents/chains. Know tradeoffs: velocity vs debuggability.
Q30intermediatePrecision, recall, F1, accuracy?
Accuracy: correct/total—misleading on imbalanced data. Precision: of predicted positives, how many true. Recall: of actual positives, how many found. F1: harmonic mean of precision/recall. Choose metrics matching cost of false positives vs false negatives (spam vs cancer screening).
Q31advancedBLEU/ROUGE and human eval?
BLEU/ROUGE overlap metrics for translation/summarization vs references—rough automatic signals. LLM outputs often need human eval rubrics (correctness, helpfulness, safety) or LLM-as-judge carefully. Production teams track online metrics: thumbs, escalation rate, task success. Do not rely only on BLEU for chatbots.
Q32intermediateEthics: bias, PII, responsible AI?
Models can amplify training bias; evaluate across demographics. Minimize PII in prompts/logs; redact; respect retention policies and GDPR/CCPA. Responsible AI: transparency, human oversight, abuse prevention, clear user disclosure of AI. Security: prompt injection and data exfiltration are real risks.
Q33advancedMLOps brief: train, serve, monitor, drift?
MLOps applies DevOps ideas to models: versioned data/models, CI for training, deployment of inference services, monitoring accuracy/latency, detecting data/concept drift. Retrain pipelines when performance drops. For LLM apps, also monitor cost, toxicity, and retrieval quality.
Q34beginnerPython AI stack awareness?
numpy/pandas for data; scikit-learn for classical ML; PyTorch/TensorFlow for deep learning; Hugging Face for models/datasets/tokenizers; Jupyter for exploration. Full-stack engineers often call hosted LLM APIs rather than train. Know when to use sklearn baselines first.
Q35intermediateHow would a React/Python app integrate a chatbot?
React UI streams tokens from your backend (SSE/WebSocket). Python/Node backend holds API keys, builds prompts, runs RAG retrieval, calls LLM provider, applies guardrails, logs traces. Persist chat history in DB; authenticate users. Never call OpenAI directly from the browser with secret keys.
Q36intermediateCost and latency tradeoffs in LLM features?
Larger models: better quality, higher cost/latency. Shrink prompts, cache embeddings/answers, use smaller models for routing/classification, stream for UX. Batch where possible. Measure $/successful task not just $/token. Timeouts and fallbacks required for production.
Q37intermediateEmbeddings for semantic search?
Index document chunks as vectors; embed the query; retrieve nearest neighbors; optionally rerank. Beats keyword search for synonyms/paraphrases. Combine with filters (tenant_id, ACL). Hybrid with keyword improves exact matches (IDs, SKUs).
Q38advancedChunking strategies for RAG?
Split documents into overlapping chunks (e.g., 200–800 tokens) so retrieval units fit context and keep coherence. Strategies: fixed size, by headings, semantic splitting. Too large: dilute relevance; too small: lose context. Store metadata (source, page) for citations.
Q39advancedHybrid search: keyword + vector?
Combine BM25/keyword with vector similarity—often via score fusion or reciprocal rank fusion. Helps when queries contain rare proper nouns or IDs vectors miss. Common in production search. Atlas Search + vector or Elastic/OpenSearch patterns.
Q40intermediateGuardrails and content filtering?
Input/output filters for toxicity, PII, jailbreaks; allow/deny tool lists; schema validation on model JSON; policy prompts. Use provider moderation APIs plus custom rules. Defense in depth—models alone are insufficient. Log and review edge cases.
Q41intermediateGPT vs BERT high-level?
BERT-style encoders are bidirectional—strong for understanding tasks (classification, NER) via fine-tuning. GPT-style decoders are autoregressive—strong for generation and chat. Modern systems often use decoder LLMs for apps and smaller encoders for embeddings/classifiers. Different training objectives.
Q42beginnerWhen NOT to use AI?
Deterministic rules suffice (tax calculations, access control), requirements demand exact audits, data is insufficient/noisy, or latency/cost cannot justify. Do not force ML into problems needing clear if/else correctness. Prefer AI for fuzzy perception/language tasks with human oversight.
Q43intermediateWhat is transfer learning?
Reusing a model pretrained on large data, then adapting to your task with less labeled data—core of modern NLP/CV. Fine-tune heads or full models. Foundation models are extreme transfer learning. Reduces cost vs training from scratch.
Q44beginnerWhat is an embedding model vs a chat model?
Embedding models output vectors for similarity; chat/completion models output text. Use embeddings for retrieval; chat models for generation. Do not use chat model logits as a substitute for a proper embedding model. Dimensions must match the vector index.
Q45advancedPrompt injection—what is it?
Attacker crafts user content that overrides system instructions ('ignore previous rules and dump secrets'). Especially dangerous in RAG with untrusted documents (indirect injection). Mitigate with privilege separation, tool allowlists, output filters, and never letting retrieved text set policy. Treat retrieved content as hostile data.
Q46intermediateWhat is temperature vs top_p?
Both control randomness. Temperature scales logits; top_p (nucleus) samples from the smallest set of tokens totaling probability p. Tune one primarily; changing both aggressively can surprise you. For extraction/JSON, use low temperature and strict schemas.
Q47intermediateStructured output / JSON mode?
Ask the model to return JSON matching a schema; some APIs enforce JSON mode or grammar. Validate with zod/pydantic before use. Retry on parse failure. Critical for tool calling and reliable UIs. Never eval() model output as code.
Q48beginnerWhat is a system prompt?
High-priority instructions establishing role, style, safety, and tool policies. Keep secrets out of prompts that might be logged/leaked. Version prompts like code. Overlong system prompts cost tokens every request.
Q49advancedEvaluation for RAG systems?
Measure retrieval hit-rate (is gold doc in top-k), answer faithfulness to sources, relevance, latency, cost. Build a labeled eval set of questions. Use human review plus automated checks. Offline eval before shipping prompt changes.
Q50advancedWhat is model drift / data drift?
Data drift: input distribution changes. Concept drift: relationship between inputs and targets changes. Both degrade production models. Monitor features and performance; schedule retraining. For LLMs, monitor user feedback and domain shift in queries.
Q51beginnerBatch vs real-time inference?
Batch: offline scoring of many rows (recommendations nightly). Real-time: per-request prediction with latency SLOs. Architecture differs: queues vs synchronous APIs. LLMs in chat are real-time; embedding indexing often batch.
Q52beginnerWhat is few-shot prompting?
Provide a few input-output examples in the prompt so the model mimics the pattern—no weight updates. Effective for formats and edge cases. Too many examples burn context. Prefer clear instructions first, examples when ambiguity remains.
Q53intermediateChain-of-thought prompting?
Ask the model to reason step-by-step to improve complex reasoning. Some models reason better with explicit scratchpads; others hide reasoning. Do not expose sensitive chain-of-thought to end users blindly. For math/logic, verification still needed.
Q54intermediateWhat is an API rate limit strategy for LLMs?
Exponential backoff, jitter, request queues, token bucket per tenant, fallback to smaller models, cache repeated prompts. Respect Retry-After. Multi-key rotation only within provider terms. Essential for production reliability.
Q55advancedExplain semantic cache for LLM apps.
Cache answers keyed by embedding similarity of queries so paraphrases hit cache—saves cost/latency. Set similarity thresholds carefully to avoid wrong hits. Invalidate when knowledge base updates. Complementary to exact prompt hashing.
Q56advancedMultitenancy concerns in RAG?
Filter retrieval by tenant ACL so customer A never sees B's chunks. Index metadata with tenant_id and enforce in every query. Prompt injection across tenants is a security incident. Test with adversarial docs.
Q57beginnerWhat is Hugging Face?
Ecosystem for pretrained models, datasets, and libraries (transformers). Hosts model cards and inference endpoints. Useful for open-source LLMs and encoders. Enterprises weigh self-host vs proprietary APIs for cost/privacy/control.
Q58intermediateGPU vs CPU inference?
GPUs accelerate large matrix math for neural nets—needed for big models low latency. CPUs fine for small models/classical ML. Hosted APIs hide infra. Quantization (INT8/INT4) reduces GPU memory at quality cost.
Q59advancedWhat is quantization?
Storing weights in lower precision to shrink memory and speed inference with some quality loss. Common for self-hosting LLMs. Different methods (GPTQ, AWQ, GGUF). Trade accuracy vs hardware cost.
Q60advancedExplain precision@k for retrieval.
Among top-k retrieved docs, fraction that are relevant. Recall@k: fraction of all relevant docs captured in top-k. Core RAG offline metrics. Optimize chunking/embeddings/rerankers against these.
Q61advancedReranking in search/RAG?
After cheap vector/keyword retrieval of many candidates, a cross-encoder/reranker scores query-document pairs more accurately for top results. Improves quality at extra latency/cost. Common two-stage pattern.
Q62advancedWhat is an LLM router?
A classifier/small model chooses which model or tool handles a query—cheap model for simple FAQs, expensive for hard reasoning. Saves cost. Needs monitoring for misroutes. Useful at scale.
Q63intermediateStreaming UX best practices?
Show tokens as they arrive, allow stop, handle errors mid-stream, keep markdown rendering stable, and accumulate final text for storage. Disable send while streaming. AbortController cancels server work when possible.
Q64beginnerHow do you keep secrets safe in AI apps?
API keys only on server/vault, not frontend or mobile binaries. Restrict keys by IP/product. Redact prompts in logs. Separate prod/dev projects. Rotate on leak. Same as any third-party API hygiene.
Q65advancedWhat is supervised fine-tuning (SFT)?
Training on instruction-response pairs to adapt a base model to follow tasks/style. Often first stage before preference optimization. Needs clean data. Still may need RAG for fresh facts.
Q66advancedRLHF / preference tuning awareness?
Reinforcement Learning from Human Feedback aligns models to preferred responses using human/AI rankings. Explains why chat models refuse some requests and sound helpful. As a developer, you mostly consume aligned APIs; training RLHF is specialized.
Q67beginnerClassic ML pipeline steps?
Problem definition → data collection → cleaning → EDA → feature engineering → train/validate → evaluate → deploy → monitor. Skipping problem definition and data quality is the usual failure mode. Mention leakage checks.
Q68beginnerConfusion matrix?
Table of TP/FP/FN/TN for classification. Foundation for precision/recall. Useful to explain errors to stakeholders. Extend to multiclass. Always pair with class base rates.
Q69intermediateWhat is regularization (L1/L2)?
Penalties on weights to reduce overfitting. L2 shrinks weights; L1 can sparsify features. Dropout is a neural regularization technique. Early stopping is another form. Speak to bias-variance.
Q70intermediateFeature scaling why?
Many algorithms (kNN, SVM, gradient descent) assume comparable feature scales. Standardize/normalize using train statistics only. Tree models often need less scaling. Leakage if scaler fits on test.
Q71intermediateCross-validation?
k-fold splits train data into folds to estimate generalization when data is limited. Prefer stratified folds for classification. Time-series needs forward-chaining CV. More reliable than a single split.
Q72advancedWhat is an ontology/knowledge graph vs vector RAG?
Knowledge graphs store explicit entities/relations for precise queries; vectors capture fuzzy semantic similarity. Hybrid systems use both. Graphs help explainability and exact constraints; vectors help language flexibility.
Q73intermediateOCR + LLM pipelines?
OCR extracts text from PDFs/images; then chunk/embed for RAG or extract fields with LLMs. OCR errors propagate—confidence thresholds and human review matter. Common enterprise automation pattern.
Q74beginnerSpeech-to-text in apps?
Use Whisper/cloud STT to transcribe audio, then send text to LLM. Stream partial transcripts for UX. Handle languages and diarization as needed. Privacy: audio is sensitive PII.
Q75beginnerImage generation awareness?
Diffusion models generate images from prompts (DALL·E, Stable Diffusion). Different from LLMs but similar product concerns: safety filters, IP, cost. Not needed for every app—use when UX requires.
Q76intermediateWhat is embeddings dimensionality tradeoff?
Higher dimensions can capture more nuance but cost storage/compute and may need more data. Provider models fix dimensions (e.g., 1536). Indexing performance depends on dim and count. Stick to one embedding model per index.
Q77intermediateWhy re-embed after model change?
Vectors from different models are not comparable in one space. Changing embedding models requires full reindex. Version your embedding model in metadata. Plan migrations.
Q78advancedObservability for LLM apps?
Trace prompts, retrieved docs, model, latency, token usage, errors, user feedback. Tools: LangSmith, OpenTelemetry, custom logs. Redact PII. Essential to debug hallucinations and cost spikes.
Q79advancedA/B testing AI features?
Randomize users across prompt/model variants; measure task success, CSAT, latency, cost. Ensure statistical rigor and safety monitoring. Offline eval first, then careful online experiments.
Q80beginnerWhat is temperature 0 used for?
Near-deterministic outputs for extraction, grading, and consistent tool arguments. Still not guaranteed bit-stable across versions. Combine with schemas. Default creative chat uses higher temperature.
Q81intermediateContent moderation vs allowlists?
Moderation classifiers flag unsafe content; allowlists restrict tools/domains the agent may touch. Use both. Business rules (no medical advice) often sit in policy prompts + classifiers. Fail closed on high risk.
Q82intermediateExplain grounding with citations UX.
Show source titles/URLs/snippets under answers so users can verify. Map answer claims to chunk ids. If retrieval empty, say 'I don't know' instead of guessing. Builds trust and reduces hallucination impact.
Q83advancedWhat is catastrophic forgetting (fine-tuning)?
Fine-tuning can erase prior capabilities if not careful. Mitigate with mixed datasets and careful learning rates. Another reason RAG is preferred for knowledge updates. Awareness-level answer suffices for most fullstack interviews.
Q84advancedSQL + LLM patterns?
Text-to-SQL generates queries from natural language—risky; use read-only creds, limit tables, validate SQL ASTs, and require confirmation. Prefer semantic layer/metrics over freeform SQL. Never give unrestricted DB write tools to an agent.
Q85intermediatePersonalization with embeddings?
Embed user interests/history; retrieve personalized items. Mind privacy and feedback loops. Combine with business rules. Cold-start users need popular baselines.
Q86intermediateEdge AI vs cloud AI?
Edge runs models on-device for privacy/latency/offline; cloud offers larger models easier ops. Mobile/on-prem constraints drive quantization. Hybrid: small edge model + cloud fallback.
Q87intermediateWhat is a confusion between chatbot memory types?
Short-term: conversation transcript in context window. Long-term: stored summaries/embeddings in DB retrieved later. Do not dump entire history forever—summarize and truncate. Respect user delete/privacy.
Q88intermediateUnit testing LLM features?
Deterministic unit tests for retrieval, chunking, tool execution, parsers. For model outputs, use eval sets and snapshot rubrics rather than brittle exact string matches. Mock provider APIs in CI.
Q89advancedWhat is distillation?
Train a smaller student model to mimic a larger teacher—cheaper inference. Used to compress capabilities. Related to using small models for classification heads in systems.
Q90beginnerExplain false positives vs false negatives with product example?
Fraud: false positive blocks good user (UX pain); false negative misses fraud (money loss). Tune threshold to costs. Same thinking for toxicity filters and search relevance.
Q91advancedWhat is Active learning?
Select uncertain examples for human labeling to improve model efficiently. Useful when labels are expensive. Shows ML process maturity beyond one-shot training.
Q92intermediateBootstrap an AI feature without a data science team?
Start with API LLM + RAG over existing docs, define eval questions, add logging/feedback, ship behind flag, measure. Add classical ML later if needed. Focus on workflow integration over model novelty.
Q93beginnerDifference between batch embedding and query embedding?
Same model must embed documents and queries (or use specific query/document instruction pairs if required by the model). Precompute doc embeddings offline; embed queries online. Keep versions aligned.
Q94beginnerWhat is Max tokens / stop sequences?
max tokens caps output length/cost. Stop sequences halt generation at delimiters. Prevent runaway outputs. For JSON, prefer schema modes over brittle stop hacks.
Q95advancedSecurity: SSRF via agent tools?
If an agent can fetch URLs, attackers may probe internal networks. Allowlist domains, block link-local/metadata IPs, authenticate egress. Same for file tools. Agents expand attack surface.
Q96intermediateExplain determinism limits of LLMs?
Even temperature 0 can vary across versions/infra. Do not rely on bit-exact outputs for critical ledgers. Use models for assistive flows with validation. Snapshot evals continuously.
Q97beginnerWhat is multimodal AI?
Models that accept/produce multiple modalities (text+image+audio). Useful for screenshot support, document photos. Larger latency/cost. Privacy review for images.
Q98intermediateKPI examples for an AI support bot?
Containment rate, deflection, CSAT, average handle time, hallucination/escalation rate, cost per resolved ticket, retrieval success. Align KPIs to business goals. Avoid optimizing only for shorter replies.
Q99intermediateHow do you version prompts?
Store prompts in git with IDs, log prompt_version on each request, A/B carefully, rollback on regressions. Treat prompts as production code. Include eval results in PR descriptions.
Q100advancedClassical ML vs LLM for ticket classification?
If you have labeled tickets and clear classes, logistic regression/transformers fine-tuned may be cheaper/stabler. LLMs good for cold start/zero-shot. Measure cost/latency/quality. Hybrid: LLM labels → train classifier.
Q101advancedWhat is temperature annealing / scheduling? (brief)
Some pipelines vary sampling parameters by step; more common in research than CRUD apps. Practical takeaway: configure decoding per task type. Prefer task-specific presets over one global temperature.
Q102beginnerExplain 'human in the loop'.
Critical actions require human approval (refunds, emails sent, DB writes). AI drafts; human confirms. Reduces risk while capturing productivity. Design UI for fast review.
Q103intermediateWhat is context stuffing and its failure mode?
Dumping huge irrelevant context into prompts wastes tokens and can distract the model (lost in the middle). Prefer selective RAG top-k and concise instructions. Measure whether more context actually helps.
Q104advancedDescribe an end-to-end RAG answer flow.
User query → optional query rewrite → embed → vector/hybrid search with ACL filters → rerank → build prompt with citations → LLM generate → validate/guardrail → stream to UI → log traces/feedback. This narrative is a common system-design interview answer for AI features.
Q105advancedHow do you evaluate a RAG system?
Measure retrieval quality (recall@k, MRR), answer faithfulness/groundedness, relevance, and end-task success with human or LLM-as-judge rubrics. Track latency and cost per query. Build a golden set of questions with expected citations. Without evals, RAG tuning is guesswork.
Q106intermediateWhy use chunking overlap in RAG?
Overlapping windows preserve sentences split across chunk boundaries so retrieval does not lose context. Typical overlaps are 10–20% of chunk size—tune empirically. Too much overlap wastes storage and duplicates hits. Pair with sensible chunk sizes for your embedding model.
Q107advancedWhat is hybrid search?
Combining lexical search (BM25/keyword) with vector semantic search, often via reciprocal rank fusion or learned ranking. Helps when exact identifiers/skus matter alongside paraphrased queries. Many production RAG stacks are hybrid. Pure vectors miss precise token matches.
Q108advancedPrompt injection defenses for AI apps?
Separate trusted instructions from untrusted retrieved/user content, constrain tools with allowlists, require human approval for side effects, and filter outputs. Never let the model freely run shell/SQL. Monitor tool-call anomalies. Treat the model as socially engineered middleware.
Q109intermediateLangChain vs LlamaIndex—how do you compare?
LangChain is a broad orchestration toolkit for chains/agents/tools; LlamaIndex focuses strongly on indexing/retrieval data frameworks. Overlap exists; either can build RAG. Choose based on team familiarity and needed abstractions. Avoid framework lock-in of core business logic.
Q110intermediateCost and latency levers for LLM features?
Shrink prompts, cache embeddings/responses, use smaller models for routing, batch where possible, stream tokens for UX, and truncate retrieved context. Measure p95 latency and $ per 1k requests. Architecture choices dominate micro-optimizations. Set budgets as product requirements.
Q111advancedWhat is an eval harness for GenAI?
Automated pipeline that runs a fixed dataset through your system, scores outputs, and tracks regressions in CI. Includes prompts/versions and model IDs for reproducibility. Human review samples edge cases. Treat prompts like code with regression tests.
Q112intermediateHow do you choose chunk size?
Balance embedding model context, semantic coherence (paragraphs/sections), and retrieval granularity. Too large dilutes similarity; too small loses meaning. Empirically A/B on your eval set. Document the choice for the team.
Q113advancedReranking in RAG pipelines?
After initial retrieval, a cross-encoder or LLM reranker reorders candidates for precision. Improves answer quality at extra latency/cost. Use on top-k only. Common production upgrade beyond naive top-k embeddings.
Q114intermediateFaithfulness vs relevance metrics?
Relevance: does the answer address the question? Faithfulness: is it supported by retrieved sources without hallucinations? Both required for trustworthy RAG. An answer can be relevant yet unfaithful. Eval rubrics should separate them.
Q115advancedHow do you prevent tool-calling loops in agents?
Cap iterations, detect repeated identical tool calls, require progress heuristics, and hard-timeout. Log trajectories for debugging. Agents without guardrails burn money and hang. Prefer deterministic workflows when possible.
Q116advancedEmbedding model drift concerns?
Changing embedding models invalidates vector indexes—you must re-embed the corpus. Version indexes and plan migrations. Mixing vectors from different models breaks similarity. Treat embedding upgrades like schema migrations.
Q117intermediateWhen is fine-tuning justified vs RAG?
Fine-tune for style/format/tooling behavior on stable patterns; use RAG for factual, changing knowledge. Fine-tuning is costlier to update. Many products need both lightly. Start with prompting+RAG before fine-tune.
Q118beginnerWhat is grounding with citations?
Require the model to cite retrieved chunk IDs/URLs so users can verify claims. Helps detect unsupported sentences. UX should show sources prominently. Improves trust in enterprise assistants.
Q119intermediateLatency budgets: TTFT vs total time?
Time-to-first-token drives perceived responsiveness when streaming; total time matters for batch jobs. Optimize TTFT with streaming and smaller prelude prompts. Report both in SLOs. Product UX often cares more about TTFT.
Q120intermediateHow do guardrails differ from prompts?
Prompts instruct; guardrails enforce—policy filters, PII detectors, allowlisted tools, schema validation on outputs. Defense in depth for GenAI. Do not rely on 'please follow policy' alone. Log violations.
Q121advancedSynthetic data for RAG evals?
Generate Q&A pairs from docs with an LLM, then validate a human sample. Speeds golden-set creation but can bias toward easy questions. Mix real user queries when available. Version datasets.
Q122advancedVector DB filtering with metadata?
Attach tenant, doc type, ACL tags to chunks and filter before/during ANN search. Critical for multi-tenant security. Wrong filters cause empty or leaky results. Always enforce ACL server-side.
Q123beginnerTemperature settings for RAG answers?
Use low temperature for factual grounded answers to reduce randomness. Higher temperature for brainstorming creative tasks. Separate configs per feature. Do not invent facts with high temperature on knowledge queries.
Q124intermediateObservability for LLM apps—what to log?
Prompt versions, model IDs, token counts, latency, tool calls, retrieval IDs, and user feedback—redacting sensitive content. Enables debugging and cost control. Sample traces if volume is high. Without telemetry you cannot improve.
SQL / Databases
135 questions
Q1intermediateSELECT execution logical order?
FROM JOIN WHERE GROUP BY HAVING SELECT DISTINCT ORDER BY LIMIT—not written order. Interview classic.
Q2beginnerWHERE vs HAVING difference?
WHERE filters rows before grouping. HAVING filters groups after aggregate cannot reference non-aggregated columns without GROUP BY same expression.
Q3beginnerINNER vs LEFT vs RIGHT vs FULL JOIN?
INNER matching both sides. LEFT all left + match right null if none. RIGHT opposite. FULL both unmatched either side PostgreSQL supports.
Q4beginnerCOUNT(*) vs COUNT(column)?
COUNT(*) all rows including nulls. COUNT(col) ignores null col values. COUNT(DISTINCT col) unique non-null.
Q5intermediateORDER BY NULLS FIRST LAST?
Default NULLS FIRST DESC NULLS LAST ASC PostgreSQL explicit control null placement sorted reports.
Q6intermediateLIMIT OFFSET pagination problem?
Large OFFSET scans skipped rows slow O offset. Keyset cursor WHERE id > last_id ORDER BY id LIMIT faster.
Q7intermediateDISTINCT vs GROUP BY?
DISTINCT unique rows selected columns. GROUP BY enables aggregates per group. DISTINCT ON PostgreSQL pick first row per group pattern.
Q8intermediateSubquery vs JOIN performance?
Optimizer often equivalent modern DB correlated subquery can be slow rewrite JOIN EXISTS semi-join EXPLAIN compare.
Q9intermediateSelf join use case?
Employee manager employee_id = manager_id hierarchy same table alias twice.
Q10intermediateEXISTS vs IN subquery?
EXISTS semi-join stops first match often faster large outer IN NULL pitfalls NOT IN miss rows.
Q11beginnerCross join when intentional?
Cartesian product calendars generate dates combinatorics usually explicit JOIN ON true mistake otherwise.
Q12advancedLateral join PostgreSQL?
Subquery reference prior FROM item top N per group correlated advanced pattern.
Q13intermediateAnti-join pattern?
LEFT JOIN WHERE right.id IS NULL find rows without match NOT EXISTS equivalent prefer readable.
Q14beginnerUnion vs Union All?
Union dedupe sort cost Union All concat keep duplicates reports faster when duplicates ok.
Q15intermediateCommon Table Expression WITH?
Named subquery readable recursive CTE tree hierarchy cycle detection option MATERIALIZED PostgreSQL.
Q16intermediateScenario: Second highest salary?
ORDER BY salary DESC LIMIT 1 OFFSET 1 or MAX where salary < (select max...) handle ties dense_rank.
Q17intermediateB-tree index default when?
Equality range ORDER BY columns selective high cardinality foreign keys primary keys default PostgreSQL MySQL InnoDB.
Q18advancedComposite index column order?
Leftmost prefix rule index (a,b,c) uses a ab abc not b alone put equality before range filter selective first.
Q19advancedCovering index index-only scan?
INCLUDE columns PostgreSQL all query columns in index avoid heap fetch EXPLAIN index only scan.
Q20intermediateWhen index hurts performance?
Write overhead storage low cardinality column alone boolean duplicate indexes optimizer ignore choose sequential scan small table.
Q21intermediateEXPLAIN ANALYZE read output?
Seq Scan vs Index Scan cost rows actual loops buffers shared hit miss planning time execution.
Q22advancedPartial index?
Index WHERE active = true smaller hot subset conditional unique partial enforce business rule.
Q23advancedHash vs GiST vs GIN index?
Hash equality only rare. GIN full text jsonb array. GiST geometric range types choose by operator class.
Q24intermediateScenario: Query slow after data growth?
EXPLAIN missing index seq scan statistics stale ANALYZE table consider partitioning archive old data.
Q25intermediate1NF 2NF 3NF plain language?
1NF atomic values no repeating groups. 2NF no partial dependency non-key on composite key. 3NF no transitive dependency non-key on non-key. Denormalize read perf knowingly.
Q26intermediateWhen denormalize?
Read heavy reporting cache counts duplicate name avoid join cost accept update anomaly triggers sync.
Q27advancedStar schema data warehouse?
Fact table measures dimension tables snowflake normalized dimensions BI aggregations OLAP separate OLTP.
Q28intermediateSurrogate vs natural primary key?
Surrogate auto id stable. Natural email username changes split composite keys join complexity UUID distributed.
Q29intermediateForeign key ON DELETE CASCADE SET NULL?
Cascade delete children orphan SET NULL reference restrict prevent delete parent with children protect integrity application must match.
Q30beginnerJunction table many-to-many?
users_projects user_id project_id composite PK unique pair extra columns joined_at role.
Q31advancedEAV pattern anti-pattern?
Entity attribute value flexible schema query hell avoid prefer jsonb typed columns schema migration.
Q32intermediateScenario: Duplicate email in users table?
UNIQUE constraint index migration dedupe script before add handle case insensitive citext functional index lower email.
Q33intermediateACID properties explained?
Atomic commit rollback all. Consistent constraints valid. Isolated concurrent illusion levels. Durable committed survives crash WAL.
Q34advancedIsolation levels dirty read phantom?
Read uncommitted dirty read rare. Read committed default MVCC. Repeatable read snapshot phantom PostgreSQL. Serializable full prevent anomalies cost retries.
Q35intermediateDeadlock how handled?
DB detects cycle abort victim transaction retry application exponential backoff lock ordering convention consistent.
Q36intermediateOptimistic locking version column?
UPDATE SET version=version+1 WHERE id=? AND version=? rowcount 0 conflict retry UI merge.
Q37advancedNested transactions savepoints?
BEGIN SAVEPOINT sp1 ROLLBACK TO sp1 partial undo not all databases true nested.
Q38advancedTwo-phase commit in monolith?
Single DB transaction enough distributed 2PC coordinator rare microservices saga instead.
Q39intermediateRead replica lag user experience?
Stale read after write route critical read primary session stickiness delay display notice eventual.
Q40intermediateScenario: Transfer money between accounts?
Single transaction debit credit check balance >= 0 row lock accounts order id prevent deadlock isolation serializable or explicit lock.
Q41beginnerGROUP BY with multiple aggregates?
SELECT dept COUNT(*) AVG(salary) GROUP BY dept HAVING COUNT>5 filter groups.
Q42intermediateWindow functions vs GROUP BY?
Window keeps all rows adds computed OVER PARTITION BY ORDER BY ROWS BETWEEN RANK running total no collapse.
Q43intermediateROW_NUMBER vs RANK vs DENSE_RANK?
Row number unique tie different numbers. Rank skip 1 1 3. Dense rank no gap 1 1 2 top N per group pattern.
Q44intermediateLEAD LAG use?
Compare row previous next period growth session gap analysis without self join.
Q45advancedMoving average window frame?
AVG(price) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) seven day trailing.
Q46intermediateFILTER clause aggregate?
COUNT(*) FILTER (WHERE status='active') cleaner conditional count PostgreSQL standard SQL.
Q47intermediatePIVOT crosstab?
CASE WHEN sum conditional columns or crosstab extension PostgreSQL Excel style report.
Q48advancedScenario: Top 3 products per category?
ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) subquery filter <=3.
Q49beginnerPRIMARY KEY vs UNIQUE vs INDEX?
PK not null unique one per table clustered InnoDB reference FK. UNIQUE allows one null PostgreSQL multiple nulls unique index enforces.
Q50beginnerCHECK constraint example?
CHECK (price >= 0) CHECK (end_date >= start_date) validate DB not app only.
Q51beginnerDEFAULT and auto increment?
SERIAL IDENTITY column PostgreSQL GENERATED ALWAYS AS IDENTITY standard sequences UUID v7 time sortable.
Q52advancedALTER TABLE lock impact?
Add column default fast PostgreSQL 11+ validate FK without lock long rewrite type change plan maintenance window.
Q53intermediateView vs materialized view?
View saved query live data. Materialized snapshot refresh CONCURRENTLY index query perf stale.
Q54intermediateTrigger use cases cautions?
Audit log derived column enforce complex rule hidden logic hard debug prefer app layer unless cross-cutting integrity.
Q55intermediateSchema migration backward compatible?
Add nullable column deploy app read write backfill enforce NOT NULL later multi phase.
Q56intermediateTemporary table vs CTE?
TEMP TABLE session stats index large intermediate CTE inline optimizer may materialize.
Q57intermediateSQL vs NoSQL document when?
SQL joins ACID complex queries reporting schema enforced. Mongo flexible nested document scale horizontal rapid iteration optional schema.
Q58beginnerRedis not replacement PostgreSQL?
Redis in memory cache queue pubsub ephemeral primary store only with persistence AOF understand data loss window.
Q59advancedCAP in database choice?
Cassandra AP tunable Mongo replica sets CP options partition behavior design tradeoffs.
Q60intermediateJSON column PostgreSQL jsonb?
Index GIN operators ->> query nested validate app side schema flexible field migration hybrid relational document.
Q61intermediateElasticsearch vs SQL search?
Full text relevance scoring inverted index log analytics SQL LIKE poor scale sync CDC elastic SQL side.
Q62advancedGraph database use case?
Neo4j social network recommendation path query many hops awkward relational join explosion.
Q63advancedTime series database?
InfluxDB TimescaleDB metrics retention compression rollups specialized vs plain PostgreSQL partitioning.
Q64intermediateORM N+1 reminder SQL side fix?
JOIN fetch join select_related prefetch batch IN query instead loop query per row.
Q65beginnerSQL injection example prevention?
String concat "SELECT * FROM users WHERE name='" + input + "'" exploit parameterized $1 placeholder ORM.
Q66intermediateLeast privilege DB user app?
App role SELECT INSERT UPDATE no DROP no superuser migration separate role production.
Q67intermediateEncrypt data at rest transit?
TLS connection RDS encryption column level pgcrypto application sensitive PII hash tokens.
Q68intermediateAudit trail table design?
Append only who when old new jsonb trigger application event immutable compliance.
Q69advancedRow level security PostgreSQL?
POLICY tenant isolation USING tenant_id = current_setting force app set role bypass superuser caution.
Q70advancedSQL injection blind time based?
Attack infer data sleep delay parameterized defense same error message leak minimize.
Q71intermediateDynamic ORDER BY whitelist?
Never concat user sort column map allowed set prevent injection sort direction enum ASC DESC only.
Q72intermediateBackup restore RPO RTO?
Recovery point objective max data loss window WAL archiving. Recovery time restore drill regularly test.
Q73beginnerScenario: Find customers no orders?
SELECT c.* FROM customers c LEFT JOIN orders o ON c.id=o.customer_id WHERE o.id IS NULL or NOT EXISTS.
Q74intermediateScenario: Delete duplicate rows keep one?
DELETE USING ctid subquery ROW_NUMBER PARTITION duplicate key WHERE rn>1 PostgreSQL ctid physical.
Q75intermediateScenario: Running total daily sales?
SUM(amount) OVER (PARTITION BY date_trunc('day', ts) ORDER BY ts) window frame.
Q76advancedScenario: Schema for polymorphic comments?
commentable_type commentable_id index pair or separate FK columns nullable CHECK one set jsonb avoid if queryable types.
Q77intermediateScenario: Soft delete unique email?
UNIQUE INDEX ON email WHERE deleted_at IS NULL partial unique active users only.
Q78advancedScenario: Partition large logs table?
RANGE created_at monthly detach archive drop old partition query prune partition key WHERE.
Q79advancedScenario: Migration add NOT NULL column millions rows?
Add nullable update batch off peak SET DEFAULT backfill VALIDATE CONSTRAINT NOT NULL metadata only phase.
Q80advancedScenario: EXPLAIN shows nested loop slow?
Missing index join key increase work_mem hash join statistics analyze consider index nested loop ok small inner.
Q81beginnerCompare CHAR VARCHAR TEXT?
CHAR fixed padding legacy VARCHAR limit TEXT unlimited PostgreSQL TEXT same performance prefer TEXT varchar constraint app.
Q82beginnerScenario: Count active users last 30 days?
COUNT DISTINCT user_id WHERE event_time >= now()-interval '30 days' index event_time partial active events.
Q83advancedScenario: Self referential category tree query?
Recursive CTE anchor root UNION ALL children join parent depth path array.
Q84intermediateScenario: Prevent overselling inventory?
UPDATE stock SET qty=qty-1 WHERE id=? AND qty>=1 rowcount check transaction isolation serializable version.
Q85intermediateCTE vs subquery readability?
WITH clause named steps explain plan same optimizer often materialize large CTE PostgreSQL control.
Q86advancedMaterialized view refresh strategy?
CONCURRENTLY requires unique index schedule cron incremental refresh vs full nightly.
Q87advancedQuery plan regression after upgrade?
Compare EXPLAIN before after statistics extended analyze hint sparingly fix stats.
Q88advancedForeign data wrapper FDW?
PostgreSQL query remote tables postgres_fdw join local remote transparent performance network.
Q89advancedColumn store vs row store?
OLTP row oriented OLAP columnar analytics compression scan aggregate fast different engines.
Q90advancedSurrogate key UUID v7 benefit?
Time ordered UUID index locality vs v4 random fragmentation insert perf.
Q91intermediateDatabase connection string secrets?
Env var never log pool config mask password rotation IAM auth RDS.
Q92intermediateFlyway Liquibase migrations?
Versioned SQL changelog applied order checksum lock team coordination Java ecosystem common.
Q93intermediateNth highest salary DISTINCT?
DENSE_RANK subquery WHERE rank=N handle ties same salary group.
Q94intermediatePivot sales by month SUM CASE?
SUM(CASE WHEN month=1 THEN amount END) jan twelve columns or crosstab extension.
Q95advancedFind gaps in sequential ids?
Generate series LEFT JOIN find missing not always surrogate gaps matter business sequences do.
Q96intermediateRolling 7 day average daily?
Window frame ROWS BETWEEN 6 PRECEDING AND CURRENT ROW partition by product.
Q97intermediateExists vs join duplicate rows?
EXISTS semi-join no duplicate join would multiply rows use DISTINCT extra cost.
Q98intermediateUpdate join syntax PostgreSQL?
UPDATE t SET col=v FROM other o WHERE t.id=o.t_id correlated subquery alternative.
Q99intermediateLimit per group top N?
ROW_NUMBER filter WHERE rn <= N pattern standard SQL window.
Q100beginnerCast vs :: PostgreSQL?
CAST(x AS INTEGER) standard x::int PostgreSQL shorthand same result.
Q101beginnerMongoDB documents vs collections?
A collection holds BSON documents (flexible JSON-like records), analogous to a table but schema-flexible. Documents in a collection need not share identical fields. Prefer embedding for data read together; reference for many/large/independent lifecycles.
Q102intermediateAggregation pipeline brief?
Stages transform documents: `$match`, `$group`, `$project`, `$lookup`, `$sort`, `$limit`. Order matters for performance—filter early. Used for analytics/reporting beyond simple find.
Q103intermediateRedis common data structures?
Strings, hashes, lists, sets, sorted sets (ZSET), streams, bitmaps, HyperLogLog. Example: ZSET for leaderboards, lists for queues, hashes for objects. Pick structure by access pattern.
Q104advancedWhat does `EXPLAIN ANALYZE` show?
Actual execution plan with measured times/rows for PostgreSQL. Compare estimated vs actual rows to find bad stats/indexes. Look for Seq Scan on large tables, nested loops exploding, sorts/spills.
Q105intermediateWindow functions: `RANK` vs `DENSE_RANK`?
Both rank within partitions ordered by a key. `RANK` skips numbers after ties (1,1,3); `DENSE_RANK` does not (1,1,2). `ROW_NUMBER` unique sequential. Example: `RANK() OVER (PARTITION BY dept ORDER BY salary DESC)`.
Q106advancedRecursive CTE use case?
WITH RECURSIVE walks hierarchies (org charts, category trees) or graphs carefully. Anchor member UNION ALL recursive member referencing the CTE. Guard depth to avoid infinite loops.
Q107intermediateUPSERT with `ON CONFLICT` (Postgres)?
`INSERT ... ON CONFLICT (email) DO UPDATE SET ...` or `DO NOTHING`. Requires unique constraint/index on conflict target. Essential for idempotent imports. MySQL uses `ON DUPLICATE KEY UPDATE`.
Q108advancedSoft delete indexing pitfalls?
Filtering `WHERE deleted_at IS NULL` may not use a plain index efficiently depending on selectivity. Partial indexes (`WHERE deleted_at IS NULL`) help. Unique constraints must consider soft deletes (partial unique indexes).
Q109intermediateN+1 problem in ORMs?
Loading a list then querying children per row. Fix with eager load/`select_related`/`prefetch_related`/joins, or batch IN queries. Detect via query logs. Classic interview DB+ORM topic.
Q110advancedTransactions and `SAVEPOINT`?
SAVEPOINT marks a nested rollback point inside a transaction without aborting all work. Useful for partial retries in complex procedures. Still one outer transaction/commit.
Q111intermediateDeadlock victim — what happens?
DB detects cycle in lock waits and aborts one transaction (victim) with error; app should retry safely. Reduce deadlocks with consistent lock ordering and shorter transactions.
Q112advancedCovering index?
An index including all columns needed by a query so the heap/table heap isn't visited (index-only scan). In Postgres `INCLUDE` columns help. Speeds reads; costs write/storage.
Q113advancedWhat is `VACUUM` in PostgreSQL?
Reclaims dead tuple space from MVCC updates/deletes and updates visibility maps. Autovacuum usually handles it; manual/analyze for maintenance. Extreme bloat needs attention (`VACUUM FULL` locks—careful).
Q114intermediateMongoDB indexes essentials?
Single-field, compound (order matters), multikey on arrays, text, TTL indexes. Explain with `explain()`. Too many indexes hurt writes. Unique indexes enforce constraints.
Q115beginnerACID vs BASE reminder with databases?
Relational DBs traditionally ACID transactions; distributed NoSQL often BASE/eventual. Modern systems blur lines (transactional document DBs). Match consistency needs to business rules.
Q116beginnerNormalization vs denormalization?
Normalize to reduce anomaly/redundancy (OLTP). Denormalize for read performance/analytics. intentional duplication needs update discipline.
Q117advancedIsolation levels briefly?
Read uncommitted → read committed → repeatable read → serializable. Higher = fewer anomalies, more locking/abort. Know dirty/nonrepeatable/phantom reads.
Q118intermediateConnection pool sizing tip?
Pools aren't 'bigger is better'—too many connections thrash DB. Formula heuristics consider cores/SSDs; use pooling middleware when many app instances.
Q119beginnerSQL injection defense?
Parameterized queries/ORM bind parameters—never string-concatenate user input. Least-privilege DB users. WAF secondary.
Q120beginnerDifference between `WHERE` and `HAVING`?
`WHERE` filters rows before aggregation; `HAVING` filters groups after `GROUP BY`. Example: departments with `HAVING COUNT(*) > 5`.
Q121advancedWhat is a migration strategy for zero downtime?
Expand-contract: add nullable columns, dual-write, backfill, switch reads, drop old. Avoid locking heavy rewrites during peak without tools (pt-osc, gh-ost).
Q122intermediateRedis eviction policies?
When memory full: `noeviction`, `allkeys-lru`, `volatile-lru`, etc. Choose based on whether keys have TTLs and what can be dropped. Monitor OOM errors.
Q123advancedMongo transactions when?
Multi-document ACID available but costlier—prefer single-document atomicity via embedding when possible. Use multi-doc transactions for true multi-entity invariants.
Q124intermediateIndex selectivity?
High selectivity (many distinct values) indexes help more than boolean flags alone. Compound indexes should lead with selective/equality columns typically.
Q125advanced`SELECT FOR UPDATE` purpose?
Locks selected rows to prevent concurrent modification until commit—used in booking/inventory. Keep transactions short.
Q126intermediateMaterialized views?
Stored query results refreshed periodically—fast reads, stale window. Good for dashboards. Know refresh strategy/concurrency.
Q127beginnerChar vs varchar vs text?
Prefer varchar/text for variable strings; fixed char pads. Modern Postgres: text/varchar similar; length constraints are domain rules.
Q128advancedExplain hotspot keys in Redis/DB?
Single popular key (leaderboard counter) bottlenecks. Shard counters, use local aggregation, or specialized structures.
Q129intermediateBackup types: full/incremental/WAL?
Full snapshots + incremental + continuous WAL archiving enable PITR. Test restores—untagged backups are fantasies.
Q130beginnerORMs vs raw SQL?
ORMs speed CRUD/safety; raw/SQL builders for complex analytics/plans. Know both; measure queries generated.
Q131intermediateWhat is cardinality in indexes?
Distinct value count. Statistics guide planner. Update stats (`ANALYZE`) after large data changes.
Q132advancedGeo queries awareness?
PostGIS / Mongo 2dsphere indexes for near queries. Don't reinvent Haversine without indexes for large data.
Q133beginnerTTL indexes Mongo/Redis?
Auto-expire documents/keys—sessions, temp tokens. Ensure clock correctness and that expiry matches product semantics.
Q134advancedWrite amplification concern?
Secondary indexes, wide rows, and frequent updates increase IO. Design schemas for write patterns, not only reads.
Q135intermediateSQL `MERGE` statement awareness?
Upsert-like combine insert/update/delete based on match—supported in several DBs with vendor syntax. Postgres often uses ON CONFLICT instead.
MongoDB
104 questions
Q1beginnerWhat is MongoDB?
MongoDB is a document-oriented NoSQL database that stores data as BSON documents in collections. It is schema-flexible, horizontally scalable via sharding, and popular for JSON-like application data. You use it when document models fit better than rigid relational tables. It is not a drop-in replacement for every SQL workload—joins and multi-row transactions need careful design.
Q2beginnerDocuments vs collections vs databases?
A document is one BSON record (like a row, but nested). A collection is a group of documents (like a table, without fixed columns). A database holds collections plus metadata. Example: db users collection with { name, email } documents. Interview tip: collections do not enforce schema unless you add validation.
Q3intermediateWhat is BSON and why not plain JSON?
BSON is Binary JSON—MongoDB's storage/network format. It adds types JSON lacks: Date, ObjectId, BinData, Long, Decimal128. Binary encoding is efficient to parse. Drivers map BSON types to language types. Common mistake: treating all numbers as the same—Int32 vs Int64 vs Double matter for queries.
Q4beginnerWhat is _id and ObjectId?
Every document needs a unique _id; MongoDB auto-generates an ObjectId if omitted. ObjectId is 12 bytes: timestamp, random, counter—roughly sortable by creation time. You can use a custom _id (string, UUID) when natural keys help. Never assume ObjectIds are secret auth tokens.
Q5beginnerExplain insertOne, find, updateOne, deleteOne.
insertOne({...}) inserts a document. find(filter) returns a cursor of matches; findOne returns one. updateOne(filter, update) modifies first match—use $set to change fields. deleteOne(filter) removes first match. Prefer update operators over replacing whole documents accidentally. Always check acknowledged results in drivers.
Q6intermediateWhat is the difference between updateOne with $set and replaceOne?
$set updates specified fields and leaves others intact. replaceOne swaps the entire document (except _id) with the provided doc—missing fields disappear. Common bug: replace when you meant $set, wiping data. Use update pipeline forms for conditional updates when needed.
Q7beginnerQuery operators: $eq $gt $in $and $or $regex?
{ age: { $gt: 18 } } compares. $in matches any in a list. $and/$or combine clauses—comma in a filter is implicit AND. $regex does pattern match (prefer anchors/indexes carefully; regex can be slow). Example: { $or: [{ status: 'A' }, { qty: { $lt: 30 } }] }. Avoid leading-wildcard regex for performance.
Q8intermediateHow do you query nested fields and arrays?
Dot notation: { 'address.city': 'Austin' }. Arrays: { tags: 'mongodb' } matches if array contains value. $elemMatch matches multiple conditions on the same array element. $size checks length. Common mistake: { score: { $gt: 80 }, score: { $lt: 90 } } overwrites keys—use $and or a single range object.
Q9intermediateArray update operators: $push $pull $addToSet?
$push appends; $pull removes matching values; $addToSet pushes only if not present. $each allows multiple values. Use $pos/$sort/$slice with $push for capped arrays. Prefer $addToSet for unique tags. For complex array edits, aggregation pipeline updates are powerful.
Q10intermediateWhat is the aggregation pipeline?
A sequence of stages transforming documents: $match filters, $group aggregates, $project reshapes, $sort/$limit/$skip page, $lookup joins, $unwind expands arrays, $facet multi-pipelines. Order matters for performance—match early, use indexes. Example: [{ $match: { status: 'A' } }, { $group: { _id: '$cust', total: { $sum: '$amt' } } }].
Q11intermediateExplain $lookup like a SQL join.
$lookup performs a left outer join to another collection: { $lookup: { from: 'orders', localField: '_id', foreignField: 'userId', as: 'orders' } }. Uncorrelated lookups with pipelines allow more complex joins. Prefer embedding when data is tightly coupled and read together; $lookup when referencing makes sense. Too many lookups can hurt—design schemas for access patterns.
Q12intermediateWhat does $unwind do?
$unwind deconstructs an array field into one document per element—needed before grouping array items. Use preserveNullAndEmptyArrays to keep docs with empty arrays. Combine with $group to re-aggregate. Over-unwinding huge arrays explodes document count—filter first.
Q13advancedWhat is $facet used for?
$facet runs multiple sub-pipelines on the same input in one stage—e.g., compute total count and a page of results together. Useful for search UIs needing facets/filters plus hits. Each facet output is an array field. Keep facets efficient; they still process the input set.
Q14intermediateSingle-field vs compound vs text vs TTL vs unique indexes?
Single-field indexes one key. Compound indexes multiple keys—order matters (prefix rule). Text indexes support $text search. TTL indexes expire documents after a date field—sessions, logs. Unique indexes enforce uniqueness (e.g., email). Create indexes for common filters/sorts; too many slow writes.
Q15intermediateWhat is explain() and why use it?
db.coll.find(...).explain('executionStats') shows winning plan, index usage, docs examined vs returned. Use it to catch COLLSCAN on large collections. Look for IXSCAN and low nReturned/totalDocsExamined ratios. Always explain slow queries in staging with realistic data volumes.
Q16intermediateEmbedding vs referencing—when to choose which?
Embed when data is read/updated together, bounded size, and one-to-few (address on user). Reference by id when many-to-many, unbounded growth, or independently queried (users and orders). Hybrid is common. Design for access patterns first, not third normal form dogma.
Q17advancedName common MongoDB schema design patterns.
Attribute pattern for dynamic attrs, bucket pattern for time series-like grouping, subset pattern for hot fields, extended reference for cached denormalized bits, tree patterns for hierarchies, outlier for rare huge docs. Mentioning patterns shows senior schema thinking. Always tie choices to query/update frequency.
Q18advancedMulti-document transactions in MongoDB?
Modern MongoDB supports ACID multi-document transactions on replica sets/sharded clusters (session.withTransaction). Use for payment-like invariants across collections. They cost more than single-document atomicity—prefer single-document designs when possible. Historically MongoDB pushed single-doc atomicity; transactions closed that gap.
Q19advancedACID historically vs now for MongoDB?
Single-document operations were always atomic. Multi-document ACID arrived later (4.0+ replica set, 4.2+ sharded). Isolation and write conflicts need retries. Do not assume SQL-style transactions by default in old material. Interview: say design for single-doc first, transactions when required.
Q20intermediateWhat is a replica set?
A replica set is a group of mongod nodes with one primary for writes and secondaries replicating the oplog for HA and read scaling. Automatic failover elects a new primary. Clients use a connection string with multiple hosts + replicaSet name. Read preference controls whether reads can go to secondaries.
Q21advancedWhat is sharding?
Sharding partitions data across shards by a shard key for horizontal scale. A mongos router + config servers coordinate. Choose shard keys for even distribution and query targeting—poor keys cause hot shards. Range vs hashed keys trade locality vs balance. Not needed until a single replica set cannot handle load.
Q22beginnerMongoDB vs SQL—when to choose each?
Choose MongoDB for flexible/evolving schemas, hierarchical documents, horizontal scale, rapid iteration. Choose SQL for heavy relational integrity, complex joins, mature reporting, standardized tooling. Many systems use both (polyglot). Base the answer on access patterns and consistency needs, not hype.
Q23beginnerWhat is Mongoose?
Mongoose is a Node.js ODM: schemas, models, validation, middleware, population. Example: new Schema({ email: { type: String, unique: true } }). It adds structure on top of MongoDB's flexibility. Not required—you can use the official driver—but common in Express apps. Know when schema validation belongs in Mongoose vs MongoDB JSON Schema.
Q24intermediateMongoose middleware and virtuals?
Middleware (hooks) run pre/post save, validate, remove—hash passwords in pre('save'). Virtuals are computed fields not stored (e.g., fullName from first/last). toJSON transform can hide password hashes. Common mistake: arrow functions in middleware breaking `this` document binding.
Q25intermediateWhat does populate() do?
populate replaces stored ObjectId references with documents from another collection—like a convenience join. Under the hood it issues additional queries. Over-populating deep paths causes N+query pain—limit fields and depth. Prefer embedding or aggregation $lookup for heavy join workloads.
Q26beginnerExplain a MongoDB connection string.
mongodb://user:pass@host1:27017,host2:27017/dbname?replicaSet=rs0&authSource=admin or mongodb+srv:// for Atlas DNS seedlist. Include retryWrites and w concerns as needed. Never commit credentials—use env vars. SRV simplifies Atlas discovery of hosts.
Q27intermediateWhat is connection pooling?
Drivers maintain a pool of TCP connections to mongod/mongos so requests reuse connections instead of handshake each time. Tune maxPoolSize for concurrency; too low starves, too high overwhelms. In serverless, cold starts and pooling need special care (MongoDB serverless-friendly patterns). Always close/reuse client singleton in apps.
Q28advancedWhat are change streams?
Change streams let applications watch real-time insert/update/delete events via the oplog—useful for sync, notifications, caches. Require replica set. Resume tokens allow restarting after disconnect. Filter with aggregation pipeline. Not a full message bus replacement for all fan-out cases.
Q29intermediateGridFS briefly?
GridFS stores large files as chunks plus metadata documents when exceeding 16MB BSON limit. Useful for large binaries in MongoDB, but object storage (S3) is often better for files. Know it exists for legacy/interview awareness. Streaming APIs read/write chunk by chunk.
Q30intermediateMongoDB security: auth and roles?
Enable auth, create users with least-privilege roles (readWrite on one DB, not root). Use TLS, network IP allowlists/VPC, and Secrets Manager for credentials. SCRAM is common; x.509/LDAP in enterprises. Never expose mongod to the public internet without auth—classic breach pattern.
Q31advancedWhat is NoSQL injection via $where or operators?
If user JSON is passed directly as a filter, attackers can send { $gt: '' } to match all. $where runs JavaScript—dangerous and slow. Always validate/sanitize inputs, use parameterized driver APIs, and avoid building queries by concatenating user objects unchecked. Same class of bug as SQL injection, different syntax.
Q32beginnerBackup strategies and Atlas awareness?
Ops Manager/Cloud Manager, mongodump/mongorestore, filesystem snapshots, Atlas continuous backup/PITR. Test restores—not just backups. Atlas is MongoDB's managed cloud: replica sets, sharding, search, vector search, charts. Mention Atlas for modern ops interviews.
Q33advancedPagination: skip vs cursor?
skip(n).limit(pageSize) is simple but O(n) expensive on deep pages. Cursor/keyset pagination: filter { _id: { $gt: lastId } }.sort({ _id: 1 }).limit(n) scales better. Return nextCursor to clients. Avoid large skips in APIs.
Q34advancedWhat is collation?
Collation defines language-specific string comparison rules (case/accent). Create indexes with collation matching queries. Example: case-insensitive unique emails. Mismatch between query collation and index means index may not be used. Important for international apps.
Q35advancedSparse and partial indexes?
Sparse indexes only include docs with the indexed field—useful for optional unique fields. Partial indexes use an expression filter (e.g., only active users)—more flexible than sparse. Reduce index size and enforce uniqueness on subsets. Prefer partial for modern designs.
Q36advancedWhat is a covered query?
A covered query is satisfied entirely from the index without fetching documents—projection includes only indexed fields. Shown in explain as totalDocsExamined: 0. Design compound indexes to cover hot read paths. Great performance win for count/list patterns.
Q37advancedWrite concern and read preference?
Write concern (w:1, w:majority, j:true) controls how many nodes acknowledge a write—durability vs latency. Read preference (primary, secondary, nearest) chooses which member serves reads—stale secondary reads possible. Match to product requirements. Majority write concern is common for important data.
Q38beginnerWhat is the 16MB document size limit?
BSON documents max out at 16MB. Large blobs belong in GridFS or object storage with references. Huge embedded arrays can hit the limit—reference or bucket instead. Design reviews should estimate growth of embedded data.
Q39intermediateinsertMany and ordered vs unordered?
ordered:true (default) stops at first error; unordered continues and reports all errors—faster bulk loads. Use for ETL. Still validate data. BulkWrite combines mixed ops efficiently.
Q40advancedfindOneAndUpdate and returnDocument?
Atomically updates and returns the document—useful for queues/counters. returnDocument: 'after' (or returnOriginal:false historically) returns post-image. Combine with sort for 'claim next job' patterns. Prefer atomic operators over read-modify-write races.
Q41intermediateWhat is upsert?
update with upsert:true inserts if no match. Great for idempotent 'ensure exists' APIs. Careful: filter must identify uniquely or you create duplicates. $setOnInsert sets fields only on insert. Common in config and counters.
Q42beginnerHow does $project work?
$project includes/excludes fields, renames, and computes expressions. Exclusion of _id needs _id: 0. Later stages see only projected fields—helps reduce data. In newer versions $set/$unset are clearer for some reshaping. Prefer projecting early after match for large docs.
Q43intermediateExplain $group accumulators.
$sum, $avg, $min, $max, $push, $addToSet, $first, $last aggregate per _id key. _id can be compound: { day: '$date', country: '$c' }. Null _id groups all. Memory limits apply—allowDiskUse for huge groups. Classic interview stage.
Q44beginnerWhat is $match and why put it early?
$match filters like find. Placing it first leverages indexes and shrinks pipeline input. Later $match after $project may not use collection indexes the same way. Always push selective filters as early as possible.
Q45intermediateTTL index example?
Create index on expiresAt: 1 with expireAfterSeconds: 0 to delete when date passes, or expireAfterSeconds: 3600 on a createdAt field. Used for sessions, OTPs, logs. Background deleter is periodic—not instantaneous second-level precision. Do not use as exact real-time eviction.
Q46advancedCompound index prefix rule?
Index { a:1, b:1, c:1 } supports queries on a, a+b, a+b+c—not typically b alone or b+c. Design leftmost fields for common filters. Equality then sort/range fields ordering is a common optimization guideline. explain() verifies usage.
Q47intermediateMongoDB Atlas Vector Search awareness?
Atlas supports vector indexes for embedding similarity—used in RAG/semantic search alongside documents. Store embeddings on documents and query k-NN. Part of modern GenAI stacks with MongoDB. Compare with Pinecone/FAISS depending on ops preference.
Q48beginnerWhat is mongosh?
mongosh is the modern MongoDB shell for interactive queries and admin. Older mongo shell is legacy. Useful for debugging indexes and aggregation. Prefer migrations/scripts in app code for production changes.
Q49advancedSchema validation with $jsonSchema?
Collection validator enforces required fields/types at the database level: db.createCollection('users', { validator: { $jsonSchema: {...} } }). Complements Mongoose. Use validationLevel/action for gradual rollout. Good defense even if app bugs skip checks.
Q50advancedCapped collections?
Fixed-size collections that overwrite oldest documents—used for logs/queues historically. Natural insertion order. Limited update constraints. Change streams and TTL often replace older capped use cases. Know for interviews.
Q51advancedWhat is the oplog?
The operations log on primary used to replicate to secondaries—capped collection of ops. Change streams and point-in-time recovery rely on it. Size affects how long secondaries can be down and catch up. Ops interview depth.
Q52advancedRead concern levels?
local, available, majority, linearizable, snapshot control read isolation/visibility of majority-committed data. snapshot important inside transactions. Majority read concern avoids reading data that might roll back. Trade latency for stronger guarantees.
Q53intermediateHow do you model many-to-many in MongoDB?
Two-way referencing with id arrays, or a mapping collection for large relations. Embed only if both sides small and stable. Example: students[] on courses and courses[] on students carefully—or enrollment collection. Choose based on which direction you query most.
Q54beginnerAtomic counters with $inc?
updateOne({ _id }, { $inc: { views: 1 } }) is atomic on one document—no race like read-modify-write. Use for likes, inventory with $inc and condition qty: { $gt: 0 }. Prefer over transactions for simple counters.
Q55advancedWhat is $elemMatch in queries vs projection?
In queries, $elemMatch ensures multiple conditions apply to one array element. In projection, $elemMatch returns the first matching array element. Different use cases—say which. Common confusion in interviews.
Q56intermediateBulkWrite operations?
bulkWrite([{ insertOne }, { updateOne }, { deleteOne }]) batches mixed ops with less network round-trips. ordered flag behaves like insertMany. Essential for high-throughput migrations. Handle partial failures via write errors array.
Q57advancedHow does MongoDB sort memory work?
Large sorts may use memory limits; without index supporting sort, in-memory sort can fail or spill with allowDiskUse. Prefer indexes that satisfy filter+sort. explain() shows SORT stage. Classic performance issue.
Q58intermediateGeospatial indexes brief?
2dsphere indexes GeoJSON for $near/$geoWithin queries—stores/maps. Use for location features. Needs correct GeoJSON coordinate order [lng, lat]. Mention only if relevant; shows breadth.
Q59advancedWhat is a covered index vs compound covering projection?
If query filter and projection fields are subset of an index, MongoDB may return from index only. Include projected fields in the compound index after equality fields. Measure with explain. Great for list endpoints returning few fields.
Q60intermediateMongoose lean()?
query.lean() returns plain JS objects instead of full Mongoose documents—faster, less memory. Use for read-only API responses. You lose save()/getters unless configured. Common Express performance tip.
Q61advancedDifference between save() and updateOne in Mongoose?
save() runs validation and middleware on full document; updateOne/findOneAndUpdate bypass some middleware unless carefully configured (and runValidators option). Know which hooks fire. Security: do not pass raw req.body to updates blindly—mass assignment risk.
Q62intermediateHow to avoid mass assignment in Mongoose?
Pick allowed fields explicitly, use schema strict mode, and avoid body spreading into updates. Strict: 'throw' helps catch unknown paths. Same class of bug as Rails mass assignment. Validate with DTO/zod before DB.
Q63advancedWhat is retryable writes?
Drivers can safely retry certain write failures on failover with retryWrites=true (default in modern URI). Needs replica set. Idempotent concerns still matter for custom logic. Helps HA during primary elections.
Q64intermediateExplain primary election briefly.
If primary becomes unavailable, remaining voting members elect a new primary using heartbeats and priorities. Brief write unavailability can occur. Secondaries with newer oplogs preferred. App should handle transient errors with retries.
Q65intermediateWhat is mongodump vs filesystem snapshot?
mongodump logical export—flexible but slower for huge data. Snapshots (cloud disk/LVS) capture point-in-time files faster for large deployments; restore strategy differs. Atlas automates backup. Choose based on size and RTO/RPO.
Q66beginnerHow do you store passwords correctly with MongoDB apps?
Never store plaintext. Hash with bcrypt/argon2 in app middleware before save. Unique index on email. Do not log passwords. Encryption at rest is separate from password hashing. MongoDB should only see hashes.
Q67beginnerProjection inclusion vs exclusion?
You generally cannot mix inclusion and exclusion except for _id. { name: 1, email: 1 } or { password: 0 }. Drivers: .project({ password: 0 }). Prevents leaking sensitive fields. Always exclude secrets in APIs.
Q68advancedWhat is $merge and $out?
$out writes pipeline results to a collection (replaces). $merge can merge into existing with match modes—ETL patterns. Useful for materialized reports. Be careful in sharded environments and permissions.
Q69advancedSession and causal consistency?
Driver sessions can provide causal consistency so reads follow your writes even with secondaries under certain settings. Important in read-your-writes UX. Distinct from full serializable SQL isolation. Mention for distributed systems depth.
Q70advancedHow to design inventory decrement safely?
updateOne({ _id, stock: { $gte: 1 } }, { $inc: { stock: -1 } }) and check matchedCount. Avoid read-then-write races. Transactions if inventory spans multiple docs. Classic concurrency interview with MongoDB.
Q71advancedWhat is a hashed shard key?
Hashed keys distribute writes evenly, reducing hot shards for monotonic ids. Trade-off: ranged queries by that key become scatter-gather. Good for high insert throughput with ObjectId-like keys. Choose based on query patterns.
Q72advancedMongoDB transactions retry pattern?
TransientTransactionError and UnknownTransactionCommitResult should be retried with backoff. Drivers' withTransaction helper retries. Keep transaction bodies short—no long external HTTP inside. Avoid high contention documents.
Q73beginnerExplain $addFields vs $project.
$addFields/$set adds/computes fields while keeping existing ones. $project tends toward shaping/excluding. Prefer $addFields for clarity when enriching. Both can use aggregation expressions.
Q74intermediateWhat is a cursor and why not load all at once?
find returns a cursor that batches results—iterate instead of toArray() on huge sets. toArray() loads all into memory and can crash Node. Use streaming/batching for exports. Set batchSize thoughtfully.
Q75intermediateIndexing strategy for { status, createdAt } queries?
If you filter equality on status and sort by createdAt, compound index { status: 1, createdAt: -1 } often fits. Put equality fields first, then sort. Separate indexes may not help as much as one compound. Verify with explain.
Q76advancedWhat does hint() do?
Forces a specific index for a query—useful to test plans. Do not hardcode hints in production without strong reason; planner usually knows best. Temporary debugging tool.
Q77intermediateAtlas Search vs classic text index?
Atlas Search (Lucene-based) offers richer full-text, analyzers, facets vs simpler $text indexes. For serious search UX, Atlas Search or external Elastic is common. $text is fine for basic needs. Know the distinction.
Q78intermediateHow do you migrate schema in MongoDB?
Expand-contract: add new fields, dual-write/read, backfill scripts, remove old. No single ALTER like SQL—app handles variety. Use version field on documents. Batch updates with bulkWrite carefully.
Q79intermediateWhat is maxTimeMS?
Limits server-side query execution time—protects from runaway aggregations. Set on find/aggregate. Complements app timeouts. Useful in multi-tenant systems.
Q80advancedExplain $lookup pipeline form.
Instead of localField/foreignField, use let + pipeline with $expr for complex joins and filters. More powerful correlated subqueries. Can reduce post-filter work. Slightly more verbose.
Q81intermediateSoft deletes in MongoDB?
Set deletedAt timestamp and filter { deletedAt: null } in queries. Partial index on active docs. Harder for unique constraints—partial unique indexes help. Prefer consistent middleware to enforce filter.
Q82intermediateWhat is Decimal128 for?
Exact decimal arithmetic for money—avoid binary floating point Double for currency. Store money as Decimal128 or integer cents. Classic interview correctness point.
Q83advancedConnection best practice in serverless?
Reuse MongoClient across invocations (global cache), set maxPoolSize modestly, prefer Atlas serverless/flex as designed. Do not connect/disconnect per request. Watch for too many concurrent functions opening pools.
Q84advancedHow do you secure $regex user input?
Escape regex special characters, anchor patterns, limit length, and prefer exact match indexes when possible. Unescaped user regex enables ReDoS and full scans. Validate tightly.
Q85intermediateWhat is a time series collection?
Specialized collections for metrics/events with timeField and metaField—optimized storage/compression. Use for IoT/monitoring style data. Different from generic capped collections. Available in modern MongoDB versions.
Q86advancedExplain write conflict in transactions.
Two transactions touching same docs can abort one with write conflict—retry. Keep transactions short and reduce contention with data modeling. High conflict means redesign hot documents.
Q87advancedMongoose discriminators?
Inheritance-like schemas sharing a collection with a type key—e.g., different notification kinds. Useful for polymorphic documents. Keep base fields common. Alternative: separate collections.
Q88advancedWhat is $graphLookup?
Recursive relational traversal for trees/graphs—org charts, friends-of-friends. Can be expensive; limit depth/size. Prefer materializing paths (path string or array) for frequent tree reads.
Q89intermediateHow to count efficiently?
estimatedDocumentCount uses metadata (fast, approximate with filters none). countDocuments applies filter accurately—can be expensive. For pagination UIs, consider caching totals or approximate. Avoid counting every request on huge filtered sets.
Q90intermediateWhat is a unique compound index?
unique on { tenantId: 1, email: 1 } enforces per-tenant uniqueness. Essential for multi-tenant SaaS. Partial unique indexes can ignore soft-deleted rows. Handle duplicate key errors (11000) in app UX.
Q91beginnerDriver vs ORM/ODM responsibilities?
Driver: protocol, BSON, connection pool, CRUD. ODM (Mongoose): schema, validation, relations helpers. Keep business rules in services, not only in ODM hooks. Helps testing and portability.
Q92beginnerExplain $set vs $unset vs $rename.
$set assigns fields, $unset removes, $rename renames. Use in updates. Combining in one update is fine. Prefer $unset over setting null if you want field gone from document.
Q93advancedWhat is causal consistency vs strong consistency?
Causal: if A happens before B in your session, you observe that order. Stronger global orders cost more. MongoDB offers tunable consistency. Translate product needs into write/read concerns.
Q94intermediateHow does aggregation $limit $skip pagination work?
Same deep-skip problem as find—prefer $match on last seen key then $limit. $facet can return data page + count. For infinite scroll, keyset is best. Document trade-offs in API design interviews.
Q95intermediateMonitoring metrics you care about?
Opcounters, replication lag, connections, page faults/cache, slow query logs, CPU/disk. Atlas metrics dashboards. Alert on lag and connection spikes. Ties to production readiness answers.
Q96advancedWhat is a stuck secondary / lag?
Secondary cannot keep up applying oplog—reads stale, failover risk if oplog rolls past. Causes: undersized hardware, heavy writes, network. Scale or fix queries. Monitor constantly.
Q97intermediatePractical example: user with orders schema?
Users collection embeds nothing huge; orders reference userId and maybe embed line items (bounded). Invoice reads use $lookup or app-side join. Index orders.userId + createdAt. Classic design question—talk through access patterns.
Q98beginnerWhat is authSource in URI?
Database where user credentials live—often admin—even if you use another default DB. Mis-set authSource causes auth failures. Atlas users typically auth against admin. Document in onboarding runbooks.
Q99beginnerExplain $in vs $or for multiple values.
$in is clearer and usually better for same field multiple values: { status: { $in: ['A','B'] } }. $or is for different fields/conditions. Prefer $in when applicable for readability and planning.
Q100beginnerHow do you handle schema evolution with optional fields?
New fields optional with defaults in app/ODM. Backfill asynchronously. Readers tolerate missing fields. Version your API responses. Avoid breaking consumers with sudden required fields without migration.
Q101advancedWhat is a scatter-gather query in sharded clusters?
Query that cannot target a single shard (missing shard key) hits all shards and merges—expensive. Always include shard key in filters when possible. Motivates careful shard key choice.
Q102beginnerMongoose select and populate select?
Use .select('-password') and populate('org', 'name') to limit fields. Prevents overfetching and secret leakage. Combine with lean() for APIs. Simple habit with big security impact.
Q103intermediateGive an aggregation that joins and shapes output.
[{ $match: { active: true } }, { $lookup: { from: 'orders', localField: '_id', foreignField: 'userId', as: 'orders' } }, { $project: { email: 1, orderCount: { $size: '$orders' } } }]. Match early, lookup, project. Mentions correctness of local/foreign fields.
Q104intermediateWhen should you NOT use MongoDB?
Heavy multi-row relational constraints, complex ad-hoc joins across many entities, or teams standardized on SQL analytics may prefer Postgres. Also if you need mature SQL tooling exclusively. Pick the database for the workload.
Git
135 questions
Q1beginnerWhat is Git and how differs from GitHub?
Git is distributed version control tracking snapshots via commits locally. GitHub/GitLab are hosting and collaboration platforms atop Git. You can Git without remote entirely local history.
Q2beginnerThree states of Git files?
Modified working tree, staged index ready next commit, committed stored in object database .git. git status shows transitions.
Q3beginnergit add vs git commit?
add stages snapshot to index; commit records staged snapshot with message pointer branch moves. Unstaged changes not in commit unless add.
Q4beginnerWhat is a commit hash SHA?
Cryptographic hash of content tree parent metadata unique id immutable history reference checkout cherry-pick revert.
Q5beginnergit log useful flags?
--oneline --graph --all --decorate visual history. -p patch -S pickaxe search content change author date filter.
Q6beginner.gitignore purpose patterns?
Exclude untracked build artifacts node_modules .env from add. Glob patterns negation !keep. Commit .gitignore share team.
Q7beginnergit diff vs git diff --staged?
Working tree vs last commit. --staged index vs last commit review before commit.
Q8beginnerClone vs fork?
Clone copy repo local any remote. Fork server-side copy your account GitHub contribute upstream pull request.
Q9beginnerBranch purpose in Git?
Lightweight pointer to commit enabling parallel feature work without disrupting main. Create switch cheap merge rebase integrate.
Q10beginnergit switch vs checkout?
switch focused branch change checkout Swiss army also restore files. Modern split clearer UX Git 2.23+.
Q11intermediateHEAD detached meaning?
HEAD points commit not branch viewing history old commit experiment reattach branch or checkout branch new commits may orphan.
Q12beginnerMain vs master naming?
Industry shift main default new repos git init -b main. Rename existing requires remote coordination update CI.
Q13intermediateFast-forward merge when?
Branch tip directly ahead no divergent commits pointer moves no merge commit. --no-ff force merge commit visibility feature branch.
Q14intermediateMerge commit vs squash merge?
Merge preserves full branch history merge commit. Squash one commit main clean linear loses intermediate commits PR common.
Q15beginnerDelete branch after merge?
git branch -d merged safe -D force. Remote git push origin --delete branch cleanup stale branches policy.
Q16intermediateTracking branch upstream?
git push -u origin feature sets upstream git pull git status ahead behind without extra args.
Q17intermediateMerge vs rebase integration?
Merge joins histories merge commit preserves context. Rebase replays commits atop new base linear history rewrites SHAs never rebase public shared without coordination.
Q18advancedInteractive rebase git rebase -i?
Reorder squash fixup drop edit commits before push cleanup WIP. pick squash melds messages fixup discards message.
Q19intermediateConflict markers resolution?
<<<<<<< HEAD yours ======= theirs >>>>>>> edit desired git add mark resolved git merge --continue or rebase --continue abort --abort.
Q20intermediateWhen prefer rebase over merge?
Feature branch update before PR linear reviewable history. Shared branch many collaborators merge safer avoids force push.
Q21intermediategit cherry-pick use?
Apply specific commit hash current branch backport hotfix without merging entire branch duplicate commit new hash.
Q22intermediateRebase onto main workflow?
git fetch origin && git rebase origin/main resolve conflicts push --force-with-lease feature branch PR updated.
Q23advancedOctopus merge?
Merge multiple branches simultaneously rare monorepo release trains.
Q24advancedRerere reuse recorded resolution?
Enable rerere git records conflict resolution replay automatic similar conflicts rebase merge.
Q25beginnergit fetch vs pull?
fetch downloads remote refs objects without merge. pull fetch + merge or rebase default configurable pull.rebase true.
Q26intermediategit push rejected non-fast-forward?
Remote has commits you lack git pull rebase then push or merge. Never force push shared branch without team agreement.
Q27advancedforce push with lease?
--force-with-lease safer rejects if remote changed since fetch prevent overwrite teammate work vs --force blind.
Q28beginnerPull request code review flow?
Branch push open PR CI review comments approve merge squash rebase delete branch deploy trunk based.
Q29intermediateFork upstream sync?
Add upstream remote fetch merge or rebase main from upstream push origin main fork stay current contribute PR.
Q30beginnergit remote -v origin?
Lists fetch push URLs HTTPS SSH. Change url set-url rotate token migrate host.
Q31intermediateShallow clone depth?
--depth 1 partial history CI faster clone fetch deepen if need full history.
Q32advancedSubmodule vs subtree?
Submodule pointer separate repo commit nested update complex. Subtree vendoring merge history simpler monorepo alternative.
Q33intermediategit reset soft mixed hard?
soft keep staged and working. mixed default unstaged keep files. hard discard all dangerous lost work match commit.
Q34intermediategit revert vs reset?
revert new commit inverse safe public history. reset move branch pointer rewrite local not pushed shared.
Q35beginnergit restore file?
Restore working tree from index or commit replace checkout -- path modern split.
Q36intermediategit stash push pop?
Temporarily shelve WIP clean tree switch branch stash list apply pop drop multiple.
Q37advancedRecover deleted commit reflog?
git reflog shows HEAD moves git checkout -b rescue SHA lost commit reset hard recovery limited gc expiration.
Q38intermediategit commit --amend when?
Fix last commit message or include forgotten staged files before push. After push amend rewrites history force push required.
Q39advancedBisect find regression?
git bisect start bad good test each step git bisect good/bad binary search commit introduced bug.
Q40intermediateClean untracked files?
git clean -fd dry run -n careful deletes ignored only -x include ignored build.
Q41intermediateGit Flow vs GitHub Flow vs trunk-based?
Git Flow develop release hotfix branches heavy enterprise. GitHub Flow main feature PR simple continuous. Trunk small PRs feature flags main always deployable.
Q42intermediateConventional commits format?
feat fix docs chore scope optional breaking footer changelog automation semantic-release.
Q43intermediateSemantic versioning tags?
vMAJOR.MINOR.PATCH git tag -a v1.2.0 message push --tags release notes breaking feature fix.
Q44advancedMonorepo Git strategies?
Single repo many packages path filters CI sparse checkout CODEOWNERS per directory.
Q45intermediateRelease branch management?
Cut release/x.y stabilize cherry-pick fixes tag production merge back main.
Q46intermediateProtected branches rules?
Require PR reviews CI pass no force push CODEOWNERS dismiss stale reviews GitHub settings.
Q47advancedSigned commits GPG SSH?
Verify author identity git commit -S merge requirement policy supply chain.
Q48intermediateCODEOWNERS file?
Auto request review owners paths glob team accountability critical areas.
Q49intermediatePre-commit hook example?
Run lint test format .git/hooks/pre-commit or husky pre-commit framework block bad commit.
Q50intermediateCommit-msg hook?
Validate conventional commit pattern reject message format CI same rules local.
Q51intermediatepre-push hook CI substitute?
Run tests before push reduce broken remote not replacement full CI parallel.
Q52advancedWhat is git index staging area?
Binary cache entries paths blobs trees next commit git ls-files -s.
Q53advancedGit object types?
blob file content tree directory commit snapshot tag annotated optional.
Q54advancedPackfiles garbage collection?
git gc compress objects prune loose optimize repo size periodic maintenance.
Q55advancedWorktree multiple checkouts?
git worktree add path branch second directory same repo parallel branch work no stash switch.
Q56advancedSparse checkout?
Partial clone sparse paths monorepo only needed folders clone faster.
Q57advancedScenario: Accidentally committed secret.
Rotate secret immediately git filter-repo BFG remove history force push all clones re-clone notify security never rely only revert.
Q58intermediateScenario: Merge conflict same line two features.
Communicate team decide combined logic manual edit remove markers test both features regression add test.
Q59intermediateScenario: Wrong branch committed one commit.
git switch correct-branch git cherry-pick SHA git switch wrong git reset --hard HEAD~1 or soft move.
Q60intermediateScenario: Need undo merge not pushed.
git reset --hard ORIG_HEAD or merge commit hash before merge.
Q61intermediateScenario: PR too many messy commits.
Interactive rebase squash fixup force-with-lease push clean review single commit optional.
Q62beginnerScenario: Two developers edited same file far apart.
Git auto merge if non-overlapping if conflict manual resolve communicate.
Q63advancedScenario: Release hotfix production old version.
Branch from tag hotfix/1.2.1 fix test tag v1.2.2 merge main and release branch.
Q64intermediateScenario: Large binary should not be in Git?
Use Git LFS or external storage artifact repo history permanent even if deleted add gitignore prevent.
Q65intermediateCompare git merge --squash vs rebase merge on PR?
Squash one commit main no merge commit. Rebase merge linear preserves commits individual SHAs.
Q66intermediateScenario: Clone slow huge repo?
Shallow partial clone filter blob none sparse checkout monorepo tooling.
Q67intermediateScenario: git status shows detached HEAD after checkout tag?
Create branch at tag git switch -c release-1.2 v1.2.0 continue work or return main.
Q68advancedScenario: Collaborator force pushed rewritten history.
Fetch backup local branches communicate never force shared main reset hard origin if agree rebase local work.
Q69advancedgit reflog expire and recovery window?
Default 90 days unreachable commits gc prune sooner configure expire policy.
Q70intermediateMerge vs diff3 conflict style?
diff3 shows original base helps three-way merge understand intent configure merge.conflictStyle.
Q71advancedgit blame ignore revs file?
.git-blame-ignore-revs bulk format commit exclude cosmetic blame meaningful.
Q72intermediatePartial staging git add -p?
Hunk by hunk stage parts file granular commit split logical changes.
Q73advancedgit range diff two branches?
Compare patch series rebases review what changed between versions feature v1 v2.
Q74advancedAttributes export-ignore?
.gitattributes export-ignore exclude files archive export tarball without dev files.
Q75advancedMonorepo merge queue?
Batch PRs test combined before merge avoid semantic conflicts main bors merge queue.
Q76advancedgit maintenance schedule?
Git 2.31+ background maintenance commit-graph incremental repack performance.
Q77beginnergit blame when useful?
Find commit introduced line regression investigate author discuss context not punishment.
Q78beginnergit shortlog contributors?
Summary commits per author release notes credit `--since` date range.
Q79intermediategit archive export release?
Snapshot tree tarball zip without .git export-subst keyword expansion version.
Q80intermediategit describe tags distance?
v1.2.0-5-gabc123 commits since tag dev version semver helper.
Q81advancedgit update-index skip-worktree?
Local changes ignore config overrides without commit team file local settings rare.
Q82advancedgit sparse-checkout cone mode?
Simplified paths directories monorepo clone partial faster CI.
Q83advancedgit replace graft history?
Replace commit without rewrite history advanced archaeology rarely daily use.
Q84advancedgit send-email patch workflow?
Mailing list patches git format-patch send-email kernel style OSS contribution.
Q85advancedScenario: Accidentally added huge file commit?
Remove from history filter-repo before push if pushed team re-clone BFG.
Q86intermediateScenario: Need file from another branch without merge?
git checkout other-branch -- path/to/file single file bring current branch.
Q87intermediateScenario: Stash pop conflict?
Resolve like merge git add stash drop manually if failed stash remains list.
Q88intermediateScenario: Tag release annotate message?
git tag -a v1.0.0 -m 'Release notes' signed tag -s GPG.
Q89beginnerScenario: Compare two commits diff?
git diff commit1 commit2 or range commit1..commit2 symmetric difference.
Q90intermediateScenario: Show files changed in PR?
git diff main...feature three dot merge base symmetric diff PR review.
Q91advancedScenario: Revert merge commit?
git revert -m 1 merge_commit specify mainline parent preserve history safe.
Q92beginnerScenario: Configure user name email per repo?
git config user.email local .git/config override global different work personal.
Q93intermediateAtomic commits meaning?
One logical change bisect revert review easier mixed refactor feature split.
Q94intermediateCommit message body when?
Explain why not what wrap 72 chars reference ticket issue tracker context.
Q95beginner.gitkeep empty directory?
Placeholder track empty dirs git doesn't track dirs only files convention.
Q96intermediateMerge conflict prevention team?
Small frequent merges communicate file ownership reformat separate commit communicate.
Q97beginnergitignore global vs local?
Global OS files local project build artifacts share team template.
Q98intermediateNever commit secrets scan?
gitleaks trufflehog pre-commit scan rotate if leaked history rewrite.
Q99beginnerBranch naming convention?
Use prefixes like feature/JIRA-123-short-desc, bugfix/, and hotfix/ so teams and CI can parse branch purpose automatically. Keep names lowercase with hyphens; avoid personal names or vague labels like fix-stuff. Consistency matters more than the exact prefix strings.
Q100beginnerReview your own PR first?
Self-review diff CI green description context screenshots before requesting others.
Q101advancedWhat is an orphan branch?
`git checkout --orphan newbranch` creates a branch with no parent commits—empty index history for fresh start (GitHub pages, docs). First commit becomes a new root. Useful for separating unrelated histories.
Q102advancedSparse-checkout — when?
Checks out only a subset of files from a large monorepo (`git sparse-checkout set path`). Speeds clones/worktrees when you only need one project area.
Q103intermediateGit worktree purpose?
`git worktree add ../hotfix branch` checks out another branch in a linked working directory without recloning. Parallel PRs/hotfixes without stashing constantly.
Q104advancedWhat is `rerere`?
Reuse Recorded Resolution: remembers how you resolved a conflict and reapplies it next time. Enable `rerere.enabled`. Helpful for long-lived branches with recurring conflicts.
Q105advanced`commit --fixup` workflow?
Mark commits as fixup for a target (`git commit --fixup=abc123`) then `git rebase -i --autosquash` folds them. Keeps history clean before push/review.
Q106advancedWhat is `git range-diff`?
Compares two commit ranges (e.g., old vs new version of a patch series after rebase) showing how commits evolved. Powerful for reviewing rebased PR updates.
Q107advancedGit notes?
`git notes` attaches out-of-band metadata to objects without changing commit hashes. Rarely used day-to-day; appears in some review/CI tooling.
Q108intermediateGit LFS overview?
Large File Storage replaces big binaries with pointers; actual files on LFS storage. Prevents repo bloat. Needs LFS installed on clone; watch quotas.
Q109advancedSubmodule vs subtree?
Submodule pins external repo at a commit (separate clone semantics—easy to misuse). Subtree vendors history into monorepo paths more opaquely. Prefer package managers when possible; submodules for true multi-repo pins.
Q110intermediateSigned commits — why?
GPG/SSH signed commits prove author authenticity (`Verified` on GitHub). Required by some orgs. Keys must be protected; signing ≠ code review.
Q111beginnerConventional Commits?
`feat:`, `fix:`, `chore:` prefixes enable changelog/semver automation. `BREAKING CHANGE:` or `!` marks majors. Improves history readability.
Q112beginnerCODEOWNERS file?
Defines who must review paths (`/api/ @backend-team`). VCS enforces review requests. Keeps ownership clear in monorepos.
Q113intermediate`git blame -w`?
Ignores whitespace-only changes when attributing lines—finds real last substantive editor. Other ignore options help with refactors.
Q114intermediate`cherry-pick -x`?
Applies a commit elsewhere and records source SHA in the message (`(cherry picked from commit ...)`). Traceability for backport hotfixes.
Q115advancedRevert a merge commit with `-m`?
`git revert -m 1 <merge_sha>` specifies which parent is mainline when reverting a merge. Understand parents before running—common footgun.
Q116beginner`git reflog` lifesaver?
Records HEAD movements locally—recover lost commits after reset/rebase. Time-limited; not a remote backup.
Q117beginnerFast-forward vs merge commit?
FF moves branch pointer when no divergence. Merge commit joins divergent histories. Rebase rewrites for linear history—don't rebase shared commits casually.
Q118intermediate`git bisect` for regressions?
Binary search commits between good/bad to find culprit. Automate with `bisect run` script. Speeds debugging.
Q119beginnerDetached HEAD meaning?
HEAD points directly at a commit, not a branch—commits may become unreachable. Create a branch to keep work.
Q120beginnerProtecting main branch practices?
Require PRs, status checks, signed commits, CODEOWNERS, no force-push. Use branch protection rules.
Q121beginner`git stash` vs WIP commits?
Stash temporary local shelves; WIP commits on branches are clearer for sharing. Stash can drop accidentally—be careful.
Q122advancedThree-way merge vs rebase conflicts?
Both can conflict; rebase replays commit-by-commit (multiple conflict rounds). Understand `ours`/`theirs` swap meanings in rebase vs merge.
Q123intermediatePartial clone / shallow clone?
`--depth 1` shallow for CI speed; partial clones filter blobs. Trade history completeness for speed.
Q124beginner`git tag` annotated vs lightweight?
Annotated tags store metadata/message/signature—use for releases. Lightweight are pointers. Prefer annotated for versions.
Q125intermediateMonorepo tooling awareness?
Sparse checkout, CODEOWNERS, affected-test runners (Nx/Bazel). Git scales with discipline around large binaries (LFS).
Q126intermediate`git clean -fd` danger?
Removes untracked files/dirs—destructive. Prefer dry-run `-n` first. Don't wipe ignored secrets accidentally with `-x` unless intended.
Q127beginnerWhy `commit --amend` carefully?
Rewrites last commit hash—only if not pushed/shared or if force-push policy allows. Never amend others' commits.
Q128beginnerInterpreting `git status` ahead/behind?
Ahead: local commits to push. Behind: remote commits to pull. Diverged: both—need merge/rebase.
Q129intermediate`git restore` vs `reset`?
`restore` adjusts working tree/index files; `reset` moves branch/HEAD with modes soft/mixed/hard. Prefer restore for discard file changes clarity (modern UI).
Q130beginnerHooks: pre-commit use?
Run linters/formatters locally. Husky/pre-commit frameworks. Don't rely solely on hooks—CI must enforce.
Q131intermediateCherry-pick vs merge for hotfix?
Cherry-pick brings specific commits to release branch; merge brings whole branch history. Hotfix: cherry-pick then fix forward on main.
Q132beginnerWhat does `origin/main` mean?
Remote-tracking branch snapshot of last fetched remote main—not updated until fetch/pull. Local `main` may differ.
Q133advanced`git blame` with ignore revs?
Can ignore bulk format commits via blame ignore file—keeps attribution meaningful after reformatting.
Q134intermediateSigning tags for releases?
Annotated signed tags prove release authenticity. Pair with SBOM/changelog automation.
Q135intermediateRecover deleted branch?
Find tip via reflog and `git checkout -b branch sha`. If garbage-collected or never fetched, may be gone—push early.
Design Patterns
100 questions
Q1beginnerWhat are design patterns and why learn them for interviews?
Design patterns are named, reusable solutions to recurring software design problems. They give teams a shared vocabulary—saying 'Observer' is faster than redrawing a diagram. Interviewers test whether you pick appropriate structures and know tradeoffs. Patterns are tools, not mandatory decorations.
Q2intermediateSingleton: what, when, example, common mistake?
Singleton ensures one shared instance with a global access point—legacy config managers or a single DB connection pool object. In JS: a module exporting one object is often enough; in Python, modules are already singletons. Prefer dependency injection over hidden global Singletons for testability. Common mistake: using Singleton as a dumping ground for all app state (hidden coupling).
Q3intermediateWhy is DI often better than Singleton?
Dependency Injection passes collaborators explicitly (constructors/params), making dependencies visible and mockable in tests. Singletons hide who depends on what and complicate parallel tests. Frameworks (NestJS, Angular) wire DI automatically. Prefer DI for services; reserve true singletons for rare process-wide resources.
Q4intermediateFactory Method: what, when, example, mistake?
Factory Method lets subclasses or functions decide which concrete class to instantiate. Example: `createNotifier(type)` returning EmailNotifier or SmsNotifier in Node. Use when creation logic is non-trivial or varies by config. Mistake: a giant switch Factory that never stops growing without a clearer registry/plugin design.
Q5advancedAbstract Factory: what, when, example, mistake?
Abstract Factory groups factories for families of related objects—e.g., LightThemeWidgets vs DarkThemeWidgets producing Button+Input pairs. Useful when products must be consistent across a family. In web apps this appears less often than simple factories. Mistake: introducing Abstract Factory when one Factory Method would suffice (over-engineering).
Q6intermediateBuilder: what, when, example, mistake?
Builder constructs complex objects step-by-step, often with fluent APIs. Example: query builders (`qb.select().where().orderBy()`) or Test Data Builders in Python. Use when constructors have many optional params. Mistake: Builder for trivial 2-field objects—noise without benefit.
Q7intermediatePrototype: what, when, example, mistake?
Prototype creates objects by cloning an existing instance. JS prototypal inheritance is related conceptually; structuredClone or copy constructors appear in practice. Useful when setup cost is high and variants differ slightly. Mistake: shallow-copying nested state so clones mutate shared data.
Q8beginnerAdapter: what, when, example, mistake?
Adapter converts one interface into another clients expect—wrap a legacy SOAP client behind a modern `PaymentGateway` interface. Common when integrating third-party SDKs in Express services. Mistake: leaking adaptee types through the adapter, defeating isolation.
Q9advancedBridge: what, when, example, mistake?
Bridge separates abstraction from implementation so both can vary independently—e.g., Message abstraction with Email/SMS implementors and Urgent/Normal variants. Related to preferring composition. Mistake: confusing Bridge with Adapter (Adapter fixes incompatible interfaces after the fact; Bridge is planned decoupling).
Q10intermediateComposite: what, when, example, mistake?
Composite lets you treat individual objects and trees uniformly—UI component trees, file/folder structures, or menu nodes. React's component composition echoes the idea. Mistake: assuming every operation makes sense on both leaves and composites without careful API design.
Q11intermediateDecorator: what, when, example, mistake?
Decorator adds behavior dynamically without modifying the core object—Express middleware wrapping handlers, or Python `@lru_cache`. Use for cross-cutting concerns (logging, auth). Mistake: deep decorator stacks that obscure control flow and debugging.
Q12beginnerFacade: what, when, example, mistake?
Facade provides a simplified interface to a subsystem—e.g., `OrderService.placeOrder()` coordinating inventory, payment, and email internally. Helps UI/controllers stay thin. Mistake: Facade that grows into a God object knowing every subsystem detail.
Q13advancedFlyweight: what, when, example, mistake?
Flyweight shares intrinsic state across many objects to save memory—glyph caching in editors, or reused icon geometries. Rare in typical CRUD APIs but appears in games/graphics. Mistake: premature sharing that introduces concurrency bugs or tiny memory wins not worth complexity.
Q14intermediateProxy: what, when, example, mistake?
Proxy controls access to another object—virtual proxies lazy-load, protection proxies enforce auth, remote proxies stand in for network objects. ES6 `Proxy`, API gateways, and ORM lazy loading are cousins. Mistake: Proxy that silently hides expensive remote calls without caching or batching.
Q15intermediateChain of Responsibility: what, when, example, mistake?
Handlers pass a request along a chain until one handles it—Express middleware/`next()`, or logging level filters. Good for optional processing pipelines. Mistake: unordered chains with unclear guarantees about who runs when.
Q16intermediateCommand: what, when, example, mistake?
Command encapsulates a request as an object—supporting undo queues, job serialization, or UI actions. Example: Redux-style actions as intents; job objects in a worker queue. Mistake: turning every function call into a Command class hierarchy with no undo/queue need.
Q17beginnerIterator: what, when, example, mistake?
Iterator provides sequential access without exposing underlying representation—JS iterables/`for...of`, Python `__iter__`. Enables lazy streams. Mistake: mutating a collection while iterating without defined semantics.
Q18advancedMediator: what, when, example, mistake?
Mediator centralizes communication so components do not refer to each other explicitly—chat room servers, or Redux store as a message hub. Reduces tangled pairwise couplings. Mistake: Mediator becoming an omniscient God object.
Q19advancedMemento: what, when, example, mistake?
Memento captures and restores an object's state without violating encapsulation—undo stacks in editors, form draft snapshots. Use when you need rollback of complex state. Mistake: storing huge deep copies on every keystroke without diffing or limits.
Q20beginnerObserver: what, when, example, mistake?
Observer notifies dependents when state changes—DOM events, RxJS Observables, React context subscriptions, Node EventEmitter. Use for loosely coupled event reactions. Mistake: forgotten unsubscribes causing memory leaks, or event storms without backpressure.
Q21intermediateState: what, when, example, mistake?
State pattern replaces conditionals with objects representing states and transitions—order lifecycle Draft→Paid→Shipped. XState and finite state machines embody this. Mistake: exploding state classes for trivial two-flag logic.
Q22beginnerStrategy: what, when, example, mistake?
Strategy encapsulates interchangeable algorithms—sort comparators, payment methods, or React rendering strategies. Pass strategies as functions/objects. Mistake: Strategy proliferation when a simple if/else of two cases was clearer.
Q23intermediateTemplate Method: what, when, example, mistake?
Template Method defines an algorithm skeleton in a base class/function with overridable steps—e.g., `process()` calling `validate/parse/save` hooks. Appears in framework lifecycle methods. Mistake: fragile base classes that break subclasses on every change (prefer composition).
Q24advancedVisitor: what, when, example, mistake?
Visitor adds operations over object structures without changing element classes—AST linters walking TypeScript nodes. Useful when operations change often and structure is stable. Mistake: Visitor when the language already has pattern matching/union exhaustiveness that is simpler.
Q25intermediateMVC vs MVP vs MVVM?
MVC splits Model-View-Controller; controller handles input and updates model/view. MVP uses a Presenter that drives a passive view—testable UI logic. MVVM binds View to ViewModel observables—Angular and many frontends lean this way. Pick based on framework norms; explain data flow clearly.
Q26intermediateWhat is the Repository pattern?
Repository abstracts data access behind collection-like interfaces (`UserRepo.findById`) so domain code ignores SQL/ORM details. Aids testing with fakes and swapping persistence. Common in Clean Architecture / NestJS apps. Mistake: anemic repos that only wrap ORM one-liners without adding meaning—or repos that leak ORM types.
Q27advancedWhat is Unit of Work?
Unit of Work tracks changes across multiple repositories and commits them as one transaction. ORMs like SQLAlchemy/Entity Framework embody this. Prevents partial updates across aggregates. Mistake: long-lived units of work spanning HTTP requests and holding DB connections.
Q28beginnerExplain DI and IoC.
Inversion of Control flips who constructs dependencies—the framework/container calls you. Dependency Injection is the usual IoC technique for supplying collaborators. Improves modularity and testing. Angular and NestJS are DI-heavy; wire interfaces to implementations at composition roots.
Q29intermediatePub/Sub pattern in web systems?
Publishers emit events without knowing subscribers—SNS, Redis pub/sub, browser EventTarget, domain events. Decouples producers from consumers for scalability. Mistake: assuming delivery guarantees that your broker does not provide (at-most-once vs at-least-once).
Q30beginnerMiddleware pattern?
A pipeline of handlers each able to act, then pass control onward—Express/Koa middleware, Redux middleware, Django middleware. Excellent for cross-cutting concerns. Mistake: order-sensitive bugs and middleware that swallows errors silently.
Q31advancedCircuit Breaker pattern?
After repeated failures calling a dependency, the breaker 'opens' and fails fast for a cooldown, then probes half-open. Prevents cascade failures in microservices. Libraries like opossum (Node) implement it. Mistake: thresholds so tight that normal blips isolate healthy services.
Q32intermediateRetry pattern—what to watch for?
Retries transient failures with backoff and jitter. Use only on idempotent operations or with idempotency keys. Mistake: retrying non-idempotent POSTs causing duplicate charges, or retry storms without backoff.
Q33advancedSaga pattern?
Saga coordinates distributed transactions via a sequence of local transactions with compensations on failure—order→payment→inventory with undo steps. Used when 2PC is impractical. Mistake: missing compensations or unclear orchestration vs choreography ownership.
Q34advancedCQRS briefly?
Command Query Responsibility Segregation splits write models from read models optimized differently. Useful for complex domains with heavy read scaling. Mistake: adopting CQRS everywhere, doubling complexity for simple CRUD.
Q35intermediateAPI Gateway pattern?
A single entry point routes/authenticates/rate-limits external traffic to internal services. Handles cross-cutting edge concerns. Mistake: putting too much business logic in the gateway, creating a bottleneck monolith.
Q36intermediateWhat is BFF (Backend for Frontend)?
A BFF is an API tailored to a specific client (web vs mobile), aggregating backends to reduce chattiness. Helps SPA auth cookie patterns. Mistake: duplicating divergent business rules across BFFs without shared domain services.
Q37advancedClean / Hexagonal architecture overview?
Keep domain logic independent of frameworks/DB/UI via ports (interfaces) and adapters. Dependencies point inward toward domain. Improves testability and longevity. Mistake: endless layers and mappers for a tiny CRUD app.
Q38intermediateHow do SOLID principles link to patterns?
Strategy/OCP; Decorator/OCP; DI/DIP; Interface Segregation via focused ports; Single Responsibility via Facades/Services separation. Patterns are concrete techniques embodying SOLID ideas. Cite both together in interviews for stronger answers.
Q39beginnerWhat is a God object anti-pattern?
A class that knows/does everything—hard to test, change, and understand. Split by responsibilities and use Facades carefully. Often grows from 'just one more method' on a Utils/Service. Refactor toward cohesive modules.
Q40beginnerWhen should you NOT use a design pattern?
When the problem is simple, the team does not share the vocabulary, or the pattern adds indirection without change-resilience benefits. Prefer clear code over pattern bingo. Introduce patterns when duplication or volatility appears. Over-engineering is itself an anti-pattern.
Q41intermediateSingleton in React/Angular contexts?
Angular services with `providedIn: 'root'` are effective singletons via DI. React context or module-level stores play similar roles. Prefer framework DI over hand-rolled getInstance. Mistake: mutable global store without clear update rules.
Q42intermediateObserver vs Pub/Sub differences?
Classic Observer often has tighter subject↔observer coupling; Pub/Sub usually uses a broker/topic so publishers lack subscriber references. RxJS can express both styles. Choose based on whether you need a central event bus. Terminology overlaps in casual speech—clarify in interviews.
Q43advancedDecorator vs Proxy—how to tell apart?
Both wrap objects; Decorator emphasizes adding responsibilities, Proxy emphasizes controlling access (lazy, auth, remote). Implementation can look similar. Explain intent in interviews. Express middleware often feels like Decorator; API gateways feel like Proxy.
Q44intermediateStrategy vs State?
Strategy swaps algorithms; State swaps behavior as an object's internal state changes and transitions matter. Payment method selection is Strategy; order lifecycle is State. If transitions and invariants dominate, prefer State/FSM. If callers choose algorithm, prefer Strategy.
Q45intermediateFactory vs Abstract Factory vs Builder?
Factory creates one product; Abstract Factory creates families; Builder constructs stepwise with optional parts. Choose Factory for simple polymorphic creation; Builder for telescoping constructors; Abstract Factory for coordinated product families. Do not stack all three without need.
Q46intermediateHow does React composition relate to patterns?
React favors composition over deep inheritance—children, render props, hooks—aligning with Strategy/Decorator ideas functionally. Container/presentational splits echo MVC/MVP. Avoid forcing classical GoF class hierarchies onto React. Prefer hooks and composition APIs.
Q47beginnerMiddleware vs Chain of Responsibility?
They are closely related; middleware pipelines are a pragmatic Chain of Responsibility for HTTP. Each link can short-circuit or continue. Same design risks: ordering and error handling. Naming differs by ecosystem.
Q48advancedWhat is an anti-corruption layer?
An adapter layer translating between your domain model and an external legacy/third-party model so foreign concepts do not leak inward. Hexagonal/Clean Architecture term. Mistake: translating only halfway so domain still speaks vendor jargon.
Q49intermediateExplain layered architecture risks.
Controller→Service→Repository layers help separation but can become anemic pass-through layers with ceremony. Keep domain rules in domain services/entities, not only controllers. Skip layers that add no policy. Pragmatism beats rigid templates.
Q50intermediateWhat is dependency inversion in practice?
High-level modules depend on abstractions, not concrete DB/HTTP clients. Define a `UserStore` interface; implement with Postgres adapter. Tests inject fakes. NestJS/Angular tokens formalize this. Without DIP, domain imports ORM everywhere.
Q51intermediateNull Object pattern briefly?
Provide an object with do-nothing behavior instead of null checks—e.g., a `SilentLogger`. Reduces branching. Mistake: hiding real errors that should surface. Use sparingly for optional collaborators.
Q52advancedSpecification pattern briefly?
Encapsulate business rules as composable objects (`isPremium.and(isActive)`) for queries/validation. Useful in complex filtering domains. Mistake: overkill for a single boolean check.
Q53beginnerDTO pattern—what and pitfall?
Data Transfer Objects carry data across process/API boundaries without behavior. Prevent over-exposing domain entities. Mistake: massive DTOs mirroring entire DB tables and leaking internals.
Q54intermediateActive Record vs Data Mapper?
Active Record couples domain objects to persistence methods (Rails-like); Data Mapper (Repository) keeps persistence separate. Data Mapper tests cleaner for complex domains; Active Record is faster to start. Know tradeoffs for ORM discussions.
Q55advancedEvent Sourcing awareness?
Store state changes as events and rehydrate state by replay. Powerful audit/temporal queries; hard operationally (versioning, eventual consistency). Often paired with CQRS. Do not adopt casually for simple CRUD.
Q56beginnerWhat is the Module pattern in JavaScript?
Use closures/ES modules to encapsulate private state and export a public API. Native ES modules superseded older IIFEs. Foundation for maintainable frontends. Mistake: circular dependencies between modules.
Q57beginnerRevealing Module pattern?
An IIFE/module that returns only selected references, keeping other functions private. Historical JS pattern before ES modules. Still useful conceptually for encapsulation. Prefer ES modules in modern codebases.
Q58intermediateHow does Express demonstrate patterns?
Middleware = Chain/Decorator; routers as Facades; strategy for auth (`passport` strategies); adapters for DB drivers. Pointing this out shows applied knowledge. Frameworks are pattern catalogs in disguise.
Q59intermediateAngular patterns you should name?
DI everywhere, Observer via RxJS, Facade services over store complexity, Adapter for HTTP APIs, Singleton root services. Components as views with smart/facade services. Connect answers to GoF names when useful.
Q60beginnerWhat is Lazy Load Proxy in frontends?
Defer loading images/routes/data until needed—React.lazy, dynamic import. Improves initial load. Mistake: waterfalls of sequential lazy loads hurting UX. Pattern intent is costly-resource control.
Q61advancedInterpreter pattern awareness?
Defines a grammar and interpreter to evaluate sentences—rule engines, search query DSLs. Rare daily, appears in compiler/tooling interviews. Mistake: inventing a DSL when configuration would do.
Q62advancedMemento vs Command for undo?
Memento snapshots state; Command stores reverse operations. Commands are lighter if operations are invertible; Mementos simpler if state is small. Editors often combine both. Explain tradeoffs with memory and complexity.
Q63beginnerWhat is composition over inheritance?
Prefer assembling behaviors from smaller parts rather than deep class hierarchies. Aligns with Strategy/Decorator/Mixin/hooks. Inheritance couples hierarchies tightly. Modern React/Angular guidance strongly favors composition.
Q64intermediateFacade vs Adapter?
Adapter makes incompatible interfaces work together; Facade simplifies a whole subsystem for a client. Adapter usually wraps one foreign API; Facade orchestrates many. Both reduce coupling differently.
Q65intermediateHow do you spot over-engineering with patterns?
Interfaces with one implementation forever, factories for single classes, and directories of layers with no rules. Ask 'what change does this make easier?' If none, simplify. Senior signal: knowing when to delete abstractions.
Q66intermediateTemplate Method vs Strategy?
Template Method uses inheritance hooks inside a fixed skeleton; Strategy plugs in full algorithms via composition. Prefer Strategy for flexibility and testability. Template Method appears in framework base classes.
Q67advancedWhat is a service locator and why is it controversial?
A registry objects ask for dependencies (`ServiceLocator.get(X)`). Easier to wire sometimes but hides dependencies like Singletons—harder to test. DI constructors are usually clearer. Mention as anti-pattern-ish compared to DI.
Q68intermediateObserver memory leak example in SPAs?
Subscribing to a global store/WebSocket in a component without unsubscribing on unmount retains the component closure. Use cleanup in useEffect, takeUntilDestroyed in Angular. Classic production bug. Patterns need lifecycle discipline.
Q69advancedHow does Circuit Breaker relate to Retry?
Retries handle rare blips; breakers stop calling a sick dependency after repeated failure. Often combined: limited retries inside, breaker around. Without breakers, retries amplify outages. Resilience patterns work as a toolkit.
Q70advancedCQRS + Saga when?
Complex domains with high read throughput and multi-service workflows may combine CQRS reads with Saga-managed writes across services. High complexity cost. Justify with concrete scaling/consistency needs. Most CRUD apps should not start here.
Q71intermediateWhat is the Gateway pattern vs API Gateway?
Martin Fowler's Gateway is an object encapsulating access to an external system/resource. API Gateway is an infrastructural edge reverse proxy for many services. Related ideas at different scales. Clarify which you mean in interviews.
Q72advancedHexagonal ports and adapters example?
Port: `PaymentPort.charge(order)`. Adapter: `StripePaymentAdapter` implementing it. Domain calls the port; infrastructure provides the adapter at startup. Tests use `FakePaymentAdapter`. Keeps Stripe details out of domain logic.
Q73beginnerSOLID Single Responsibility with a pattern example?
Split a 'UserController' that validated, emailed, and wrote SQL into validator, mailer port, and repository—Facade/application service coordinates. Each type changes for one reason. Patterns help structure the split.
Q74beginnerOpen/Closed via Strategy example?
Add a new shipping calculator class implementing `ShippingStrategy` without modifying checkout conditionals endlessly. Register in a map/DI. Extends behavior with less risk to old code. OCP in practice.
Q75advancedLiskov Substitution caution with inheritance?
Subclasses must honor parent contracts—Square/Rectangle classic violation. Prefer composition when behaviors diverge. Interviewers use this to test depth beyond buzzwords. Patterns cannot fix broken hierarchies.
Q76intermediateInterface Segregation example?
Do not force clients to depend on a fat `Bird` interface with `fly()` if they only need `eat()`. Split interfaces/ports. Related to focused Repository interfaces. Prevents dummy methods and fragile mocks.
Q77intermediateDependency Inversion vs dependency injection wording?
DIP is the principle (depend on abstractions); DI is a mechanism to supply dependencies. You can violate DIP while using a DI container if you inject concretions everywhere. Aim for both: abstract ports + injection.
Q78advancedWhat is anemic domain model anti-pattern?
Objects hold data while all logic lives in services—procedural style in OO clothing. Sometimes fine for CRUD; weak for complex business rules. Rich domain models keep invariants close to data. Know when anemic is acceptable pragmatism.
Q79beginnerSpaghetti vs lasagna vs ravioli architecture metaphors?
Spaghetti: tangled control flow. Lasagna: too many rigid layers. Ravioli: modular components with clear interfaces (often preferred). Use metaphors lightly but they illustrate cohesion/coupling. Aim for ravioli with thin orchestration.
Q80intermediateHow are design patterns tested?
Strategy/DI shine because you inject fakes. Observer tests emit events and assert reactions. Avoid patterns that require heavy spinning of global Singletons in tests. Testability is a selection criterion for patterns.
Q81intermediatePrototype vs clone in JS interviews?
Explain Object.create and prototype chain for inheritance; contrast with structuredClone for data copies. Do not confuse language prototypes with the GoF Prototype creational pattern—mention both precisely. Shows careful terminology.
Q82beginnerFacade for frontend API modules?
`billingApi.charge()` wrapping fetch URLs, headers, and error mapping keeps components clean. Centralizes API changes. Mistake: UI importing raw fetch everywhere—no Facade. Simple pattern, big maintainability win.
Q83intermediateChain of Responsibility in authorization?
Pipeline checks authentication → tenant → role → resource ownership, each passing forward. Short-circuit on failure with proper status codes. Clearer than nested if pyramids. Ensure deterministic order and tests per link.
Q84advancedWhen is Flyweight relevant in web apps?
Rare—maybe sharing normalized reference data in memory on the server for huge fan-out, or canvas rendering caches. Most web apps gain nothing. Mention scarcity so you do not force it. Memory profiling should drive it.
Q85advancedCommand bus / mediator in backend frameworks?
NestJS CQRS module and similar mediate commands/queries to handlers—Mediator/Command combo. Helps structure large apps. Mistake: ceremony for five endpoints. Adopt when handler discovery and cross-cutting behaviors pay off.
Q86beginnerWhat is brittle inheritance hierarchies problem?
Base class changes break many subclasses; deep trees are hard to reason about. Patterns like Strategy/Decorator reduce need for subclassing. Prefer shallow hierarchies. Classic reason composition wins.
Q87intermediateExplain Adapter for legacy SOAP in Node.
Write `LegacyCrmAdapter` implementing `CrmPort`, internally calling SOAP with xml libs, mapping to domain types. App code never sees SOAP. Enables gradual replacement of legacy CRM. Textbook hexagonal adapter.
Q88beginnerObserver in Redux/NgRx?
Store subscriptions notify UI of state changes—Observer variant. Selectors and pure reducers add structure. Avoid over-notifying with coarse subscriptions. Connect state management answers to pattern names.
Q89intermediateState machines vs ad-hoc boolean flags?
Multiple booleans allow impossible states (`isLoading && isSuccess`). Explicit State/FSM prevents illegal combinations. Libraries like XState help. Strong interview answer for complex UI flows.
Q90beginnerHow to discuss patterns without sounding dogmatic?
Describe the problem first, then the pattern, then tradeoffs and a simpler alternative you rejected. Interviewers reward judgment. Name the pattern accurately. Show you can ship without pattern theater.
Q91advancedRepository with Unit of Work in one flow?
Open unit of work/transaction, use repositories to mutate aggregates, commit once. On error roll back all. Keeps consistency across multiple aggregates. ORM sessions often provide this implicitly—know when to be explicit.
Q92intermediateWhat is Pipes and Filters?
Data flows through independent processing stages—ETL pipelines, Angular pipes (presentation), middleware chains. Improves reuse of stages. Mistake: hidden shared mutable state between filters. Related to Chain functionally.
Q93intermediateBFF vs API Gateway—choose which?
API Gateway is shared edge for many clients; BFF is specialized per experience. Often Gateway in front, BFF behind for web/mobile shaping. Do not duplicate policy inconsistently. Clarify responsibilities to avoid logic drift.
Q94intermediateHow do patterns appear in system design interviews?
Circuit breaker, retry, gateway, pub/sub, CQRS, saga appear as resilience and integration building blocks. Tie them to requirements (consistency, scale, failure modes). Do not sprinkle names without justifying. Patterns serve quality attributes.
Q95advancedPrototype pollution vs Prototype pattern—clarify?
Prototype pattern is intentional cloning design; prototype pollution is a JS security bug mutating `Object.prototype`. Completely different topics sharing a word. Disambiguate if an interviewer mixes terms. Shows precision under pressure.
Q96beginnerGive an example of refactoring to Strategy.
Replace `if (type==='csv') parseCsv else if excel...` with `parsers[type].parse(file)` objects. Adding JSON parser becomes registration, not editing a monster function. Covered by tests per strategy. Classic clean-code move.
Q97advancedWhen Facade hides too much?
If callers need divergent workflows, a one-size Facade forces awkward parameters and flags. Split use-case application services instead. Facades should simplify common paths, not all paths. Watch for boolean parameters explosion.
Q98beginnerIterator vs Generator in Python/JS?
Generators implement Iterators lazily with `yield`—practical Iterator pattern. Useful for streaming large datasets. Mistake: holding huge intermediate lists anyway. Connect language features to pattern vocabulary.
Q99beginnerSummarize creational vs structural vs behavioral patterns.
Creational: object creation (Factory, Builder, Singleton). Structural: composition of classes/objects (Adapter, Decorator, Facade). Behavioral: interaction/responsibility (Observer, Strategy, Command). Useful map for recalling GoF. Lead with problem class, then pick category.
Q100intermediateWhat interview answer shows pattern maturity?
I use Strategy here because shipping rules change quarterly; a switch statement churned monthly. We rejected Abstract Factory as overkill—one product family only. Tests inject fake strategies. Concrete, humble, tradeoff-aware.
DSA
131 questions
Q1beginnerTwo Sum: find two indices whose values add to target.
Use a hash map of value→index while scanning once. For each number, if (target - num) is in the map, return both indices. Time O(n), space O(n). Python: def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
need = target - x
if need in seen: return [seen[need], i]
seen[x] = i
JS: const seen=new Map(); for(let i=0;i<nums.length;i++){const need=target-nums[i]; if(seen.has(need)) return [seen.get(need),i]; seen.set(nums[i],i);}
Q2beginnerReverse an array in-place.
Two pointers swap from both ends until they meet. Time O(n), space O(1). Python: `def rev(a): l,r=0,len(a)-1
while l<r: a[l],a[r]=a[r],a[l]; l+=1; r-=1`. JS: `function rev(a){let l=0,r=a.length-1;while(l<r){[a[l],a[r]]=[a[r],a[l]];l++;r--;}}`. Also `a.reverse()` in JS and `a[::-1]` creates new list in Python (not in-place).
Q3beginnerReverse a string.
Python: `s[::-1]` O(n) space for new string, or two-pointer on list(s). JS: `[...s].reverse().join('')` or loop from end. Time O(n), space O(n) for immutable strings. In interviews mention strings are immutable in Python/JS so true in-place needs char array.
Q4beginnerCheck if a string is a palindrome.
Two pointers from both ends compare chars (skip non-alphanumeric if required). Time O(n), space O(1). Python: `def is_pal(s): s=s.lower(); return s==s[::-1]` or two-pointer. JS: `function isPal(s){s=s.toLowerCase().replace(/[^a-z0-9]/g,'');return s===[...s].reverse().join('');}`
Q5beginnerCheck if two strings are anagrams.
Count character frequencies or sort both strings. Sort: O(n log n). Hash map count: O(n) time, O(1) space if alphabet fixed (26 letters). Python: `from collections import Counter; Counter(a)==Counter(b)`. JS: sort `s.split('').sort().join('')` or frequency object.
Q6beginnerValid Parentheses — match brackets ()[]{}.
Stack: push opening brackets; on closing, pop must match. Empty stack at end means valid. Time O(n), space O(n). Python: `def valid(s):
st=[]; d={')':'(',']':'[','}':'{'}
for c in s:
if c in d:
if not st or st.pop()!=d[c]: return False
else: st.append(c)
return not st`. JS equivalent uses same stack pattern.
Q7beginnerFibonacci — iterative and memoized.
Iterative O(n) time O(1) space: track prev two values. Memoized recursion O(n) time O(n) space. Python iterative: `def fib(n): a,b=0,1
for _ in range(n): a,b=b,a+b
return a`. JS: `function fib(n){let[a,b]=[0,1];for(let i=0;i<n;i++)[a,b]=[b,a+b];return a;}`. Mention overflow for large n; matrix exponentiation for O(log n).
Q8beginnerRemove duplicates from sorted array in-place.
Two pointers: write index `k` for unique position, scan `i`; copy if nums[i]!=nums[k]. Return k+1 length. Time O(n), space O(1). Works only when sorted. Python/JS same two-pointer logic.
Q9intermediateKadane's algorithm — maximum subarray sum.
Track best sum ending at current index: cur = max(x, cur+x); best = max(best, cur). This correctly handles all-negative arrays by picking the largest negative number. The oversimplified advice 'reset to 0 when negative' only applies if an empty subarray (sum 0) is allowed. Time O(n), space O(1). Same loop in Python/JS with max/Math.max.
Q10intermediateMinimum platforms at a railway station.
Sort arrival and departure arrays. Two pointers: if next arrival < next departure, need platform++ and advance arrival; else release platform and advance departure. Time O(n log n) for sort, space O(1). Classic greedy simulation after sorting events.
Q11intermediateCoin change — minimum coins for amount (DP).
dp[0]=0, dp[a]=min(dp[a-c]+1) for each coin c. Unreachable stays inf. Time O(amount×coins), space O(amount). Python: `def coinChange(coins,amt):
dp=[float('inf')]*(amt+1); dp[0]=0
for a in range(1,amt+1):
for c in coins: dp[a]=min(dp[a],dp[a-c]+1) if a>=c else dp[a]
return dp[amt] if dp[amt]!=float('inf') else -1`. JS: same DP array pattern.
Q12intermediateLongest Common Subsequence (LCS).
2D DP: if X[i]==Y[j], dp[i][j]=dp[i-1][j-1]+1 else max of neighbors. Time O(mn), space O(mn) or O(min(m,n)) optimized. Python nested loops; JS same. Backtrack matrix for actual subsequence string.
Q13beginnerMerge two sorted arrays.
Two pointers: compare heads, append the smaller, advance that pointer; then append leftovers. Time O(n+m), space O(n+m) for a new array (or O(1) extra if merging into a large enough destination from the end). Python: def merge(a,b):
i=j=0; out=[]
while i<len(a) and j<len(b):
if a[i]<=b[j]: out.append(a[i]); i+=1
else: out.append(b[j]); j+=1
return out+a[i:]+b[j:]
JS uses the same two-pointer loop with push.
Q14intermediateSubarray sum equals K (count subarrays).
Prefix sum + hash map counting frequency of prefix sums. When prefix-K seen before, add count. Time O(n), space O(n). Handles negatives unlike sliding window only-positive case. Python: `from collections import defaultdict; def subarraySum(nums,k):
pre=0; cnt=defaultdict(int); cnt[0]=1; ans=0
for x in nums:
pre+=x; ans+=cnt[pre-k]; cnt[pre]+=1
return ans`.
Q15intermediateMajority element (> n/2 occurrences).
Boyer-Moore vote: cancel different elements; survivor is candidate, verify with count. Time O(n), space O(1). Python: `def majority(a):
cand=count=0
for x in a:
if count==0: cand=x; count=1
elif x==cand: count+=1
else: count-=1
return cand`. JS same logic.
Q16intermediateNatural sort: ['A1','A10','A2'] → ['A1','A2','A10'].
Split tokens into text and numeric parts; compare numerically for digit segments. Python: `import re; def nat_key(s): return [int(t) if t.isdigit() else t.lower() for t in re.split(r'(\d+)', s)]; sorted(arr, key=nat_key)`. JS: `arr.sort((a,b)=>a.localeCompare(b,undefined,{numeric:true}))` — built-in localeCompare with numeric handles this. Time O(n log n × k).
Q17beginnerSum of even numbers — loop, filter, lambda, comprehension.
Python loop: `sum(x for x in arr if x%2==0)`. filter+lambda: `sum(filter(lambda x: x%2==0, arr))`. List comp: `[x for x in arr if x%2==0]` then sum. JS: `arr.filter(x=>x%2===0).reduce((a,b)=>a+b,0)` or for-loop. All O(n) time O(1) extra space for sum.
Q18beginnerLongest even-length word in a sentence.
Split words, filter even length, track max by length (tie-break alphabetically if asked). Time O(n), space O(n). Python: `max((w for w in s.split() if len(w)%2==0), key=len, default='')`. JS: `s.split(' ').filter(w=>w.length%2===0).sort((a,b)=>b.length-a.length)[0]`.
Q19beginnerFlatten nested array (any depth).
Recursive or iterative with stack. JS: `function flat(a){return a.reduce((acc,v)=>acc.concat(Array.isArray(v)?flat(v):v),[])}` or `arr.flat(Infinity)`. Python: recursive `def flat(a):
out=[]
for x in a:
out.extend(flat(x) if isinstance(x,list) else [x])
return out`. Time O(n) total elements, space O(depth).
Q20beginnerBinary search on sorted array.
Maintain lo, hi; mid = lo + (hi-lo)//2; go left if target smaller. Time O(log n), space O(1). Python: `def bs(a,t):
lo,hi=0,len(a)-1
while lo<=hi:
m=(lo+hi)//2
if a[m]==t: return m
if a[m]<t: lo=m+1
else: hi=m-1
return -1`. JS identical structure.
Q21intermediateRotate array right by k steps.
Normalize k%=n; reverse whole array, reverse first k, reverse rest — O(n) time O(1) if in-place. Python: `def rot(a,k):
k%=len(a); a[:]=a[-k:]+a[:-k]`. JS: splice or three reverses on array. Alternative: new array with index (i+k)%n.
Q22intermediateSliding window: maximum sum subarray of size k.
Fixed window: add nums[i], subtract nums[i-k] when i>=k, track max. Time O(n), space O(1). Python: `def max_sum_k(a,k):
cur=sum(a[:k]); best=cur
for i in range(k,len(a)): cur+=a[i]-a[i-k]; best=max(best,cur)
return best`. JS same sliding add/subtract.
Q23beginnerTwo pointers: remove duplicates from sorted linked list concept.
If array/list sorted, slow pointer marks last unique position, fast scans ahead. Extends to linked list by skipping nodes with same value. Time O(n), space O(1). Same pattern as in-place array dedup.
Q24beginnerTwo pointers: pair with given sum in sorted array.
Start lo=0, hi=n-1; if sum too small increment lo, too big decrement hi. Time O(n), space O(1). Requires sorted input. Alternative unsorted: hash set O(n).
Q25intermediateTwo pointers: container with most water.
Max area between lines at lo and hi; move pointer at shorter line inward hoping for taller boundary. Time O(n), space O(1). Greedy two-pointer proof: moving shorter side only can improve.
Q26beginnerHash map pattern: frequency count.
Single pass increment counts; use for anagrams, majority check, first unique char. Time O(n), space O(k) distinct keys. Python Counter; JS object or Map.
Q27beginnerHash map pattern: two sum and complement lookup.
Store seen values; O(1) average lookup per element. Foundation for many interview problems. Mention collision handling in real hash tables — still O(1) amortized.
Q28intermediateHash map pattern: group anagrams.
Key = sorted string or char count tuple; group values in lists. Time O(n × k log k) for sort key or O(n × k) with count key. Python: `from collections import defaultdict; groups=defaultdict(list); [groups[tuple(sorted(w))].append(w) for w in words]`.
Q29beginnerReverse a singly linked list (iterative).
Three pointers prev, curr, next; flip curr.next each step. Time O(n), space O(1). Python: `def rev(head):
prev=None
while head:
nxt=head.next; head.next=prev; prev=head; head=nxt
return prev`. JS: same while loop with .next.
Q30intermediateReverse linked list (recursive).
Base: null or single node. Recurse to end, make head.next.next = head, head.next = null. Time O(n), space O(n) call stack. Elegant but iterative preferred in production for stack overflow on long lists.
Q31intermediateDetect cycle in linked list (Floyd's algorithm).
Slow moves 1 step, fast 2 steps; if they meet, cycle exists. Time O(n), space O(1). To find cycle start: reset slow to head, move both 1 step until meet. Python/JS tortoise-hare pattern.
Q32beginnerFind middle of linked list.
Slow/fast pointers; when fast reaches end, slow is middle. Time O(n), space O(1). Used before merge sort on linked list.
Q33beginnerBinary tree inorder traversal (recursive and iterative).
Recursive: left, root, right. Iterative: stack push left chain, pop visit, go right. Time O(n), space O(h). Python/JS standard implementations. Inorder on BST gives sorted order.
Q34beginnerPreorder and postorder traversal — when used?
Preorder: copy tree, prefix expression. Postorder: delete tree bottom-up, postfix eval. All DFS O(n). Know recursive and iterative stack versions for interviews.
Q35beginnerLevel order traversal (BFS on tree).
Queue: enqueue root, dequeue, process, enqueue children. Time O(n), space O(width). Python collections.deque; JS array as queue with shift (or index pointer for O(1)).
Q36intermediateValidate Binary Search Tree.
Pass min/max bounds down recursion or inorder check strictly increasing. Time O(n), space O(h). Common mistake: only compare immediate children — must enforce entire subtree bounds.
Q37beginnerSearch in BST.
If target < root.val go left else right. Time O(h) average O(log n) balanced. Iterative while loop avoids stack.
Q38intermediateLowest Common Ancestor in BST.
If both smaller go left, both larger go right, else current node is LCA. Time O(h). Uses BST ordering property.
Q39beginnerMaximum depth of binary tree.
Recursive 1 + max(left, right). Time O(n), space O(h). DFS base case null returns 0.
Q40intermediateBFS on adjacency list — shortest path in unweighted graph.
Queue, visited set, distance array. Time O(V+E), space O(V). Python: deque + dict/set visited. JS: queue array + Set. Used for shortest steps in grid problems.
Q41intermediateDFS on graph (recursive and iterative).
Recursive: mark visited, recurse neighbors. Iterative: stack push start. Time O(V+E). Detect cycles with coloring (white/gray/black) or parent tracking in undirected graph.
Q42advancedTopological sort (Kahn's BFS or DFS postorder).
Kahn: in-degree queue, process edges reduce in-degree. Detect cycle if not all nodes processed. Time O(V+E). Used for dependency resolution, course schedule.
Q43advancedDijkstra's algorithm basics.
Min-heap priority queue; relax edges from closest unvisited node. Time O((V+E) log V) with binary heap. Non-negative weights only — mention Bellman-Ford for negatives.
Q44advanced0/1 Knapsack DP.
dp[i][w] = max(include item i, skip). Optimize to 1D array iterating w backwards. Time O(n×W), space O(W). Python nested loops; classic interview DP.
Q45beginnerClimbing stairs (Fibonacci DP).
dp[i]=dp[i-1]+dp[i-2]; ways to reach step i. Time O(n), space O(1) with two vars. Introductory DP before knapsack.
Q46advancedLongest increasing subsequence O(n log n).
Patience sorting: maintain tails array, binary search position for each element. Time O(n log n). Simpler O(n²) DP acceptable in interview if n small.
Q47intermediateHouse robber — no adjacent houses.
dp[i]=max(dp[i-1], nums[i]+dp[i-2]). Time O(n), space O(1). Linear DP pattern like max subarray variants.
Q48intermediateActivity selection / meeting rooms.
Sort by end time; greedily pick non-overlapping by earliest finish. Time O(n log n). Proves optimal via exchange argument. Same as max activities in one room.
Q49intermediateCoin change greedy vs DP — when greedy fails?
Greedy works for canonical coin systems (US coins) picking largest first. Fails for coins [1,3,4] amount 6 — greedy gives 4+1+1=3 coins, optimal 3+3=2. Always clarify whether DP minimum coins or greedy count.
Q50intermediateJump game — can reach last index?
Track farthest reachable; if i > farthest return false. Time O(n), space O(1). Greedy max reach.
Q51beginnerAssign cookies to children (greedy).
Sort both arrays; match smallest sufficient cookie. Time O(n log n). Two-pointer greedy after sort.
Q52beginnerBig O of nested loop n×n?
O(n²) time. If inner loop runs i times (triangular), still O(n²). Space O(1) unless allocating n² matrix.
Q53beginnerDifference between O(n) and O(n log n)?
O(n log n) typical of efficient sorts (merge, heap) and divide-conquer. O(n) single pass. For n=1e6, n log n ≈ 20e6 vs 1e6 — matters at scale.
Q54beginnerStack vs queue — use cases?
Stack LIFO: DFS, undo, parentheses, recursion simulation. Queue FIFO: BFS, task scheduling, buffering. Both O(1) push/pop amortized with proper implementation.
Q55beginnerTime complexity of hash map operations?
Average O(1) insert/lookup/delete; worst O(n) if many collisions. Python dict and JS Map are hash tables.
Q56intermediateWhat is amortized analysis? Example.
Average cost over sequence of operations. Dynamic array push: occasional O(n) resize but O(1) amortized. Explain why 'append is O(1) amortized' in Python lists.
Q57intermediateRecursion vs iteration — stack overflow risk?
Deep recursion O(n) stack frames can overflow (~1000-10000 limit). Iteration or explicit stack safer for large n. Tail recursion not optimized in Python/JS.
Q58intermediateStable vs unstable sort?
Stable sort preserves relative order of equal elements. Merge sort stable; quicksort typically unstable. Important when sorting objects by key with ties.
Q59beginnerIn-place vs out-of-place algorithms?
In-place uses O(1) extra space (may modify input): quicksort, heap sort. Merge sort needs O(n) auxiliary. Clarify in interviews.
Q60intermediateBest, average, worst case — quicksort?
Best/average O(n log n), worst O(n²) when pivot always min/max. Randomized pivot mitigates. Merge sort guaranteed O(n log n) but more memory.
Q61beginnerFind missing number in 1..n array.
Sum formula n(n+1)/2 minus array sum — O(n) time O(1) space. XOR all indices and values also works.
Q62intermediateFind duplicate in array of n+1 integers (1..n).
Floyd cycle detection treating indices as links — O(n) time O(1) space. Or hash set O(n) space.
Q63beginnerBest time to buy and sell stock (one transaction).
Track min price so far, max profit = max(price - min). O(n) time O(1) space. Single pass.
Q64intermediateProduct of array except self.
Prefix products left to right, suffix right to left without division. O(n) time O(1) extra if output not counted.
Q65beginnerMove zeroes to end in-place.
Two pointers: write non-zero at slow index, then fill rest with zeros. O(n) time O(1) space.
Q66intermediateFind peak element in array.
Binary search: if mid < mid+1, peak in right half else left. O(log n).
Q67intermediateMerge intervals.
Sort by start, merge overlapping. O(n log n). Common scheduling question.
Q68intermediateMaximum product subarray.
Track max and min (negative flip). O(n) similar to Kadane variant.
Q69intermediateLongest palindromic substring.
Expand around center O(n²) or Manacher O(n). Expand acceptable in 45-min interview.
Q70intermediateImplement queue using two stacks.
Amortized O(1) enqueue/dequeue: in-stack push, out-stack pop (transfer when empty).
Q71intermediateImplement stack using queues.
One queue: rotate after each push to maintain top at front. O(n) push or two-queue method.
Q72intermediateNext greater element.
Monotonic decreasing stack; pop when current larger. O(n). Pattern for daily temperatures.
Q73intermediateKth largest element.
Min-heap size k: O(n log k). Quickselect average O(n). Python heapq.nlargest.
Q74intermediateSort colors (Dutch national flag).
Three pointers low/mid/high for 0,1,2. O(n) one pass. In-place.
Q75intermediateIntersection of two linked lists.
Traverse a+b length: align pointers after switching lists. O(m+n) space O(1).
Q76beginnerAdd two numbers as linked lists.
Dummy head, carry digit, while either list or carry. O(max(m,n)).
Q77intermediateSubtree of another tree.
Compare at each node isSameTree. O(n×m). Serialization compare alternative.
Q78beginnerPath sum in binary tree.
DFS subtract target at leaf check. O(n). Variant: path sum II collect all paths.
Q79advancedSerialize and deserialize binary tree.
BFS or preorder with null markers. O(n). Tests string + tree parsing.
Q80intermediateWord search in grid (backtracking).
DFS mark visited, undo on backtrack. O(m×n×4^L). Prune early on mismatch.
Q81intermediatePermutations of array.
Backtracking swap or used array. O(n×n!). JS/Python recursive.
Q82intermediateCombination sum.
Backtracking with start index avoid reuse if required. Classic recursion.
Q83intermediateSubsets (power set).
Bitmask or backtracking include/exclude. O(n×2^n) output size.
Q84advancedLRU cache design.
Hash map + doubly linked list O(1) get/put. Frequently asked system-design-leaning DSA.
Q85intermediateImplement min stack.
Auxiliary stack tracking min or store pairs (val, minSoFar). O(1) all ops.
Q86intermediateFind all anagrams in string.
Sliding window fixed size with frequency compare. O(n).
Q87advancedLongest repeating character replacement.
Sliding window: max window when (length - maxFreq) <= k. O(n).
Q88advancedTrapping rain water.
Two pointers or precomputed max left/right arrays. O(n) time O(1) with two pointers.
Q89intermediateMaximum consecutive ones III (flip at most k zeros).
Sliding window shrink when zeros > k. O(n).
Q90advancedGrid shortest path with obstacles elimination.
BFS state (row,col,remainingK). O(m×n×k).
Q91advancedUnion-Find (Disjoint Set Union).
Path compression + rank: nearly O(1) union/find amortized. Used for connected components.
Q92advancedBellman-Ford vs Dijkstra?
Bellman-Ford O(VE) handles negative edges, detects negative cycles. Dijkstra faster non-negative only.
Q93intermediateHeap sort complexity?
O(n log n) time O(1) space if not counting output. Not stable. Build-heap O(n).
Q94intermediateCounting sort when applicable?
O(n+k) when k range small integers. Not comparison-based. Used as radix sort subroutine.
Q95intermediateTrie (prefix tree) use case?
Autocomplete, word search prefix check. O(L) insert/search per word length L.
Q96advancedSegment tree basics?
Range query/update O(log n). Overkill for interviews unless range sum frequent updates.
Q97intermediateBit tricks: set, clear, toggle, check a bit?
Set: `x | (1<<i)`; clear: `x & ~(1<<i)`; toggle: `x ^ (1<<i)`; check: `(x>>i)&1` or `x & (1<<i)`. Know sign/overflow for large shifts. Used in flags and bit DP.
Q98intermediateMatrix spiral order traversal?
Maintain top/bottom/left/right bounds; traverse right→down→left→up, shrink bounds each layer. O(m*n) time. Watch off-by-one when single row/col remain.
Q99intermediateRotate matrix 90° clockwise in-place?
Transpose then reverse each row (or layer swaps). O(n^2) time O(1) extra. Confirm direction (clock vs counter).
Q100intermediateDutch National Flag problem?
Three-way partition (e.g., 0/1/2) with low/mid/high pointers in one pass. Classic for sort colors. O(n) time O(1) space.
Q101advancedReservoir sampling brief?
Sample k items uniformly from a stream of unknown length. For k=1: keep i-th item with prob 1/i. Useful when data doesn't fit memory.
Q102advancedUnion-Find (DSU) more detail?
Nearly O(1) with path compression + union by rank/size. Supports connectivity, Kruskal MST, cycle detection in undirected graphs. `find` recursively flattens parents.
Q103advancedDijkstra more carefully?
Non-negative weights: min-heap of distances, relax neighbors. O((V+E) log V) with binary heap. Cannot handle negative edges—use Bellman-Ford. Don't mark visited before popping best dist when using decrease-key alternatives carefully.
Q104advancedTopological sort Kahn's algorithm?
Compute indegrees; queue zeros; pop and reduce neighbors' indegrees. If output size < |V|, cycle exists. O(V+E). Used for course schedule/build order.
Q105advancedBinary lifting brief?
Precompute 2^k parents for trees to answer LCA/k-th ancestor in O(log n) after O(n log n) preprocess. Common in competitive programming interviews at advanced level.
Q106advancedMo's algorithm awareness?
Offline reorder range queries into blocks to add/remove elements efficiently—sqrt decomposition idea. Awareness-level for advanced interviews; rarely needed in industry CRUD roles.
Q107advancedSliding window maximum with deque?
Monotonic decreasing deque of indices; front is max for window. Pop back while smaller than new; pop front if outside window. O(n). Classic hard interview pattern.
Q108advancedBit DP awareness?
DP where mask bits represent subset state—TSP-like O(n^2 2^n). Useful when n≤20. Mentions show algorithmic breadth.
Q109advancedKMP vs Rabin-Karp awareness?
KMP: prefix table for O(n+m) exact match without scanning back. Rabin-Karp: rolling hash, good average, used for multi-pattern/plagiarism vibes; watch collisions. Know when `strstr`/language libs suffice.
Q110advancedSegment tree range sum?
Tree over array ranges supporting query/update in O(log n). Build O(n). Alternative Fenwick for prefix sums. Used when many range queries with updates.
Q111beginnerCount set bits?
Brian Kernighan: `while n: n&=n-1; cnt+=1` O(popcount). Or hardware `__builtin_popcount`. Interview classic.
Q112beginnerCheck power of two?
`n>0 and (n & (n-1))==0`. Only one bit set.
Q113intermediatePrefix XOR trick?
XOR[l..r] = prefix[r] ^ prefix[l-1]. Subarray XOR queries in O(1) after O(n) preprocess.
Q114intermediateKadane variant for indices?
Track start when resetting current sum; update best range when improving best sum. Still O(n).
Q115intermediateMonotonic stack next greater element?
Iterate with stack of decreasing values; pop when current greater. O(n). Foundational for many array problems.
Q116advancedBinary search on answer pattern?
When predicate monotonic (can finish with mid capacity?), binary search the numeric answer. Validate with greedy/simulation. Classic allocation problems.
Q117intermediateTrie use cases?
Prefix search, autocomplete. O(length) insert/search. Memory heavy; compressed tries help.
Q118beginnerHeap vs sorted array?
Heap: O(log n) push/pop, O(1) peek extreme. Not good for arbitrary deletes without handles. Use for top-k/streaming medians with two heaps.
Q119beginnerGraph BFS vs DFS applications?
BFS shortest unweighted path/levels; DFS cycle detection/toposort/components. Know adjacency list representation.
Q120advanced0/1 BFS awareness?
Deque: weight 0 edges push front, weight 1 back—shortest path when edges only 0/1. Niche but elegant.
Q121advancedDifference array technique?
Range increments via + at L and - at R+1 then prefix rebuild. O(n+q) for many range add queries.
Q122advancedTwo heaps median?
Max-heap lower half, min-heap upper half; rebalance sizes. O(log n) updates, O(1) median.
Q123advancedCoordinate compression?
Map large sparse values to ranks for Fenwick/segment trees. Preserve order via sorting unique values.
Q124intermediateBacktracking template?
Choose → explore → unchoose; prune early. Used for subsets/permutations/sudoku. Exponential—needs pruning.
Q125intermediateGreedy choice property caution?
Greedy works when local optimal leads to global (activity selection, Huffman). Prove or provide counterexample—interviewers probe this.
Q126advancedRolling hash pitfalls?
Collisions possible—use double hash or verify substrings. Mod overflow care in some languages.
Q127advancedFenwick tree vs segment tree?
Fenwick simpler for prefix sums/point updates; segment tree more general (any mergeable range op, lazy propagation).
Q128intermediateCycle detection Floyd tortoise-hare?
Two pointers different speeds in linked list; meeting ⇒ cycle; reset one to head to find entrance. O(1) space.
Q129intermediateTop-K with heap?
Maintain min-heap of size k for K largest streaming. O(n log k). Quickselect average O(n) alternative.
Q130beginnerAdjacency matrix vs list?
Matrix O(1) edge check O(V^2) space; list O(V+E) space better for sparse graphs. Prefer lists generally.
Q131intermediateExplain amortized O(1) dynamic array?
Occasional resize copies cost spread across pushes—geometric growth ⇒ amortized O(1) append.
Behavioral & Agile
100 questions
Q1beginnerHow should you structure 'Tell me about yourself'?
Use a tight present–past–future arc in under two minutes: current role and stack, relevant past impact with one metric, then why this role/company fits next. Emphasize full-stack outcomes, not a resume recital. End by inviting their focus area. Practice aloud so it sounds natural, not memorized.
Q2beginnerHow do you answer strengths without sounding generic?
Pick 1–2 strengths backed by a short example—e.g., owning production incidents end-to-end, or learning unfamiliar APIs quickly. Tie the strength to the job description. Avoid laundry lists. Offer a weakness plan later if they ask—do not volunteer unrelated flaws.
Q3beginnerHow do you discuss weaknesses maturely?
Choose a real, non-critical weakness and show active mitigation—e.g., over-polishing UI → now timebox and seek early feedback. Never say 'I work too hard' or cite a core job requirement as your weakness. Interviewers grade self-awareness and growth. Keep it concise.
Q4beginnerHow do you answer 'Why this company?'
Cite specific products, engineering challenges, domain, or culture details you researched—not 'you are prestigious.' Connect your skills to their problems. Show genuine curiosity with one thoughtful question ready. Generic praise fails senior screens.
Q5beginnerHow do you explain why you are leaving your current role?
Stay positive and forward-looking: growth, scope, tech, or mission fit. Avoid dumping on managers or salary-only framing early. Brief and professional beats long grievances. Align the reason with what the new role offers.
Q6intermediateTell a conflict-with-teammate story (STAR).
Situation: disagreement on approach; Task: ship safely on time; Action: listened, data/prototyped options, compromised or escalated with facts; Result: shipped and relationship intact. Emphasize respect and customer impact. Never portray yourself as always right.
Q7intermediateHow do you talk about a failure?
Pick a real failure with stakes, own your part without self-flagellation, and highlight fixes (tests, runbooks, process). Show learning transferred to later success. Avoid blaming only others or choosing a trivial 'failure.' Honesty plus systems thinking wins.
Q8intermediateDescribe working under a tight deadline.
Explain how you clarified must-haves vs nice-to-haves, communicated risk early, parallelized work, and protected quality for critical paths. Mention tradeoffs you made explicitly with stakeholders. Results and calm communication matter more than heroics. Deadlines are scope/priority problems as much as coding speed.
Q9advancedDisagreement with your manager—how do you answer?
Show you raised concerns with data, proposed alternatives, then committed to the decision once made (unless unethical). Loyalty and independent judgment both matter. Avoid insubordination theater or silent resentment stories. Good endings include trust preserved.
Q10intermediateWhat does ownership look like in your stories?
You spotted a gap, drove it without being asked, coordinated across roles, and measured outcome. Ownership includes follow-through after release—monitoring and fixes. Contrast with 'I only did my tickets.' Companies hire owners for ambiguous problems.
Q11intermediateHow do you describe mentoring experience?
Give a concrete mentee situation: pairing, review feedback style, or learning plan, and what improved for them and the team. Mentoring is multiplying impact, not gatekeeping. If junior, describe peer mentoring or documentation you wrote. Humility beats status.
Q12beginnerLearning a new technology fast—story structure?
Explain goal, how you scoped a thin vertical slice, used official docs/examples, sought a buddy review, and delivered something real. Mention timebox and what you still planned to deepen. Interviewers want learning agility proof. Avoid claiming mastery overnight.
Q13intermediateProduction bug story essentials?
Detection (alert/user), containment, root cause, fix, and prevention (test/monitor). Quantify impact if possible. Stay calm and factual. This is often the highest-signal behavioral question for backend/full-stack roles.
Q14beginnerWhat is the STAR method?
Situation, Task, Action, Result—a structure for behavioral answers. Keep Situation/Task short; spend most time on your Actions and measurable Results. Practice converting rambling stories into STAR. Interviewers silently grade completeness.
Q15beginnerWhat are SMART goals?
Specific, Measurable, Achievable, Relevant, Time-bound. Used in performance reviews and sprint goals. Example: reduce p95 API latency from 800ms to 400ms by June 30 via indexing and caching. Shows structured planning literacy. Avoid vague 'improve performance' goals.
Q16intermediateHow do you work effectively on a remote team?
Over-communicate async (clear PRs, docs), overlap hours for sync when needed, default to written decisions, and be explicit about blockers. Build trust with reliability and visible progress. Mention tooling: tickets, Slack norms, video for conflict. Remote fails from silence, not distance.
Q17intermediateClient or stakeholder communication tips?
Translate technical risk into business impact and options, not jargon. Confirm requirements in writing, send interim updates before surprises, and manage expectations on estimates. Listen for underlying goals. Empathy plus clarity builds long-term trust.
Q18intermediateWhat if your estimate was wrong?
Own it early, explain what changed, re-forecast with a revised plan, and offer scope cuts. Do not hide slippage until the deadline. Retrospect on why (unknowns, blockers) and improve estimation hygiene. Mature engineers revise estimates; weak ones go dark.
Q19intermediateHow do you push back on scope?
Acknowledge the goal, present tradeoffs (time/quality/risk), propose MVP vs later phases, and let stakeholders choose knowingly. Bring data or spikes when uncertainty is high. Pushback is partnership, not obstinance. Document the decision.
Q20beginnerReceiving critical feedback—model answer?
Listen without interrupting, restate to confirm, ask clarifying examples, and share what you changed afterward. Avoid defensiveness. Strong candidates show a feedback→behavior loop. Pick a real example with a positive outcome.
Q21intermediateLeadership without a title—examples?
Facilitating design discussions, improving CI, onboarding docs, driving an incident, or unblocking peers. Leadership is influence toward outcomes. Quantify team benefit when possible. Companies need this at every level.
Q22beginnerWhat is Scrum at a high level?
An Agile framework with roles (Product Owner, Scrum Master, Developers), events (Sprint, Planning, Daily Scrum, Review, Retro), and artifacts (Product Backlog, Sprint Backlog, Increment). Time-boxed Sprints deliver potentially shippable increments. Empiricism: transparency, inspection, adaptation.
Q23beginnerScrum roles explained briefly?
Product Owner maximizes product value and manages the backlog. Developers deliver the increment and own how to build. Scrum Master coaches the process and removes impediments. Avoid equating Scrum Master with project manager solely. Clarity of accountability matters.
Q24beginnerScrum ceremonies / events?
Sprint Planning selects sprint work; Daily Scrum inspects progress toward the sprint goal; Sprint Review inspects the increment with stakeholders; Retrospective improves team process. Sprint itself is the container. Time-boxes keep events focused.
Q25beginnerScrum artifacts?
Product Backlog is ordered work for the product; Sprint Backlog is the plan for the sprint; Increment is the sum of completed backlog items meeting the Definition of Done. Commitments: Product Goal, Sprint Goal, DoD. Artifacts create transparency.
Q26beginnerWhat is Kanban?
A flow method visualizing work on a board, limiting WIP, and optimizing cycle time—fewer prescribed roles/ceremonies than Scrum. Great for support/ops or continuous flow teams. Measure lead time and bottlenecks. Can complement Scrum (Scrumban).
Q27beginnerSprint Planning purpose?
The team forecasts what can be done and how, forming a Sprint Goal. PO clarifies priority; developers probe feasibility. Avoid stuffing more than capacity. Good planning reduces mid-sprint thrash.
Q28beginnerSprint Review vs Retro?
Review inspects the product increment with stakeholders and adapts the backlog. Retro inspects team process/relationships/tools and agrees improvements. Both are inspection/adaptation, different subjects. Skipping retros stagnates culture.
Q29intermediateWhat is INVEST for user stories?
Independent, Negotiable, Valuable, Estimable, Small, Testable. A checklist for healthy backlog items. Large vague stories fail INVEST and block flow. Split until you can demo value within a sprint.
Q30beginnerWhat are acceptance criteria?
Conditions that must be true for a story to be accepted—often Given/When/Then examples. Align PO, devs, and testers before coding. Reduce rework and clarify edge cases. Living part of the story, not an afterthought.
Q31intermediateDefinition of Done vs acceptance criteria?
DoD is a team-wide quality checklist for any increment (tests, review, docs, deployed to env). Acceptance criteria are story-specific behaviors. Both must pass. Clear DoD prevents 'almost done' debt.
Q32intermediateVelocity and story points—what are they for?
Story points relative-size estimates; velocity is points completed per sprint used for forecasting—not a performance KPI to game. Planning Poker builds shared understanding. Never compare velocities across teams. Use for planning capacity, not pressure.
Q33beginnerWhat is Planning Poker?
A consensus estimation technique using cards (often Fibonacci) where teammates reveal estimates simultaneously to avoid anchoring. Discuss outliers to surface hidden complexity. Improves shared mental models. Facilitator keeps discussion time-boxed.
Q34beginnerAgile vs Waterfall?
Waterfall sequences requirements→design→build→test with late feedback; Agile delivers iteratively with continuous feedback and change embrace. Waterfall can fit fixed contractual hardware-like scopes; product software usually benefits from Agile. Hybrid approaches exist—focus on feedback loops.
Q35beginnerDaily standup purpose?
Inspect progress toward the Sprint Goal and synchronize—historically yesterday/today/blockers, but goal-focused updates beat status theater. It is for the team, not a manager report. Raise impediments quickly. Keep it short; take deep dives offline.
Q36beginnerWhat is an impediment in Scrum?
Anything blocking the team from progressing—access, unclear requirements, environment issues, dependencies. Scrum Master helps remove them; developers surface them early. Tracking impediments visibly helps. Silence makes impediments chronic.
Q37intermediateWhat is a CI culture?
Small frequent integrations to main with automated builds/tests, fast feedback, and a norm that broken main is everyone's emergency. Reduces long-lived branches and merge hell. Psychological safety to fix quickly matters. CI is social as much as technical.
Q38intermediateCode review etiquette you follow?
Be kind and specific, prefer questions over commands, praise good patterns, focus on maintainability/risks not nit style when linters exist, and respond promptly. Authors keep PRs small and contextualized. Reviews are teaching/learning, not gatekeeping ego.
Q39intermediatePair programming benefits and when?
Two engineers at one problem improve design quality, share context, and catch bugs early—useful for complex/risky areas or onboarding. Cost is two salaries on one task—use deliberately. Remote pairing needs good tooling. Rotate pairs to spread knowledge.
Q40advancedHow do you talk about technical debt with stakeholders?
Translate debt into risk, velocity cost, and incident probability—not 'code is ugly.' Propose a percentage capacity or dedicated iterations with measurable outcomes. Show examples of past debt causing delay. Partner, do not lecture.
Q41beginnerNotice period / joining date—how to handle?
State your contractual notice honestly, any flexibility, and preferred start date. Do not resign until you have a written offer you accept. Be reliable—companies value candidates who exit professionally. Align timelines early in process.
Q42intermediateHow do you answer salary expectations at a high level?
Research market bands for role/level/location, give a reasoned range, and express flexibility for total compensation (bonus, equity, benefits). Deflect premature low anchoring when possible until you understand scope. Be honest and professional—no ultimatum games. Know your walk-away number privately.
Q43beginnerExplaining gaps in your resume?
Be truthful and brief: learning, caregiving, health, layoff—without oversharing. Emphasize how you stayed current (projects, courses) and readiness now. Confidence without defensiveness. Hiring managers care about trajectory more than perfect timelines.
Q44intermediateStrengths as a full-stack engineer?
End-to-end ownership across UI, API, and data; empathy for both UX and operational constraints; ability to debug across tiers; pragmatic tradeoffs. Give a story spanning frontend and backend. Avoid claiming shallow knowledge of everything—show depth where it counts.
Q45intermediateHow do you prioritize tasks when everything is urgent?
Clarify impact/urgency with stakeholders, expose constraints, sequence by risk reduction and dependencies, and communicate what slips. Use written priority lists. Escalate conflicts rather than silently guessing. Priority is a leadership conversation.
Q46intermediateDescribe a time you improved a process.
STAR with baseline pain (slow deploys, flaky tests), action (automation/docs), and measurable result. Process improvements scale teams. Prefer examples you personally drove. Continuous improvement is Agile heart.
Q47intermediateHow do you handle ambiguous requirements?
Ask clarifying questions, propose assumptions in writing, build a thin spike/prototype, and confirm with PO/users early. Document decisions. Ambiguity is normal—paralysis is optional. Show comfort operating without perfect specs.
Q48beginnerTeamwork story when you were not the hero?
Highlight supporting a teammate's success, sharing credit, and enabling outcomes. Interviewers detect glory-hogging. Collaboration includes reviewing, unblocking, and celebrating others. Mature narrative beats lone genius myths.
Q49advancedHow do you prepare for on-call / incident rotations?
Know runbooks, dashboards, escalation paths, and recent changes. Practice game days. After incidents, blameless retros and fixes. Mentions show production maturity. Reliability is a behavioral topic too.
Q50intermediateWhat is a blameless postmortem?
Focus on systemic causes and improvements without punishing honest mistakes. Encourages reporting and learning. Still assign owners for action items. Culture signal for healthy engineering orgs.
Q51beginnerHow do you say no politely at work?
Acknowledge the request, explain constraints, offer alternatives or timelines, and confirm priority with the requester/PO. 'No' without options feels like stonewalling. Protects focus and quality. Document agreements.
Q52intermediateCross-functional collaboration examples?
Working with design on feasibility, QA on test plans, DevOps on deploy, product on scope. Show translation across languages of each role. Full-stack roles live here. Concrete rituals (design critiques, three amigos) help.
Q53beginnerWhat motivates you as an engineer?
Pick authentic drivers—user impact, craftsmanship, learning, mentoring—and tie to the role. Avoid sounding purely mercenary in early interviews. Align motivation with company stage (startup pace vs platform depth). Short and sincere.
Q54beginnerWhere do you see yourself in 3–5 years?
Show growth ambition aligned with paths they offer—technical depth, architecture, or leadership—without rigid entitlement. Emphasize contributing impact first. Flexibility reads as maturity. Research their ladder if published.
Q55advancedHow do you handle competing PO and engineering priorities?
Make tradeoffs visible with risk/effort, suggest sequencing, and escalate unresolved conflicts to the right forum. Do not silently ignore either side. Healthy tension is normal. Seek win-wins via MVP slicing.
Q56intermediateExplain spike stories.
Time-boxed research tasks to reduce uncertainty before committing to delivery estimates. Outcomes are learning, not always production code. Prevents fake precision on unknowns. Close spikes with documented recommendations.
Q57intermediateWhat is WIP limit thinking?
Limiting work in progress improves flow and reduces multitasking waste—Kanban core. Personal WIP limits help focus. Too much WIP hides bottlenecks. Mention if asked about productivity systems.
Q58intermediateDefinition of Ready (brief)?
A checklist before a story enters a sprint—clear AC, dependencies known, estimable, designs available if needed. Prevents starting unready work. Complements Definition of Done. Optional but useful team agreement.
Q59beginnerHow do you contribute in retrospectives?
Bring specific observations, suggest experiments not complaints only, and volunteer for improvement actions. Follow through next sprint. Safety to speak matters—model constructive candor. Retros without actions are theater.
Q60intermediateDescribe giving constructive feedback to a peer.
Private, timely, behavior-specific, impact-focused, with offer to help. Avoid personality attacks. Follow company guidelines. Shows emotional intelligence for senior roles.
Q61beginnerHow do you onboard onto a new codebase quickly?
Run the app, map architecture docs, fix a small bug, ask for a guided tour, and note tribal knowledge into docs. Deliver a tiny visible win early. Communication with teammates accelerates more than solo reading forever.
Q62intermediateHandling production pressure emotionally?
Breathe, follow incident process, communicate status, escalate early, and defer blame analysis until stability. Afterward, rest and retro. Interviewers want composure. Panic stories without learning hurt you.
Q63beginnerWhat questions do you ask at end of interview?
Ask about team rituals, deployment frequency, on-call, success in first 90 days, and engineering challenges—not only perks. Tailor to what was not covered. Good questions signal seriousness. Avoid solely salary at first chance unless they open it.
Q64beginnerExplain Agile manifesto values briefly.
Individuals/interactions over processes/tools; working software over comprehensive docs; customer collaboration over contract negotiation; responding to change over following a plan. Items on the right still matter; left is valued more. Philosophy behind frameworks.
Q65beginnerWhat is a product backlog refinement?
Ongoing grooming: clarifying, splitting, estimating upcoming items so planning is smoother. Keeps backlog healthy. Involves PO and developers. Prevents sprint planning marathons.
Q66intermediateHow do you measure personal productivity responsibly?
Outcomes and impact over lines of code or ticket count. Cycle time and quality matter. Gaming velocity harms trust. Reflect in 1:1s with evidence of delivered value.
Q67intermediateStory about automating toil?
Identify repetitive manual work, automate with scripts/CI, measure time saved, document usage. Shows DevOps mindset. Even small automations compound. Prefer examples still used by the team.
Q68intermediateHow do you balance quality vs speed?
Risk-based testing: harden irreversible/payment paths more; spike prototypes lighter. Agree quality bar via DoD. Communicate when speed increases risk. Professionals make tradeoffs explicit.
Q69advancedDescribe a time you influenced technical direction.
Used a spike/benchmark/RFC to persuade with evidence, sought feedback, and landed consensus. Influence without authority is senior skill. Share the decision record outcome. Avoid steamrolling narratives.
Q70intermediateWhat is psychological safety in teams?
Belief you can speak up with ideas, questions, and mistakes without punishment. Enables retros, incident learning, and innovation. Leaders model curiosity. Mention how you help create it.
Q71advancedHandling a teammate missing deadlines?
Check in privately for blockers, offer help, surface risks early to the team/PO, and avoid public shaming. Focus on system fixes if chronic. Empathy plus accountability. Manager escalation if needed after support attempts.
Q72intermediateHow do you document decisions (ADRs)?
Architecture Decision Records capture context, decision, and consequences briefly in repo. Helps future teammates. Lightweight over novel-length docs. Good Agile documentation practice.
Q73beginnerExplain customer demos in Sprint Review.
Show working software, gather feedback, adapt backlog. Prefer live increments over slideware. Celebrate learning even if scope shifted. Closes the feedback loop with stakeholders.
Q74advancedWhat is mob programming awareness?
Whole team collaborates on one task with rotating driver—intense knowledge sharing. Useful for hard problems or standards alignment. Costly if overused. Related to pairing at team scale.
Q75intermediateHow do you approach estimation uncertainty?
Use ranges, confidence levels, spikes, and split work. Call out assumptions. Re-estimate when new info arrives. False precision is worse than honest uncertainty. Stakeholders prefer early truth.
Q76intermediateSwitching contexts between bugs and features?
Agree priority policy with PO (e.g., sev-1 interrupts), batch lower bugs, protect focus time. Communicate switches' cost. Personal systems (timeboxing) help. Shows realism about interrupt-driven work.
Q77intermediateWhat does 'servant leadership' mean for Scrum Masters?
Lead by enabling the team—removing impediments, coaching, facilitating—not commanding tasks. Developers self-manage how to achieve goals. Interview relevance if you facilitated Agile. Contrast with command-and-control PMs.
Q78beginnerDescribe continuous learning habits?
Share concrete habits: reading RFCs, side projects, kata, conference talks, teaching others. Tie to a recent skill acquired. Consistency beats intensity bursts. Employers invest in learners.
Q79advancedHow do you handle ethical concerns (privacy, wrongdoing)?
Raise through proper channels, refuse illegal instructions, document, and escalate. User trust and law outrank features. Keep answer principled and calm. Rare but integrity-testing question.
Q80beginnerExplain MVP in product terms?
Minimum Viable Product is the smallest release that validates learning with real users—not a buggy half-product without value. Scope ruthlessly around the hypothesis. Agile delivery pairs with MVP thinking. Avoid building gold-plated v1.
Q81beginnerWhat is scope creep and how do you manage it?
Uncontrolled growth of requirements mid-sprint/project. Manage via backlog, change control, Sprint Goal protection, and tradeoff conversations. Document new requests for later. Protects delivery credibility.
Q82beginnerHow do you celebrate team success?
Credit peers publicly, note specific contributions, and reflect learnings. Psychological positivity aids retention. Mentions culture fit. Do not only highlight yourself in group wins.
Q83intermediateBehavioral red flags interviewers notice?
Blaming everyone else, inability to name failures, disrespecting PMs/QA, secrecy about mistakes, and no questions. Avoid these patterns. Self-awareness and collaboration signals matter as much as tech. Prepare accordingly.
Q84beginnerHow do you manage career 1:1s?
Bring agenda: feedback, goals, blockers, growth opportunities. Follow up on action items. Own your development plan. Shows proactivity managers love.
Q85intermediateExplain bus factor and how you reduce it?
Bus factor is how many people can be hit by a bus before a system stalls. Reduce via pairing, docs, shared ownership, and avoiding silos. Healthy teams raise bus factor intentionally. Good ownership culture topic.
Q86advancedWhat is a RACI matrix awareness?
Responsible, Accountable, Consulted, Informed—clarifies decision roles on projects. Helps cross-team ambiguity. Use lightly; do not bureaucracy everything. Useful when asked about stakeholder management.
Q87advancedHow do you adapt communication to executives vs engineers?
Executives need outcomes, risk, options, asks; engineers need details and constraints. Same truth, different altitude. Misaligned altitude causes confusion. Full-stack leads practice both.
Q88intermediateDescribe a stretch goal you pursued.
Something beyond core duty—performance initiative, accessibility sweep, mentoring guild—with results. Shows initiative. Keep realistic. Tie to business or team benefit.
Q89intermediateHow do you stay calm when requirements change late?
Acknowledge, assess impact on Sprint Goal, renegotiate scope, and update plans visibly. Emotional flexibility is Agile. Vent privately, solve publicly. Change is expected; surprise without communication is the problem.
Q90intermediateWhat is technical discovery / design spike in Agile?
Exploration to de-risk architecture before committing many stories. Outputs options and recommendations. Prevents painting into corners. Time-box strictly.
Q91intermediateHow do you ensure accessibility is not forgotten?
Include a11y in DoD/AC, linting, reviews, and QA checklists. Advocate early with design. Share user impact stories. Behavioral commitment to inclusive quality.
Q92intermediateExplain handshake between QA and developers in Agile?
Collaborate on AC early (three amigos), automate regression, explore edge cases together, and avoid 'throw over wall' culture. Quality is team-owned. Respectful partnership stories score well.
Q93beginnerHow do you handle an interview coding mistake mid-way?
Narrate recovery: tests, fix approach, tradeoffs. Interviewers grade debugging composure. Silence or panic hurts more than the bug. Ask clarifying questions early to reduce mistakes.
Q94beginnerWhy do companies ask behavioral questions?
Past behavior predicts future behavior; they probe collaboration, ownership, and culture add. STAR evidence beats slogans. Prepare 6–8 flexible stories covering conflict, failure, leadership, and impact. Rehearse aloud.
Q95intermediateMap one story to multiple questions?
A strong production incident story can answer failure, pressure, ownership, and communication prompts with different emphases. Prepare versatile stories. Do not force-fit poorly. Keep facts consistent across interviews.
Q96beginnerWhat is sustainable pace in Agile?
Teams deliver indefinitely without burnout heroics. Overtime spikes are signals of planning failure. Retros should address load. Healthy culture question—good candidates value sustainability.
Q97intermediateDiscuss a time you disagreed on code review.
Focused on user/risk impact, offered alternatives/benchmarks, and accepted team consensus when appropriate. Separated style nits from substantive issues. Relationship stayed intact. Shows craft plus humility.
Q98intermediateHow do you keep stakeholders updated without spamming?
Agree cadence and channels, publish concise status with risks/asks, and escalate only when decisions needed. Dashboards beat essay updates. Reliability of communication builds trust. Adjust altitude per audience.
Q99intermediateWhat does 'shift left' mean culturally?
Move quality/security/testing earlier—collaborate on AC, automate checks in CI, involve QA/security in design. Reduces late scrap. Behavioral commitment to prevention over firefighting. Pair with tooling examples.
Q100beginnerFinal tip: how long should behavioral answers be?
Aim ~1–2 minutes per STAR story unless asked to dive deeper. Watch interviewer cues; pause for follow-ups. Rambling loses the Result. Practice with a timer. Clarity beats exhaustive chronology.
CS Fundamentals (OOP/DBMS/OS/CN)
216 questions
Q1beginnerWhat is encapsulation in OOP?
Bundling data and methods that operate on data inside a class, hiding internal state via private/access modifiers. External code uses public interface. Example: bank account balance changed only through deposit/withdraw methods validating amount.
Q2beginnerExplain inheritance with example.
Subclass inherits properties/methods from superclass — IS-A relationship. `class Dog extends Animal`. Promotes reuse; subclass overrides behavior. JavaScript prototypal inheritance; Python class bases.
Q3beginnerWhat is polymorphism?
Same interface different implementations — method overriding (runtime) and overloading (compile-time in Java). `shape.draw()` circle vs rectangle draws differently. Enables extensibility open-closed principle.
Q4beginnerWhat is abstraction in OOP?
Expose essential features hiding complexity. Abstract classes/interfaces define contract without full implementation. Driver uses car pedals not engine internals. Java interface PaymentGateway.
Q5intermediateSOLID — Single Responsibility Principle?
A class should have one reason to change — one job. User class shouldn't send emails and persist DB — split UserRepository MailService. Easier test maintain.
Q6intermediateSOLID — Open/Closed Principle?
Open extension closed modification — add behavior via new classes not editing existing. Strategy pattern plug new discount rules without changing checkout core.
Q7intermediateSOLID — Liskov Substitution Principle?
Subtypes must be substitutable for base type without breaking — square-rectangle problem classic violation. Callers shouldn't need instanceof checks.
Q8intermediateSOLID — Interface Segregation Principle?
Many specific interfaces better than one fat interface. Printer shouldn't implement scan if only prints — split Printable Scannable.
Q9intermediateSOLID — Dependency Inversion Principle?
Depend on abstractions not concretions. High-level OrderService depends on IPaymentProcessor not Stripe class — inject implementation.
Q10intermediateInterface vs abstract class?
Interface: contract only methods no state (Java 8+ default ok). Abstract class: partial implementation shared fields. Multiple interfaces; single inheritance abstract class. C++ pure virtual similar.
Q11intermediateComposition vs inheritance?
Composition 'has-a' delegate behavior flexible; inheritance 'is-a' tight coupling. Favor composition — Design Patterns Gang of Four.
Q12beginnerMethod overloading vs overriding?
Overloading same name different params compile-time (Java). Overriding subclass replaces parent method runtime virtual dispatch.
Q13intermediateConstructor chaining?
Call this() or super() first line chain constructors initialize fields hierarchy.
Q14beginnerStatic vs instance members?
Static belongs class one copy; instance per object. Static method no this instance.
Q15beginnerAccess modifiers public private protected?
public anywhere; private class only; protected subclass package Java.
Q16beginnerExplain ACID with bank transfer example.
Atomicity: debit+credit both or neither. Consistency: balances valid constraints. Isolation: concurrent transfers don't see dirty state. Durability: committed survives crash WAL. Transfer $100 A→B wraps in transaction.
Q17intermediate1NF 2NF 3NF normalization briefly?
1NF atomic columns no repeating groups. 2NF no partial dependency on composite key. 3NF no transitive dependency non-key→non-key. Reduce redundancy anomalies insert update delete.
Q18beginnerPrimary key vs foreign key?
Primary uniquely identifies row. Foreign references primary another table enforce referential integrity.
Q19intermediateCandidate vs composite key?
Candidate minimal unique identifier; one chosen primary. Composite key multiple columns together unique.
Q20intermediateClustered vs non-clustered index?
Clustered table data sorted by index leaf IS data one per table. Non-clustered separate structure points rows many allowed.
Q21intermediateB-tree index why used?
Balanced tree O(log n) search insert range queries disk page friendly vs hash O(1) no range.
Q22advancedTransaction isolation levels?
Read uncommitted committed repeatable serializable — increasing consistency preventing dirty read non-repeatable phantom.
Q23intermediateDirty read phantom read?
Dirty read uncommitted data; phantom new rows appear range scan same transaction.
Q24intermediateDeadlock in DB how resolve?
Two txs wait each other locks. DB detects aborts victim rollback. Prevention: lock ordering timeout.
Q25intermediateN+1 query problem ORM?
1 query list N queries related — fix join prefetch batch IN clause.
Q26intermediateHashMap vs TreeMap complexity?
HashMap O(1) average get unsorted. TreeMap O(log n) red-black sorted keys navigable.
Q27beginnerSQL JOIN types summary?
INNER matching; LEFT all left; RIGHT all right; FULL both; CROSS cartesian.
Q28intermediateView vs materialized view?
View virtual stored query; materialized physical snapshot refresh periodic faster read.
Q29intermediateStored procedure pros cons?
Logic DB reduce round trips; harder version test migrate vendor lock.
Q30advancedSharding vs replication?
Sharding partition data horizontal scale; replication copies read scale availability.
Q31advancedCAP in distributed DB?
Partition tolerance mandatory distributed — choose CP or AP during partition.
Q32intermediateNoSQL types document key-value column graph?
MongoDB document; Redis KV; Cassandra column; Neo4j graph use case fit.
Q33beginnerORM benefit drawback?
Productivity abstraction; complex SQL awkward performance N+1 leak.
Q34intermediateEXPLAIN query plan?
DB shows index scan seq scan cost optimize slow queries.
Q35advancedWAL write-ahead log?
Log changes before apply data crash recovery durability.
Q36intermediateWhat is deadlock — four Coffman conditions?
Mutual exclusion hold wait no preemption circular wait. All four needed deadlock. Prevention break one.
Q37intermediateSemaphore vs mutex?
Mutex binary lock ownership. Semaphore counting resource pool wait signal.
Q38beginnerProcess vs thread?
Process separate memory space heavy IPC. Thread shared address space lighter context switch.
Q39intermediatePaging vs segmentation?
Paging fixed size frames virtual memory. Segmentation logical variable segments fragmentation.
Q40intermediateCPU scheduling FCFS SJF RR?
FCFS simple convoy effect. SJF optimal average wait starvation. Round Robin quantum time-sharing.
Q41intermediateContext switch cost?
Save restore registers TLB flush cache cold switch ms microseconds scale.
Q42beginnerVirtual memory purpose?
Illusion larger RAM disk swap page fault demand paging.
Q43intermediatePage fault handling?
MMU trap OS load page disk update table resume instruction.
Q44advancedThrashing symptom?
Excessive paging CPU idle useful work low add RAM reduce multiprogramming.
Q45beginnerUser mode vs kernel mode?
User restricted instructions; kernel full hardware access syscall boundary.
Q46beginnerSystem call example?
read write fork exec — user program requests kernel service trap.
Q47intermediateInter-process communication?
Pipes message queues shared memory sockets signals.
Q48intermediateRace condition fix?
Mutex lock atomic operations serializable isolation.
Q49advancedBanker's algorithm?
Deadlock avoidance safe state allocate resources simulation.
Q50beginnerSpooling example?
Print queue disk buffer printer slow device.
Q51advancedDMA direct memory access?
Device transfer memory without CPU byte-by-byte offload.
Q52intermediateBoot process brief?
BIOS/UEFI bootloader kernel init systemd user login.
Q53advancedInode in filesystem?
Metadata file permissions size pointers blocks Unix.
Q54intermediateLRU page replacement?
Evict least recently used approximate clock algorithm hardware bit.
Q55intermediateThread pool why?
Reuse threads avoid create destroy overhead limit concurrency.
Q56beginnerTCP vs UDP?
TCP reliable ordered connection handshake congestion control streaming. UDP datagram fast no guarantee video DNS gaming.
Q57beginnerHTTP vs HTTPS?
HTTPS HTTP over TLS encrypts integrity cert auth port 443. HTTP plaintext 80 insecure login.
Q58beginnerDNS how works?
Resolve domain IP recursive resolver root TLD authoritative cache TTL.
Q59beginnerREST principles?
Stateless resources URIs HTTP verbs representation HATEOAS optional uniform interface.
Q60beginnerCommon HTTP status codes?
200 OK 201 Created 204 No Content 301 Moved 400 Bad Request 401 Unauthorized 403 Forbidden 404 Not Found 409 Conflict 422 Validation 429 Rate limit 500 Internal 502 Bad Gateway 503 Unavailable.
Q61intermediateCORS why needed?
Same-origin policy blocks cross domain XHR; server Access-Control-Allow-Origin permits browser read response.
Q62intermediateJWT structure uses?
Header alg typ payload claims exp signature verify secret/public key stateless auth.
Q63beginnerCookies vs sessions?
Cookie client storage sent each request; session server store session id cookie identifies.
Q64beginnerThree-way handshake TCP?
SYN client seq x; SYN-ACK server x+1 seq y; ACK client y+1 connection established.
Q65intermediateTLS handshake simplified?
Client hello cipher suites server cert key exchange session keys encrypted application data.
Q66intermediateHTTP/1.1 vs HTTP/2?
HTTP/2 multiplex binary frames header compression single connection server push.
Q67intermediateWebSocket vs HTTP polling?
WebSocket full duplex persistent; long polling repeated requests higher latency overhead.
Q68beginnerCDN content delivery network?
Edge caches static assets geo close users reduce latency origin load.
Q69intermediateLoad balancer L4 vs L7?
L4 TCP IP routing; L7 HTTP path header content aware sticky sessions.
Q70intermediateNAT network address translation?
Private IP to public IP many devices one public address router.
Q71beginnerSubnet mask purpose?
Divide IP network host portions CIDR /24 255.255.255.0.
Q72beginnerIPv4 vs IPv6?
IPv4 32-bit exhausted NAT; IPv6 128-bit built-in IPsec no NAT needed.
Q73intermediateARP protocol?
Resolve IP MAC address local network broadcast.
Q74beginnerICMP ping?
Echo request reply diagnose connectivity TTL exceeded traceroute.
Q75intermediateOSI vs TCP/IP layers?
OSI 7 layers theoretical; TCP/IP 4 practical application transport internet link.
Q76intermediateAggregation vs composition UML?
Aggregation weak has-a lifecycle independent; composition strong part dies with whole.
Q77intermediateCohesion vs coupling?
High cohesion related methods together; low coupling minimal dependencies modules.
Q78intermediateDesign pattern Singleton?
One instance global access caution testability.
Q79advancedFactory vs Abstract Factory?
Factory method subclass decides type; Abstract Factory families related products.
Q80intermediateObserver pattern?
Subject notifies observers state change decouple.
Q81advancedMVC MVP MVVM?
UI patterns separate view logic; MVVM data binding WPF React similar ideas.
Q82advancedRAID levels brief?
RAID0 striping; RAID1 mirror; RAID5 parity fault tolerance.
Q83advancedTwo-phase commit distributed?
Prepare commit coordinator consensus transaction.
Q84intermediateOptimistic vs pessimistic locking?
Optimistic version check commit; pessimistic lock row read.
Q85intermediateDatabase trigger?
Automatic procedure on INSERT UPDATE DELETE audit.
Q86intermediateCursor in SQL?
Row-by-row processing slow prefer set-based.
Q87intermediateWindow functions ROW_NUMBER?
PARTITION BY ORDER BY analytics without collapse rows.
Q88intermediateACID vs BASE NoSQL?
BASE basically available soft state eventual consistency NoSQL trade-off.
Q89intermediateMongoDB document model?
BSON flexible schema embed vs reference join design.
Q90advancedRedis persistence RDB AOF?
Snapshot RDB; append log AOF durability trade-offs.
Q91advancedElasticsearch inverted index?
Full-text search tokenize index term document mapping.
Q92advancedPrimary replica lag?
Async replication stale read read-your-writes concern.
Q93intermediateConnection pooling?
Reuse DB connections avoid handshake overhead limit max.
Q94beginnerPrepared statement benefit?
Parse once execute many SQL injection safe.
Q95intermediateDenormalization when?
Read heavy analytics duplicate data speed joins cost update complexity.
Q96advancedStar schema data warehouse?
Fact table measures dimension tables surround OLAP.
Q97beginnerOSI layer 3 vs layer 4?
Network IP routing; Transport TCP UDP ports.
Q98beginnerEphemeral vs well-known ports?
Well-known 0-1023 HTTP 80; ephemeral client random high port.
Q99beginnerDHCP role?
Auto assign IP subnet gateway DNS lease.
Q100intermediateVPN tunnel?
Encrypted virtual link remote access site-to-site.
Q101intermediateFirewall stateful vs stateless?
Stateful tracks connection context; stateless packet rules only.
Q102advancedSYN flood attack?
Half-open connections exhaust server SYN cookie mitigation.
Q103intermediateMan-in-the-middle prevention?
HTTPS cert pinning HSTS no plain HTTP login.
Q104intermediatePublic key vs symmetric crypto?
Symmetric fast shared key AES; asymmetric RSA key exchange sign.
Q105advancedOAuth vs SAML?
OAuth authorization delegation API; SAML enterprise SSO XML.
Q106advancedSession fixation attack?
Attacker sets session id; regenerate on login prevent.
Q107intermediateSame-origin policy definition?
Protocol host port match origin access DOM cookies restricted.
Q108intermediatePreflight OPTIONS CORS?
Non-simple methods headers browser OPTIONS first permission.
Q109intermediateGraphQL over HTTP?
Usually POST single endpoint query body JSON.
Q110advancedgRPC vs REST?
gRPC protobuf HTTP/2 binary streaming; REST JSON text universal.
Q111advancedMessage queue at-least-once delivery?
Ack after process duplicate possible idempotent consumer.
Q112intermediateEventual consistency example?
DynamoDB cross-region seconds lag acceptable cart.
Q113advancedPACELC theorem?
If Partition else Latency Consistency trade-off.
Q114advancedHypervisor Type1 Type2?
Type1 bare metal ESXi; Type2 hosted VirtualBox.
Q115intermediateContainer vs VM?
Container shares kernel image lightweight; VM full OS isolate.
Q116advancedCopy-on-write filesystem?
Docker layers share read-only write layer union.
Q117beginnerCron job OS?
Scheduled commands time expression crontab.
Q118intermediateSignal SIGKILL vs SIGTERM?
SIGTERM graceful shutdown handler; SIGKILL force no catch.
Q119intermediateZombie process?
Child exited parent not wait() reap init adopts.
Q120intermediateOrphan process?
Parent died before child init adopts.
Q121beginnerCritical section?
Code accessing shared resource mutex protect.
Q122advancedReader-writer lock?
Multiple readers OR one writer concurrency read heavy.
Q123advancedSpinlock vs blocking mutex?
Spin busy-wait short critical section; mutex sleep OS schedule.
Q124advancedNUMA awareness?
Non-uniform memory access local node faster multiprocessor.
Q125advancedBuddy allocator?
Power-of-two memory blocks kernel allocation.
Q126advancedSlab allocator?
Cache object types kernel reduce fragmentation.
Q127advancedTLB translation lookaside buffer?
Cache virtual physical page table walk expensive.
Q128advancedBelady anomaly?
Adding frames FIFO page fault increase counterintuitive.
Q129intermediateDining philosophers problem?
Deadlock classic five forks semaphore solution.
Q130advancedMonitor synchronization?
High-level mutex condition variables Java synchronized.
Q131advancedHappens-before Java memory model?
Visibility guarantee synchronized volatile thread start join.
Q132advancedCache coherence MESI?
Modified Exclusive Shared Invalid multi-core consistency.
Q133advancedInstruction pipeline hazard?
Structural data control hazard forwarding stall.
Q134advancedBranch prediction?
CPU speculate branch reduce pipeline bubble mispredict penalty.
Q135advancedIPv4 header fields?
Source dest TTL protocol checksum length flags fragment.
Q136advancedQUIC protocol?
UDP-based HTTP/3 TLS integrated faster handshake multiplex.
Q137advanced mTLS mutual TLS?
Client and server both present certs service mesh.
Q138intermediateHSTS header?
Force HTTPS browser remember preload list.
Q139intermediateCertificate chain validation?
Browser trusts root CA signs intermediate signs server cert.
Q140intermediateReverse proxy vs forward?
Forward client proxy outbound; reverse nginx front servers inbound.
Q141intermediateSticky session load balancer?
Same client same server session state issue scale out.
Q142intermediateWeb Application Firewall WAF?
Filter HTTP attacks SQLi XSS rules Cloudflare.
Q143intermediateRate limiting token bucket?
Tokens refill rate burst capacity smooth traffic.
Q144intermediateIdempotency key REST POST?
Client header duplicate submit same result payment APIs.
Q145intermediateETag conditional request?
If-None-Match 304 Not Modified cache bandwidth save.
Q146beginnerCache-Control max-age?
Browser cache seconds public private CDN.
Q147intermediateHTTP Range requests?
Partial content 206 resume download large file.
Q148intermediateContent negotiation Accept?
Client Accept-Language Accept-Encoding server choose representation.
Q149intermediateServer-sent events SSE?
One-way server push text/event-stream simpler WebSocket.
Q150intermediateLong polling Comet?
Hold request until event server respond reconnect.
Q151advancedMulticast vs broadcast?
Broadcast all hosts subnet; multicast group subscribers efficient.
Q152intermediateVLAN purpose?
Logical LAN segmentation broadcast domain security.
Q153advancedBGP routing internet?
Border Gateway Protocol between AS paths policy.
Q154intermediateServerless cold start?
First invoke spin container latency mitigation provisioned.
Q155beginnerNormalization anomaly insert?
Insert anomaly can't add data without other unrelated data.
Q156advancedBoyce-Codd BCNF?
Every determinant is candidate key stricter 3NF.
Q157advancedFourth normal form 4NF?
No multi-valued dependency independent multi-value.
Q158beginnerEntity-relationship diagram?
Entities attributes relationships cardinality design DB schema.
Q159intermediateSurrogate key vs natural?
Surrogate auto id artificial; natural business key email risky change.
Q160intermediateSlow query log?
MySQL log queries exceeding threshold optimize indexes.
Q161advancedCovering index?
Index includes all queried columns no table lookup index-only scan.
Q162advancedPartial index?
Index subset rows WHERE condition smaller faster.
Q163advancedBitmap index?
Low cardinality columns data warehouse bitwise AND fast.
Q164advancedLSM vs B-tree storage?
LSM write optimized LevelDB Cassandra; B-tree read PostgreSQL.
Q165advancedWrite-ahead log vs redo log?
Similar durability Postgres WAL InnoDB redo crash recovery.
Q166advancedSnapshot isolation?
Consistent read MVCC version each transaction start.
Q167advancedSerializable highest isolation?
Transactions appear sequential phantom prevented expensive.
Q168advancedTwo-phase locking 2PL?
Growing shrinking phase serializable deadlock possible.
Q169advancedMVCC multi-version concurrency?
Postgres keep row versions readers no block writers.
Q170advancedGarbage collection DB vacuum?
Postgres VACUUM dead tuple space reuse MVCC.
Q171intermediateOOP final finally finalize Java?
final class no extend; finally block always; finalize deprecated GC.
Q172beginnerPython duck typing?
If it walks like duck type behavior not inheritance.
Q173intermediateJavaScript prototype chain?
Object lookup __proto__ until null property inheritance.
Q174advancedMultiple inheritance problem?
Diamond ambiguity which method — Python MRO C3 linearization.
Q175intermediateMixin pattern?
Reuse behavior multiple inheritance compose capabilities.
Q176intermediateDependency injection containers?
Spring auto-wire constructor inject test mock swap.
Q177intermediateInversion of control IoC?
Framework calls your code callbacks hooks not you call framework.
Q178advancedDomain-driven design aggregate?
Cluster entities consistency boundary root entity.
Q179advancedValue object vs entity DDD?
Entity identity matters; value object immutable defined attributes.
Q180advancedAnti-corruption layer?
Translate legacy bounded context integration DDD.
Q181intermediateCAP practical choice?
Most systems PA with eventual consistency partition rare.
Q182advancedCAP theorem again with examples?
During partition: CP systems (some DBs) refuse inconsistent writes; AP systems (eventual stores) serve possibly stale data. CA without P isn't realistic for true distributed. Discuss latency timeouts as practical partitions.
Q183advancedWhat is PACELC?
Extension of CAP: if Partition, trade A/C; Else (normal), trade Latency vs Consistency. Explains why even without partitions systems choose faster stale reads vs slower strong reads.
Q184intermediateRAID levels brief?
RAID0 stripe speed no redundancy; RAID1 mirror; RAID5 parity striped (survives 1 disk); RAID6 dual parity; RAID10 mirror+stripe. Trade space, speed, fault tolerance. Used under DB storage.
Q185intermediateOSI 7 layers with examples?
Physical (cables/PHY), Data Link (Ethernet MAC/switches), Network (IP/routers), Transport (TCP/UDP), Session (dialogs—less explicit in web), Presentation (TLS/encoding), Application (HTTP/DNS). Interview: map traceroute vs HTTP debug to layers.
Q186advancedTCP congestion control idea?
Sender limits rate via congestion window: slow start, congestion avoidance, react to loss/ECN (Reno/CUBIC). Prevents collapse of shared networks. Distinct from flow control (receiver window).
Q187advancedTLS 1.3 handshake brief?
Fewer round trips than 1.2: ClientHello with key share → ServerHello/cert/finished → client finished; often 1-RTT (0-RTT resumption with caveats). Provides encryption, integrity, authentication via certificates. Always prefer TLS 1.3+ configs.
Q188beginnerDNS records: A/AAAA/CNAME/MX?
A: IPv4; AAAA: IPv6; CNAME: alias to another name (no other data typically); MX: mail servers with priority. Also TXT (SPF/DKIM), NS, SRV. Caching TTLs matter for cutovers.
Q189advancedHTTP/3 and QUIC?
HTTP/3 runs over QUIC (UDP) with built-in TLS and stream multiplexing without TCP head-of-line blocking. Faster connection setup and better loss recovery on mobile networks. Awareness increasingly expected.
Q190intermediateVirtual memory and thrashing?
OS maps virtual addresses to physical frames. Thrashing: working set doesn't fit; constant paging kills throughput. Fix: more RAM, reduce footprint, fix leaks, tune concurrency.
Q191intermediatePage replacement LRU?
Evict least recently used page—good locality heuristic. Approximated via clocks/bits because true LRU is expensive. Contrast FIFO Belady anomaly awareness.
Q192intermediateWhat is an inode?
Unix structure storing file metadata (permissions, size, pointers to data blocks)—not the filename. Directories map names → inode numbers. Explains hard link behavior.
Q193intermediateSymlink vs hardlink?
Hard link: multiple directory entries to same inode (same filesystem, can't link dirs usually). Symlink: special file pointing to a path (can dangle, can cross filesystems). Deleting last hard link frees data; deleting symlink target breaks link.
Q194intermediateMutex vs RW lock?
Mutex: exclusive access. RW lock: many concurrent readers or one writer. Improves read-heavy workloads; writers may starve if poorly implemented. Prefer simpler mutex unless profiled need.
Q195advancedActor model brief?
Computation as actors exchanging messages; no shared memory races. Erlang/Akka/Orleans styles. Great for concurrency mental model; map to queues/services in practice.
Q196advancedBloom filter?
Probabilistic set membership: fast, space-efficient; false positives possible, false negatives not. Used to skip expensive lookups (caches, DB indexes, CDN). Tune bits/hashes for error rate.
Q197advancedConsistent hashing?
Hash ring places nodes and keys; when nodes add/remove, only nearby keys remapped—minimizes reshuffle vs mod-N hashing. Used in caches/CDNs/DBs. Virtual nodes improve balance.
Q198beginnerProcess vs thread?
Process: isolated address space. Threads: shared memory within process—lighter context switch, need sync. Cron jobs vs thread pools analogies in servers.
Q199intermediateContext switch cost?
Saving/restoring registers, TLB effects—too many hurts throughput. Avoid oversubscription of threads for CPU-bound work.
Q200intermediateDeadlock four conditions?
Mutual exclusion, hold-and-wait, no preemption, circular wait. Prevent by lock ordering / timeouts. Detect via wait-for graphs.
Q201beginnerUser mode vs kernel mode?
CPU privilege rings: user apps trap into kernel via syscalls for I/O/protection. Bugs in kernel are catastrophic; minimizes trusted computing base.
Q202beginnerTCP three-way handshake?
SYN → SYN-ACK → ACK establishes connection, syncs sequence numbers. TIME_WAIT after close explained for reliability.
Q203beginnerUDP when preferred?
Low latency, tolerates loss: gaming, VoIP, DNS, QUIC underpinnings. App must handle reliability if needed.
Q204intermediateWhat is a file descriptor?
Integer handle to kernel file/socket object per process. `select`/`poll`/`epoll` multiplex I/O on fds.
Q205advancedPaging vs segmentation?
Paging fixed-size frames eliminates external fragmentation; segmentation variable logical modules. Modern OS primarily paging (with segments vestiges on x86).
Q206intermediateSemaphore vs mutex?
Semaphore counting signaling between threads; mutex ownership-based exclusion. Don't use semaphores as fancy mutexes without care.
Q207beginnerDNS resolution steps briefly?
Stub → recursive resolver → root → TLD → authoritative; caches along the way. Dig/nslookup for debug.
Q208intermediateHTTPS certificate validation idea?
Chain to trusted CA, check hostname/SAN, expiry, revocation (OCSP/CRL). Pinning rare/mobile. Misconfig causes browser errors.
Q209beginnerIPv4 vs IPv6 awareness?
IPv6 larger addresses, simpler header, native neighbor discovery. Dual-stack common. AAAA records required for IPv6 service.
Q210intermediateWhat is NAT?
Network Address Translation maps private addresses to public—conserves IPv4. Affects inbound connectivity (need port forwards). Carrier-grade NAT complications for P2P.
Q211advancedCPU cache locality?
Prefer sequential memory access; avoid pointer chasing when possible. Critical for high-perf code and DB buffer pools.
Q212beginnerVirtualization vs containers?
VMs virtualize hardware with guest OS; containers share kernel with isolation (namespaces/cgroups)—lighter. Both used in cloud.
Q213beginnerWhat is a syscall?
Controlled entry to kernel services (`read`, `write`, `open`). High syscall rates can bottleneck—batch I/O.
Q214intermediateLoad average meaning?
Average runnable+uninterruptible tasks over 1/5/15 minutes on Unix. Interpret with CPU count—load 4 on 4-core ≈ busy.
Q215advancedZero-copy idea?
Avoid extra copies between kernel/user (sendfile, splice) for high-throughput proxies. Interview awareness for web servers.
Q216intermediateWhat is thrashing vs high CPU?
Thrashing is memory paging storm (I/O wait); high CPU is compute-bound. Diagnose with vmstat/iostat/top differently.