Questions

439 questions in the selected packs, grouped by topic.

439 cards in the exported deck
Pack
All packs
Importance
All topics

.NET Application Architecture51 question

How would you structure a modern ASP.NET Core service so business rules remain testable and independent from the web framework and EF Core?

Answer

  • Separates delivery, application, domain, and infrastructureAssigns HTTP mapping, use-case coordination, business rules, and technical adapters to clear responsibilities.
  • Keeps dependencies pointing inwardUses interfaces owned near the application or domain and composes concrete infrastructure at the edge.
  • Defines use-case and transaction boundariesExplains where validation, authorization context, business invariants, and persistence commit occur.
  • Avoids empty layersKeeps the number of projects and abstractions proportional to domain complexity and change risk.

.NET Async and Concurrency42 questions

What does async and await do in a .NET web service, and what common mistakes reduce scalability?

Answer

  • Explains non-blocking I/O waitingStates that await frees the current thread while asynchronous I/O is pending and resumes through a continuation.
  • Separates async from parallel CPU workExplains that async does not inherently make CPU-bound work faster or make shared state thread-safe.
  • Names server-side mistakesMentions .Result or .Wait, unnecessary Task.Run, sync-over-async, fire-and-forget, or unbounded Task.WhenAll.
  • Keeps the call chain asynchronousPasses asynchronous APIs and cancellation through the stack instead of blocking at a lower layer.

An endpoint calls hundreds of partner APIs. How would you use cancellation, timeouts, and concurrency limits to protect the service?

Answer

  • Propagates cancellation cooperativelyPasses the request token through HTTP, database, queue, and internal operations and stops work at safe points.
  • Uses explicit time budgetsSets per-call and overall deadlines that reflect the caller's remaining time instead of relying on infinite defaults.
  • Bounds concurrencyUses a semaphore, channel, worker pool, or bulkhead rather than starting every call at once.
  • Defines failure and partial-result semanticsChooses fail-fast, partial response, retry, or queued processing based on business requirements.

.NET Dependency Injection Lifetimes41 question

Explain singleton, scoped, and transient lifetimes in .NET dependency injection. How do you choose safely?

Answer

  • Defines all three lifetimesCorrectly explains root-container, per-scope, and per-resolution instance reuse.
  • Explains captive dependenciesWarns against a longer-lived service retaining a shorter-lived dependency such as DbContext.
  • Considers state and thread safetyMatches singleton use to immutable or synchronized shared state and avoids hidden request data.
  • Accounts for resource ownershipMentions disposal by the container and avoiding manual ownership confusion.

.NET/C# Maintenance for a Node.js Developer32 questions

You must fix a bug in an ASP.NET Core microservice but your strongest experience is Node.js. How would you learn the code path and make a safe change?

Answer

  • Starts from observable behaviourReproduces the bug and traces the API or message contract through controller, service, data access, and tests.
  • Learns .NET-specific conventionsChecks async Task usage, cancellation, dependency-injection lifetimes, disposal, logging, and project analyzers.
  • Makes a small verified changeAdds a focused regression test, runs the normal build and integration path, documents uncertainty, and requests framework-aware review.

A Node.js service must integrate with an existing .NET component. What should be standardized so the boundary remains language-independent and diagnosable?

Answer

  • Defines a language-neutral contractUses documented OpenAPI, GraphQL, protobuf, or event schemas with explicit field and compatibility rules.
  • Standardizes runtime behaviourDefines timeout, retry, idempotency, error mapping, authentication, and serialization details.
  • Correlates observability across runtimesPropagates trace and correlation context and uses compatible logs, metrics, and health semantics.

Agent Orchestration36 questions

What responsibilities belong in agent orchestration rather than in the prompt itself?

Answer

  • Manages explicit state and transitionsKeeps workflow state, step order, stopping conditions, and checkpoints in application code.
  • Keeps policy deterministicHandles authorization, budgets, validation, approvals, and transaction boundaries outside the model.
  • Handles recoveryDefines retries, idempotency, timeout, partial failure, compensation, and resume behavior.

A team proposes separate planner, researcher, reviewer, and writer agents for a logistics workflow. How would you decide whether that complexity is justified?

Answer

  • Starts with a simple baselineCompares against one model call, one agent with tools, or a deterministic workflow before adding agents.
  • Requires real specialization or isolationUses multiple agents only for distinct context, permissions, models, ownership, or parallelizable work.
  • Demands measurable improvementMeasures quality, latency, cost, reliability, and debuggability against the simpler design.

An agent creates a booking in an external system, then fails before saving the booking id locally. How would you make the workflow recover safely?

Answer

  • Uses idempotent external operationsUses an idempotency key or external reference so retrying can find the existing booking instead of creating another.
  • Persists step stateSaves intent and progress before side effects and records results immediately after each completed step.
  • Adds reconciliation and compensationUses reconciliation to repair missing state and a defined compensation or manual review path when automatic recovery is unsafe.

Design the control loop for an agent that investigates shipment exceptions using several tools. How do you stop it from running indefinitely?

Answer

  • Represents workflow state explicitlyStores the goal, observations, completed actions and remaining decision outside the model prompt alone.
  • Applies hard execution limitsUses maximum steps, elapsed time, token or cost budgets and per-tool rate limits.
  • Defines outcomes and recoveryStops on success, lack of progress, policy violation or uncertainty, and can resume or escalate with an audit trail.

An agent workflow can wait hours for carrier data or human approval. What state would you persist, and how would it resume safely after a restart?

Answer

  • Persists an explicit durable state machineStores workflow id, current state, inputs, tool results, approvals, timestamps and version.
  • Makes steps idempotent and transactionalEach action has a unique operation key and records completion before retrying or advancing.
  • Correlates delayed events safelyExternal results and approvals include workflow and expected-state identifiers so stale events cannot advance the wrong run.

When would you use multiple specialized agents instead of one agent with several tools, and what new problems would that introduce?

Answer

  • Requires a real specialization benefitMultiple agents may help when tasks need distinct context, policies, models or independent ownership.
  • Makes coordination risks explicitAdds message passing, duplicated context, conflicting decisions, latency, cost and harder debugging.
  • Starts with the simpler measurable baselinePrefers one orchestrated agent or deterministic workflow until evaluation shows specialization improves outcomes.

Agent orchestration and MCP32 questions

Design an agent that can look up shipments, draft customer updates, and request carrier changes. How would you control its tools and side effects?

Answer

  • Defines narrow capability-based toolsSeparates read, draft, and mutation tools, validates typed arguments, and avoids a broad generic execute capability.
  • Enforces policy outside the modelPropagates user identity and tenant scope, checks authorization in the tool service, treats model and retrieved content as untrusted, and requires approval for sensitive writes.
  • Bounds execution and makes it auditableSets step, time, and cost limits, handles idempotency and partial failure, logs every tool decision and outcome, and provides cancellation or escalation.

What problem does MCP solve in an AI application, how do the host, client, and server relate, and what does MCP not solve for you?

Answer

  • Explains the interoperability problemDescribes MCP as a standard way for an AI host to discover and invoke external capabilities such as tools and resources instead of building bespoke adapters for each integration.
  • Distinguishes host, client, and serverExplains that the host owns the application and user context, clients maintain protocol connections, and servers expose capabilities through negotiated interfaces.
  • States what the protocol does not guaranteeClarifies that MCP does not automatically provide correct authorization, safe business actions, trustworthy content, idempotency, or a good agent policy.

AI Agents and Tool Use43 questions

What is an AI agent, and how is it different from a single prompt-and-response LLM call?

Answer

  • Defines the agent loopExplains repeated model decisions, tool calls, observations, and stopping conditions.
  • Explains tools and external stateExplains that tools let the workflow read current data or perform approved actions outside the model.
  • Includes application controlMentions validation, authorization, budgets, approval, and deterministic code around the model.

Design an agent that helps an operator investigate a delayed shipment and prepare a customer response.

Answer

  • Defines a narrow goal and toolsUses read-only tools for shipment data, events, policies, and partner status, with clear schemas.
  • Protects sensitive actionsValidates inputs, authorizes the operator, redacts sensitive data, and requires approval before sending or changing records.
  • Defines completion and evaluationUses step and time budgets, cites tool results, detects missing data, and measures factuality and task success.

Which agent actions could run automatically, which need confirmation, and which should never be exposed as tools?

Answer

  • Classifies action riskUses reversibility, financial impact, privacy, external communication, and permission scope to classify actions.
  • Defines autonomy tiersAllows low-risk reads automatically, requires confirmation for consequential writes, and excludes dangerous broad administration.
  • Adds technical controlsUses narrow schemas, allowlists, idempotency, rate limits, audit logs, and post-action verification.

AI agents, tools, and MCP21 question

An AI agent may read shipment data, calculate options, and draft a customer message through MCP tools. How would you structure the loop and prevent unsafe or repeated actions?

Answer

  • Exposes narrow typed tools with scoped permissionsDefines small capabilities and schemas, provides only necessary context, and maps each tool to least-privilege credentials.
  • Keeps control in deterministic application codeValidates arguments, rechecks authorization, constrains outputs, enforces step and cost budgets, and treats tool results as untrusted input.
  • Protects side effects and supports auditUses approval for high-impact actions, idempotency keys, replay protection, audit logs, explicit stop conditions, and recovery from partial completion.

AI evaluation and guardrails22 questions

How would you decide whether an LLM-based shipment assistant is good enough to release?

Answer

  • Defines task-specific quality and riskSpecifies useful outcomes, factual support, format validity, prohibited behavior, and severity-weighted failure categories instead of one vague accuracy target.
  • Uses representative and adversarial casesBuilds a versioned set from real workflows including edge cases, incomplete data, different languages, prompt injection, and previously observed failures.
  • Combines methods and monitors after releaseUses deterministic validators, source checks, human scoring, calibrated model grading, explicit thresholds, shadow or limited rollout, and versioned production telemetry.

A carrier document contains text telling the assistant to ignore its instructions and send customer data to an external address. How should the system respond and be designed?

Answer

  • Treats retrieved content as untrustedKeeps document text in a data boundary, does not elevate it to trusted instructions, and labels or structures context to reduce instruction confusion.
  • Enforces data and action policy outside the modelChecks identity, tenant, allowed recipients, data classification, and authorization in deterministic code, with no generic outbound-send tool.
  • Adds approval, evidence, and testingRequires confirmation for sensitive disclosure, records attempted calls, blocks or safely refuses the action, and includes injection cases in evaluation and monitoring.

AI guardrails and observability43 questions

An internal assistant reads carrier emails that may contain instructions aimed at the model. How would you reduce prompt-injection risk?

Answer

  • Treats retrieved content as untrusted dataExternal email text is labelled and separated from system policy rather than obeyed as instruction.
  • Enforces permissions outside the modelTool allowlists, schemas, user authorization and business rules are checked by application code.
  • Adds confirmation and limits for consequential actionsWrite actions require explicit confirmation, scoped parameters, rate limits and audit logs.

How would you design an AI feature that uses customer shipment data while minimizing privacy and data-leakage risk?

Answer

  • Minimizes and classifies dataSends only fields required for the task, removes secrets or identifiers where possible and classifies sensitivity.
  • Controls the model-provider boundaryReviews region, training use, encryption, contractual controls and approved model endpoints.
  • Restricts storage, logs and user accessUses short retention, redacted telemetry, tenant authorization and auditable access.

What would you log and monitor for an agent-based workflow without creating a new sensitive-data problem?

Answer

  • Creates a structured execution traceRecords workflow id, model and prompt version, tool names, decisions, latency, token use and outcomes.
  • Monitors task and safety outcomesTracks success, escalation, retry loops, policy blocks, incorrect actions, latency and cost.
  • Redacts and controls observability dataStores hashes, identifiers or sampled redacted content, with access and retention controls.

AI-Assisted Development31 question

Describe a productive and safe AI-assisted development workflow. Where does AI save time, and where must the engineer remain directly responsible?

Answer

  • Uses bounded verifiable tasksGives AI focused work with relevant context, constraints, examples, and a clear definition of done.
  • Reviews output as untrusted codeChecks architecture, correctness, security, accessibility, performance, and maintainability rather than accepting plausible output.
  • Verifies independentlyUses types, tests, execution, documentation, and comparison with existing code, without relying only on AI-generated tests.
  • Protects data and measures valueKeeps sensitive data within approved tools and evaluates whether AI improves lead time or quality after review cost.

API Contract Design52 questions

What elements would you define before publishing an API that will be consumed by many internal and external systems?

Answer

  • Defines operations and schemasIncludes resource semantics, request and response schemas, validation, and status codes.
  • Defines predictable failuresUses structured error responses with stable codes and documents retryable versus non-retryable failures.
  • Includes operational behaviorMentions authentication, idempotency, pagination, rate limits, timeouts, or compatibility as applicable.

An API handles more than 100 million requests per month and integrates with several downstream systems. What design decisions would you review first?

Answer

  • Keeps the contract efficientConsiders payload size, pagination, filtering, validation cost, and avoiding chatty request patterns.
  • Protects downstream dependenciesMentions timeouts, bounded concurrency, circuit breakers, rate limits, or asynchronous processing.
  • Plans for observability and capacityUses latency percentiles, error rate, throughput, tracing, load tests, and capacity planning rather than only average response time.

API Contract Design52 questions

Design the main endpoints for teachers creating assignments, publishing them to classes and viewing submissions. What makes the API resource-oriented rather than action-RPC over HTTP?

Answer

  • Models domain resourcesIdentifies assignments, publications or class assignments, and submissions as resources with stable identifiers and relationships.
  • Uses HTTP semantics deliberatelyUses suitable methods and status codes, including creation, validation failures, not found and conflicts.
  • Keeps a stable client contractDefines bounded response shapes, pagination for collections, authorization expectations and an evolution strategy.

The backend wants to replace a single studentName field with a structured student object. The frontend and backend may deploy independently. How would you roll out the change?

Answer

  • Starts with an additive contractAdds the new student object while temporarily preserving studentName so old and new clients both work.
  • Uses a safe deployment orderDeploys the tolerant backend first, updates clients to use the new field, then removes the old field only after usage is gone.
  • Observes and documents deprecationMarks the old field deprecated, tracks old-client usage and defines a removal date or version policy.

API Contracts and Validation44 questions

What should a production API contract describe beyond the successful response body?

Answer

  • Covers request and response shapesIncludes parameters, body schemas, required fields, formats, and success responses.
  • Defines errors and semanticsIncludes validation errors, authorization, not-found, conflicts, rate limits, and stable error identifiers.
  • Defines operational behaviorIncludes idempotency, pagination, ordering, versioning, and relevant caching or timeout expectations.

A frontend deploy works against staging but fails after the backend deploys a changed response. What practices would prevent this?

Answer

  • Uses a versioned contract sourceUses OpenAPI, JSON Schema, or another versioned schema as the integration reference.
  • Validates runtime dataValidates requests and responses and reports mismatches with useful context.
  • Tests compatibility in CIUses consumer/provider contract tests, generated-client checks, or compatibility gates before deployment.

Compare sharing TypeScript types, generating clients from OpenAPI, and consumer-driven contract tests. When would you use each?

Answer

  • Positions shared types correctlyRecognizes convenience in one codebase but also coupling and lack of runtime validation.
  • Explains generated contractsUses OpenAPI or schemas for documentation, generation, validation, and language-independent consumers.
  • Explains consumer contractsUses consumer-driven tests when independent teams need to verify the specific interactions consumers rely on.

The backend adds a new shipment status enum value. Can this be a breaking change for a TypeScript frontend, and how would you make the rollout safe?

Answer

  • Recognizes the practical breaking changeExplains that exhaustive switches, validation schemas, generated clients, or UI assumptions can fail on a new enum value.
  • Designs tolerant client behaviorProvides an unknown fallback, safe display, telemetry, and a domain decision about whether unknown means blocked or limited behavior.
  • Coordinates contract rolloutUpdates the contract and consumers first where needed, uses compatibility tests, and monitors old clients.

API Error Handling52 questions

What should a useful API error response contain, and how would you distinguish validation, authorization, conflict and unexpected server errors?

Answer

  • Classifies failure categoriesMaps validation, unauthenticated, forbidden, not-found, conflict and unexpected errors to appropriate HTTP semantics.
  • Defines a stable safe bodyIncludes a machine-readable code, user-safe message, optional field errors and request identifier without exposing internals.
  • Separates client and operator detailLogs the exception and context internally with correlation while keeping sensitive details out of the response.

A client times out while creating an assignment and does not know whether the server committed it. How would you prevent a retry from creating a duplicate?

Answer

  • Recognizes the ambiguous outcomeExplains that the request may have succeeded even though the response was lost, so a blind retry is unsafe.
  • Uses an idempotency keyHas the client reuse one unique operation key and stores that key atomically with the created result.
  • Returns the original result safelyOn repeated keys, returns the stored result or rejects a mismatched payload, with expiry and scope rules.

API Versioning and Compatibility42 questions

Which API changes are usually backward compatible, which are breaking, and why can adding an enum value still be risky?

Answer

  • Classifies common changesExplains that additive optional fields are often compatible, while removing, renaming, changing types, or tightening requirements is usually breaking.
  • Explains open versus closed enumsRecognizes that clients may use exhaustive switches or generated closed enums and fail on an unknown value.
  • Uses consumer evidenceConsiders documented guarantees, contract tests, telemetry, and known client behavior instead of relying only on HTTP theory.

Fifty integrations consume an API that needs a breaking contract change. How would you introduce and later retire the new version?

Answer

  • Runs versions safely in parallelIntroduces a new version without changing the existing contract and isolates routing or implementation where practical.
  • Supports consumer migrationProvides documentation, examples, test environment, communication, deadlines, and support for consumers.
  • Retires using evidenceTracks traffic and errors by client or version, confirms critical consumers moved, and has a rollback or extension plan.

api_contract_design2 questions

A new storefront feature needs data and permission decisions from a Rails backend. How would you agree an API contract that both frontend and backend teams can implement and change safely?

Answer

  • Clarifies user and permission behaviorDefines user actions, authorization outcomes, loading and error states, and who owns each rule before discussing payload shape.
  • Defines request and response contractsAgrees methods, paths, identifiers, schemas, nullability, validation, status codes, and error representation.
  • Plans evolution and verificationUses generated or shared types where useful, contract tests, version-compatible changes, examples, and observability.
  • Avoids leaking backend internalsShapes the contract around product needs rather than exposing database tables or framework-specific structures.

Design a multi-tenant API and data exchange platform that receives customer requests, validates and transforms data, invokes internal services, and exposes processing status.

Answer

  • Clarifies workload and quality requirementsAsks about volume, latency, synchronous versus asynchronous flows, payloads, tenant isolation, availability, and retention.
  • Defines a clear processing flowUses an API edge, validation, durable intake, transformation, orchestration, status store, and callbacks or polling where appropriate.
  • Separates contracts and domain ownershipKeeps translation at boundaries and routes business decisions to owning services instead of centralizing every domain rule.
  • Designs for retries and duplicatesUses idempotency, outbox or durable messaging, retry limits, dead letters, reconciliation, and traceability.
  • Covers security and observabilityIncludes authentication, tenant authorization, encryption, audit, correlation, metrics, alerting, and capacity controls.

api_security_essentials1 question

What security controls would you expect in a customer-facing API and data exchange platform beyond simply requiring login?

Answer

  • Separates authentication and authorizationUses scoped permissions, least privilege, tenant isolation, and object-level checks rather than trusting identity alone.
  • Protects inputs and sensitive dataCovers schema validation, injection prevention, transport encryption, secret management, and sensitive-data minimization.
  • Limits abuseMentions rate limits, quotas, payload limits, timeouts, replay protection, or idempotency for sensitive operations.
  • Designs for detection and responseIncludes audit logs, security telemetry, dependency scanning, key rotation, and incident procedures.

api_versioning4 questions

How can an API, especially a REST API, be versioned? Compare the main approaches and explain what you would choose.

Answer

  • Names common versioning mechanismsCovers URI path, query parameter, custom header, or media-type versioning without presenting one as universally correct.
  • Prioritizes compatibility over numberingExplains that additive compatible changes may not need a new major version and that breaking changes drive migration needs.
  • Defines an operational policyMentions deprecation windows, documentation, telemetry, client ownership, and retirement criteria.
  • Makes a contextual choiceSelects an approach based on discoverability, caching, tooling, gateway support, and consumer constraints.

What is a breaking change, and how does it relate to API versioning? Give examples beyond removing an endpoint.

Answer

  • Defines a breaking change by consumer impactExplains that a change is breaking when an existing valid consumer can no longer behave correctly without modification.
  • Gives varied examplesIncludes shape, semantics, validation, defaults, ordering, status codes, timing, or authorization changes.
  • Considers direction and consumer behaviorDistinguishes request and response compatibility and notes tolerant versus strict readers.
  • Connects breakage to versioning and migrationExplains when a new version, compatibility layer, feature flag, or staged rollout is appropriate.

You must expose two incompatible API generations for several years. Would you put the version in the path, query, header, or media type, and why?

Answer

  • Starts from constraintsAsks about client types, gateway and cache behavior, generated SDKs, observability, documentation, and routing.
  • Compares alternatives accuratelyExplains that path versions are visible and routable, while header or media-type versions preserve URIs but may complicate tooling and caches.
  • Keeps the policy consistentAvoids mixing mechanisms casually and defines how versions are documented, tested, and retired.
  • Makes a reasoned recommendationChooses an option for the stated environment and acknowledges what the choice does not solve.

A public response must replace customerName with a structured customer object. Design a migration that avoids breaking existing consumers.

Answer

  • Uses an additive expand phaseAdds the new customer object while preserving customerName and defines a source of truth for both representations.
  • Plans consumer migrationDocuments semantics, updates SDKs, uses contract tests, identifies owners, and provides a deprecation window.
  • Uses telemetry and compatibility checksMeasures old-field usage and watches errors before removal.
  • Separates final removalRemoves the old field only in a later breaking release or after verified migration.

App Structure and Reusable Components41 question

How would you structure a large React codebase used by several teams so that features remain understandable and shared components do not become a dumping ground?

Answer

  • Uses feature-oriented boundariesGroups a feature's components, hooks, tests, API adapters, and types near each other with a small public entry point.
  • Separates primitives from business componentsKeeps design-system primitives generic while product components remain within the domain that understands their business meaning.
  • Defines dependency directionPrevents shared layers from importing feature code and uses explicit APIs rather than reaching into module internals.
  • Avoids speculative abstractionExtracts reusable code from demonstrated stable patterns and prefers composition over large configurable components.

Architecture decisions and modularity42 questions

A growing logistics platform is currently one Node.js application. The team proposes splitting it into microservices. What would you evaluate before agreeing?

Answer

  • Requires a concrete architectural driverLooks for independent scaling, release cadence, ownership, regulatory boundary, or failure isolation rather than treating microservices as a goal.
  • Finds viable domain and data boundariesIdentifies cohesive business capabilities, clear data ownership, and contracts that do not require shared tables or chatty synchronous calls.
  • Accounts for distributed-system costIncludes network failure, eventual consistency, observability, deployment, security, testing, and operational maturity, and considers a modular monolith first.

Two reasonable designs exist for a new pricing feature. How would you drive and document the decision so the team can revisit it later?

Answer

  • Frames context and decision criteriaStates the problem, constraints, quality attributes, non-goals, and which consequences matter most.
  • Compares real alternatives and trade-offsEvaluates at least two viable options using evidence such as complexity, delivery risk, scalability, cost, and reversibility.
  • Records ownership and revisit conditionsDocuments the chosen option, rejected alternatives, consequences, assumptions, owner, date, and signals that should trigger a review.

ASP.NET Core Request Pipeline41 question

Explain how the ASP.NET Core request pipeline works. Why does middleware order matter?

Answer

  • Explains the middleware chainDescribes before-and-after processing around a next delegate and possible short-circuiting.
  • Gives ordering consequencesUses examples involving routing, authentication, authorization, exception handling, CORS, or static files.
  • Places cross-cutting concerns appropriatelyUses middleware for correlation, logging, error mapping, security headers, or similar request-wide behavior.
  • Keeps domain logic out of middlewareRecognizes that middleware is not the right home for business use-case rules.

Async Concurrency in Node.js52 questions

You must call an external service for 5,000 records. Compare sequential await, one large Promise.all, and bounded concurrency.

Answer

  • Explains sequential executionNotes that sequential await is simple and gentle on dependencies but wastes independent waiting time.
  • Explains unbounded Promise.allNotes that one large Promise.all can overload sockets, memory, connection pools, or the dependency.
  • Chooses bounded concurrencyProposes a measured concurrency limit with explicit retry and per-item failure handling.

A batch operation starts 20 independent requests. Three fail transiently and one fails validation. How would you return a useful result without retrying everything?

Answer

  • Collects every resultUses all-settled style handling or per-operation error capture so one failure does not hide the rest.
  • Classifies failuresSeparates retryable dependency failures from permanent validation or domain failures.
  • Retries only safe failed itemsRetries only transient failures with limits and returns a structured summary of successes and failures.

Asynchronous Error Propagation in Node.js52 questions

How would you structure error handling in a Node.js API built with async and await?

Answer

  • Classifies errors by meaningSeparates validation or domain errors, dependency failures, and unexpected programming or infrastructure errors.
  • Uses centralized boundary handlingLets errors propagate with context and maps them once at the HTTP boundary instead of duplicating response logic everywhere.
  • Handles safety and cleanupUses await or return consistently, finally for cleanup, safe client messages, correlation IDs, and no swallowed rejections.

A request updates a local record and then calls two external systems. The second call fails. How would you handle the partial failure?

Answer

  • Recognizes transaction boundariesDoes not assume one database transaction can atomically include independent external services.
  • Models workflow stateUses a state machine, outbox, saga, or durable job to record progress and resume or compensate safely.
  • Defines recovery policyMakes operations idempotent, retries only transient failures, exposes incomplete state, alerts on exhaustion, and supports manual repair.

Authentication and authorization42 questions

What is the difference between authentication and authorization, and where should each be enforced in a React and Node.js application?

Answer

  • Defines both concepts correctlyAuthentication verifies identity; authorization decides allowed actions and resources.
  • Enforces authorization on the backendExplains that frontend checks improve UX but cannot protect data or operations.
  • Checks the specific resource and actionMentions role, ownership, tenant, or attribute checks rather than only a successful login.

A logistics SaaS stores data for many companies. How would you prevent a user from accessing another company’s shipments even if they guess a valid shipment ID?

Answer

  • Derives tenant identity from trusted authenticationDoes not accept the tenant boundary solely from a client-provided field.
  • Scopes every data access by tenantQueries by both tenant and resource ID or applies a central policy that cannot be forgotten by one endpoint.
  • Adds defense and verificationUses tests, database constraints or row-level security where appropriate, plus audit logs and safe denial responses.

Authentication, authorization, and web security42 questions

What is the difference between authentication and authorization, and how do cookie sessions compare with JWT access tokens?

Answer

  • Separates identity and permissionIdentity is established first; permission is checked for each action or resource.
  • Explains sessionsThe server stores session state and the browser sends an opaque cookie identifier.
  • Explains JWT trade-offsJWTs carry signed claims but require careful expiry, revocation, storage, and scope.

Briefly explain XSS, CSRF, and CORS. Which problem does each address?

Answer

  • Explains XSSUntrusted content executes script; escaping, safe rendering, and CSP reduce the risk.
  • Explains CSRFA browser sends ambient credentials on an attacker-triggered request; SameSite cookies or CSRF tokens can help.
  • Explains CORS correctlyCORS is a browser cross-origin policy, not authentication or server-to-server protection.

AWS application architecture42 questions

How would you deploy a React frontend and a Node.js API on AWS for a logistics application that must tolerate instance and availability-zone failures?

Answer

  • Separates workload layers appropriatelyServes static assets through object storage and a CDN, and runs the stateless API behind a managed entry point and load balancer or equivalent.
  • Designs for zone and instance failureUses multiple availability zones, health checks, replacement or scaling, and a highly available managed data tier with backups.
  • Includes security and operationsUses least-privilege roles, secret management, private data access, encryption, metrics, logs, alarms, deployment controls, and recovery testing.

For a new Node.js service on AWS, how would you compare Lambda with a container service such as ECS or a managed container platform?

Answer

  • Matches compute to workload shapeConsiders event-driven versus long-running work, request duration, traffic variability, startup sensitivity, and background processing.
  • Compares operational and technical constraintsDiscusses concurrency, database connections, runtime limits, networking, deployment control, local parity, and observability.
  • Evaluates cost and team fitCompares pay-per-use with continuously provisioned capacity and includes the operational maturity and tooling the team already has.

AWS reliability and security baseline43 questions

Review a Node.js service running on one virtual machine with a local database. What would you change first to improve availability, and why?

Answer

  • Identifies failure domains and critical stateThe machine, process, disk and availability zone are explicit failure points; the database state is the highest recovery risk.
  • Adds health-based redundant computeRuns stateless instances across failure domains behind health checks and load balancing.
  • Moves state to a managed durable serviceUses a managed database with backups, multi-zone options and a tested restore or failover plan.

A Node.js service needs to read one secret, consume one queue and update one database table. How would you design its AWS permissions?

Answer

  • Uses a workload role rather than static keysThe runtime receives temporary credentials through an attached role or task identity.
  • Scopes actions and resourcesAllows only required actions on the exact secret, queue and table, with conditions where useful.
  • Plans review and auditUses infrastructure as code, access logging and periodic review instead of manual policy drift.

How would you discuss RTO and RPO with business stakeholders for a core pricing or tracking application?

Answer

  • Explains the objectives plainlyRTO is acceptable restoration time; RPO is acceptable data loss measured in time.
  • Connects values to business impactUses operational deadlines, manual workarounds, customer impact and cost to choose realistic targets.
  • Turns targets into tested mechanismsSelects backup, replication and failover mechanisms and verifies them with restore exercises.

AWS Security and Least Privilege43 questions

How would you apply least privilege to a Node.js service running in AWS?

Answer

  • Uses workload rolesUses an execution role or task role with temporary credentials instead of hard-coded access keys.
  • Scopes actions and resourcesAllows only required API actions on named resources and uses conditions where practical.
  • Reviews actual useUses logs, access analysis, and separate environments to refine permissions and detect misuse.

A service needs database credentials and a third-party API key. How would you store, deliver, rotate, and audit them in AWS?

Answer

  • Uses a managed secret storeStores secrets in Secrets Manager or Parameter Store with encryption rather than code, images, or plain CI variables.
  • Restricts retrievalAllows only the workload role to read the specific secret and avoids exposing it in logs or frontend bundles.
  • Plans rotation and auditUses versioned rotation, application refresh behavior, CloudTrail, and incident revocation.

Where should authentication and authorization be enforced in a React and Node.js application, and what checks belong in AWS infrastructure?

Answer

  • Enforces authorization on the serverTreats frontend checks as user experience only and verifies identity and permissions for every protected backend action.
  • Uses layered controlsUses API authentication, application authorization, IAM for workload access, and network controls for exposure reduction.
  • Keeps business rules explicitSeparates infrastructure access from business permissions such as which tenant or shipment a user may access.

AWS service selection43 questions

Compare Lambda, a managed container service and Kubernetes for a new Node.js API with uneven traffic and a small team.

Answer

  • Explains Lambda fit and limitsLambda fits event-driven or bursty short work but has runtime, cold-start and execution constraints.
  • Explains managed container fitA managed container platform suits long-running HTTP services with more runtime control and moderate operational burden.
  • Avoids unjustified KubernetesKubernetes is justified by broader platform needs and expertise, not merely because the API may grow.

A pricing request may take minutes and must survive restarts. Sketch an AWS-based workflow and explain the role of each service category.

Answer

  • Creates durable asynchronous intakeThe API validates, creates an operation id and places work in a durable queue or workflow.
  • Uses controlled workers and durable stateWorkers process with bounded concurrency, retries and a durable status store or orchestrator.
  • Exposes completion safelyThe client polls a status resource, receives an event or notification, and can retrieve the result idempotently.

How would you estimate and control AWS cost for a prototype that may become a core logistics application?

Answer

  • Identifies workload cost driversEstimates requests, compute duration, storage, database access, logs and data transfer from explicit assumptions.
  • Keeps the prototype evolvable but simpleStarts with managed services and clean boundaries instead of prebuilding maximum scale.
  • Adds budgets and observabilityUses tags, budgets, alerts, dashboards and periodic unit-cost review before usage surprises grow.

AWS Web Application Architecture45 questions

Sketch a sensible AWS architecture for a React frontend and Node.js API used by an international logistics team.

Answer

  • Separates application responsibilitiesSeparates static frontend delivery, API entry, stateless compute, durable data, and background processing.
  • Chooses data and async paths deliberatelyDiscusses database choice, caching when justified, and queues for slow or bursty work.
  • Includes production concernsCovers identity, least privilege, availability zones, monitoring, backups, cost, and deployment.

Compare AWS Lambda with container-based compute for a Node.js backend. Which workload characteristics drive the choice?

Answer

  • Explains Lambda strengths and limitsMentions event-driven scaling and low operational work, balanced against duration, startup, concurrency, and runtime constraints.
  • Explains container strengths and costsMentions long-running processes, predictable resources, control, and suitability for steady traffic, with more operational responsibility.
  • Uses workload evidenceBases the choice on traffic shape, latency, connection model, background work, cost, and team capability.

Why should web application instances be stateless in a horizontally scaled AWS environment, and where should state go instead?

Answer

  • Explains replaceabilityExplains that any instance can handle a request and instances can scale or fail without losing unique state.
  • Places state in durable shared systemsUses databases, object storage, caches, or external session stores according to durability needs.
  • Recognizes local caching limitsAllows local ephemeral cache only when loss and inconsistency are acceptable and correctness does not depend on it.

Design a production-ready AWS architecture for a React application with a Node.js REST API and a relational database. Explain the main data flow and failure boundaries.

Answer

  • Defines a coherent service and data flowPresents a reasonable option such as S3 and CloudFront for the frontend, ALB plus ECS or Lambda for the API, and RDS for relational data.
  • Covers security and availability boundariesUses IAM roles, secrets management, encryption, protected database networking, multiple AZs where required, backups, and health checks.
  • Plans operations and costIncludes autoscaling, logs, metrics, traces, deployment strategy, alarms, recovery objectives, and an explanation of why the selected complexity is justified.

For a new Node.js backend feature, how would you decide between AWS Lambda and a container service such as ECS Fargate?

Answer

  • Starts from workload characteristicsConsiders request duration, traffic pattern, concurrency, background work, connection behavior, package size, and cold-start sensitivity.
  • Explains operational and control trade-offsLambda reduces server management and scales per invocation; containers offer steadier runtime control, long-lived processes, and broader compatibility.
  • Includes cost and team fitEvaluates utilization, idle capacity, observability, deployment tooling, limits, and team experience using a representative load estimate.

Azure Functions and Serverless Design42 questions

Design an Azure Function that processes invoice messages reliably. Cover duplicate delivery, retries, poison messages, database capacity, and secrets.

Answer

  • Makes processing idempotentUses a stable invoice or message id and a durable uniqueness check because the trigger can redeliver.
  • Defines retry and poison handlingSeparates transient and permanent failures, limits retries, and routes exhausted messages to a poison queue with diagnostics.
  • Controls capacity and credentialsLimits concurrency to database capacity and uses managed identity or a secure configuration service instead of embedded secrets.

Compare Azure Functions with a containerized Node.js service for a short event handler, a latency-sensitive API, and a continuously connected stream processor.

Answer

  • Chooses functions for bursty event workUses Functions for short, stateless, event-triggered workloads that benefit from managed scaling.
  • Evaluates API latency and controlConsiders cold starts, predictable capacity, networking, and runtime control for latency-sensitive APIs.
  • Rejects poor fit for permanent connectionsPrefers a long-running service for continuous stream processing or long-lived connections and explicit lifecycle control.

Azure Integration Service Selection32 questions

How would you choose between Azure Functions, a container platform, Service Bus, and API Management for an integration solution?

Answer

  • Starts with workload requirementsConsiders trigger model, duration, protocol, state, latency, traffic shape, networking, and operational ownership.
  • Separates service responsibilitiesUses compute for code execution, messaging for decoupling and buffering, and API Management for gateway concerns rather than treating them as substitutes.
  • Evaluates managed-service trade-offsDiscusses scaling limits, cold starts, delivery semantics, cost, private networking, observability, and lock-in.

An incoming API request must validate data, trigger slow downstream processing, and let the caller check status. Sketch an Azure-oriented design.

Answer

  • Separates acceptance from processingValidates and accepts quickly, creates an operation ID, and queues durable work rather than holding the HTTP request open.
  • Maps components coherentlyUses an API gateway or app endpoint, Service Bus queue or topic, worker compute, and a durable status store with clear responsibilities.
  • Includes reliability behaviorMentions idempotency, retries, dead-letter handling, timeout, correlation or tracing, and least-privilege identity.

bounded_context1 question

How would you identify bounded contexts for an intellectual-property platform used by filing, payments, renewals, and reporting teams?

Answer

  • Uses domain language and rulesLooks for terms that have different meanings and for groups of invariants and workflows that change together.
  • Makes ownership explicitIdentifies which context owns each decision and data change rather than drawing only technical layers.
  • Maps context relationshipsDescribes upstream and downstream relationships, integration contracts, and translation boundaries.
  • Validates boundaries empiricallyChecks change coupling, coordination cost, transaction needs, scale, and team cognitive load.

Browser security boundaries42 questions

What problem does CORS solve, how does a browser enforce it, and why is it not an authentication or server-security mechanism?

Answer

  • Starts from the same-origin policyExplains that browsers restrict scripts from reading responses from a different origin by default.
  • Explains CORS headers and preflightDescribes server opt-in with allowed origins, methods, headers, credentials, and OPTIONS preflight when required.
  • States the security boundary correctlyNotes that non-browser clients can still call the API and that authentication and authorization remain required.

A React application displays user-written delivery notes and uses cookie-based login. What controls would you apply against XSS and CSRF?

Answer

  • Uses safe output handling for XSSRenders untrusted data as text, avoids unsafe HTML insertion, sanitizes only when rich HTML is required, and considers CSP.
  • Protects state-changing requests from CSRFUses SameSite where suitable plus a CSRF token or origin validation for unsafe cookie-authenticated requests.
  • Hardens authentication cookiesUses Secure and HttpOnly and avoids exposing session credentials to JavaScript without a strong reason.

Caching and invalidation42 questions

How do you decide whether to cache data in the browser, CDN, application process, Redis, or database layer?

Answer

  • Defines the goalIdentifies repeated expensive reads and the acceptable staleness.
  • Matches location to scopeConsiders user-specific versus shared data, distribution, and instance sharing.
  • Plans invalidation and failureDefines TTL or invalidation, fallback, limits, and stampede protection.

A shipment status is cached but may be changed by several services. How would you keep it acceptably fresh?

Answer

  • Keeps a source of truthThe database or owning service remains authoritative.
  • Chooses an update strategyUses invalidation on write, event-driven updates, versioned keys, or short TTL.
  • Handles races and missed eventsUses version checks, idempotent updates, reconciliation, or TTL as a safety net.

Caching and invalidation32 questions

A shipment summary endpoint is expensive and receives many repeated requests. How would you decide whether and how to cache it?

Answer

  • Validates that caching addresses the bottleneckMeasures query and dependency cost, request repetition, hit potential, and the acceptable data freshness before adding a cache.
  • Defines safe keys and lifetimeIncludes tenant, permissions, filters, sort, and pagination where relevant, and chooses a bounded TTL and value size.
  • Plans invalidation and failure behaviorExplains update invalidation or versioning, stampede protection, stale tolerance, and whether the source remains available on cache failure.

Users sometimes see an old shipment status for several minutes after an update, but not consistently. How would you debug and fix the caching issue?

Answer

  • Maps all cache and source pathsIdentifies browser, CDN, API, distributed cache, and database layers plus every writer and reader of the status.
  • Checks keys, timing, and racesVerifies key dimensions, TTL, invalidation delivery, ordering, clock behavior, and whether a late read repopulates an old value after invalidation.
  • Chooses and observes an explicit consistency ruleUses versioned values, write-through or targeted invalidation, rejects older versions, and adds age or hit telemetry to verify the fix.

Choosing MongoDB, Redis, or a Relational Database42 questions

Choose a primary store for transactional orders, a flexible product catalog, and short-lived session plus rate-limit data. Explain the trade-offs rather than only naming technologies.

Answer

  • Chooses relational storage for ordersConnects orders to transactions, constraints, relationships, and durable source-of-truth requirements.
  • Explains document-store fitUses MongoDB when product data is naturally read as documents with varying attributes and aggregate-level updates.
  • Explains Redis fit and limitsUses Redis for fast temporary key-based state with TTL, while avoiding unsupported durability assumptions.

A design embeds an unbounded event history inside each customer document. What risks do you see, and how would you remodel it?

Answer

  • Identifies unbounded document growthNotes document-size limits, growing update cost, large reads, and hot-document contention.
  • Returns to access patternsAsks how events are queried, ordered, retained, and updated instead of assuming all data belongs in one document.
  • Proposes a bounded modelMoves the history to a separate collection or bucketed documents while keeping only bounded summary data embedded.

CI/CD and safe delivery32 questions

What stages would you include in a CI/CD pipeline for a React and Node.js application, and how would you keep feedback fast without weakening confidence?

Answer

  • Optimizes the feedback pathRuns linting, formatting or static analysis, type checks, and unit tests early, parallelizes independent checks, and reserves expensive tests for later.
  • Produces and promotes one artifactBuilds a versioned immutable artifact once, applies environment configuration at runtime, and keeps provenance and dependency or security checks.
  • Controls and verifies production exposureUses staging or preview checks, smoke tests, canary or blue-green rollout, user-impact metrics, and a tested rollback or forward-fix path.

You need to replace a required database column used by both the current and next application versions. How would you deploy the change without downtime?

Answer

  • Expands the schema compatiblyAdds the new nullable column or structure without removing the old one and deploys code that can operate with both versions.
  • Migrates and verifies data safelyBackfills in bounded batches, observes load and errors, validates completeness, and handles writes during the transition with dual write or derived logic.
  • Contracts only after adoptionSwitches reads gradually, confirms old versions and jobs no longer depend on the field, then enforces constraints and removes the old column in a later release.

CI/CD and Safe Delivery43 questions

What stages and quality gates would you put in a CI/CD pipeline for a React and Node.js application?

Answer

  • Builds once and validates codeIncludes formatting or linting, type checks, tests, dependency checks, and one versioned artifact.
  • Checks integration and deploymentIncludes contract or migration checks, infrastructure validation, and environment smoke tests.
  • Promotes safelyUses protected approvals where justified, gradual rollout, health checks, monitoring, and rollback.

A release changes a database column used by the current API. How would you deploy it without requiring frontend and backend downtime?

Answer

  • Uses expand-and-contractAdds backward-compatible schema first, deploys code that supports old and new forms, migrates data, then removes the old form later.
  • Sequences independent deploymentsEnsures old and new application versions can coexist during rollout and rollback.
  • Verifies migration and healthMonitors data correctness, errors, latency, and migration progress with a clear stop plan.

What problems do feature flags solve, and what risks do they add compared with simply deploying a new version?

Answer

  • Explains decoupled releaseUses flags to separate code deployment from user exposure, support gradual rollout, and disable behavior quickly.
  • Explains flag debt and complexityMentions multiplied code paths, inconsistent states, permission risk, testing burden, and stale flags.
  • Manages lifecycleRequires ownership, expiry, audit, safe defaults, and cleanup after rollout.

CI/CD and Safe Releases42 questions

Design a practical CI/CD pipeline for this full-stack application from pull request to production.

Answer

  • Defines useful pre-merge gatesRuns lint, type checking, focused tests, security or dependency checks and builds the application on each pull request.
  • Promotes one versioned artifactBuilds an immutable image once, records its version and promotes the same artifact through test and production environments.
  • Plans migration and controlled exposureChecks backward-compatible migrations, deploys with health checks, uses a gradual rollout or flag and defines rollback criteria.

You need to rename a heavily used database column while old and new application instances may run together. How would you deploy the change?

Answer

  • Starts with an additive schema changeAdds the new column without removing the old one and deploys application code that can tolerate both.
  • Migrates reads and data safelyDual-writes or synchronizes during transition, backfills existing rows in bounded batches and moves reads after verification.
  • Removes old state only after proofMonitors old-column usage and errors, then removes old code and the column in a later release with a backup or recovery plan.

CI/CD for Integration Services42 questions

What stages would you include in a CI/CD pipeline for a Node.js integration service?

Answer

  • Creates one traceable artifactBuilds and versions one immutable image or package and promotes it without rebuilding.
  • Uses layered integration checksIncludes unit and static checks plus contract, schema, integration, migration, and security validation.
  • Controls deployment riskUses environment config, approvals where justified, canary or blue-green rollout, health gates, and rollback.

A new release requires a database schema change while old and new service versions may run together. How would you deploy it safely?

Answer

  • Uses expand-and-contractAdds compatible schema first, deploys code that can work during transition, migrates data, and removes old schema only later.
  • Controls migration executionMakes migrations versioned, observable, retry-safe where possible, tested on realistic volume, and separated from risky startup races.
  • Plans rollback and roll-forwardRecognizes that destructive schema changes may block rollback and prepares backups, feature flags, or a roll-forward procedure.

CI/CD Pipelines and Safe Deployment42 questions

Design a CI/CD pipeline for a Node.js API from pull request to production. Which gates, artifacts, deployment strategy, and recovery mechanisms would you include?

Answer

  • Builds one immutable artifactPins dependencies, produces a versioned container or package once, records provenance, and promotes the same artifact.
  • Uses layered automated gatesIncludes lint, unit, integration, contract, migration, dependency, and security checks with clear failure criteria.
  • Deploys progressively with recoveryUses readiness, canary or rolling rollout, observability gates, and a tested rollback or roll-forward path.

A release must rename a heavily used database column while old and new application versions overlap during rolling deployment. How would you release it safely?

Answer

  • Expands compatibly firstAdds the new column without removing the old one and deploys code that can work during overlap.
  • Migrates and verifies dataBackfills safely, dual-writes or synchronizes during transition, and verifies counts and correctness.
  • Removes only after retirementSwitches all reads, confirms old versions and consumers are gone, then removes the old column in a later release.

CI/CD quality gates43 questions

Sketch a CI/CD pipeline for a React frontend and Node.js backend deployed to AWS. Which checks belong at each stage?

Answer

  • Creates fast pull-request gatesRuns formatting or linting, type checks, focused unit tests, secret or dependency checks and production builds.
  • Builds and promotes immutable artifactsStores versioned frontend and backend artifacts once and promotes the exact outputs.
  • Uses environment and release verificationRuns integration or contract tests, deploys progressively, checks health metrics and can roll back.

A deployment completes, but error rate rises and one business workflow starts failing. What should the pipeline and team do?

Answer

  • Uses automatic release health criteriaMetrics, logs and synthetic or smoke checks compare the new release with a known baseline.
  • Stops or reverses the rolloutPauses promotion, routes traffic away or rolls back the immutable artifact before extended diagnosis.
  • Preserves evidence and follows upUses release identifiers and traces to isolate the change, then adds a regression test or safer rollout rule.

How would you divide tests between frontend units, backend units, API contracts, integrations and end-to-end flows for this role?

Answer

  • Uses fast tests for local logicUnit or component tests cover business rules, transformations and UI behavior with quick feedback.
  • Protects service boundariesContract and integration tests verify schemas, database behavior and important external adapters.
  • Keeps end-to-end tests focusedA small reliable set covers critical user journeys instead of duplicating every edge case through the UI.

container_orchestration1 question

What is the difference between Kubernetes readiness, liveness, and startup probes, and how can badly designed probes cause an outage?

Answer

  • Defines readinessExplains that readiness controls whether the pod receives traffic and may reflect temporary inability to serve.
  • Defines livenessExplains that liveness decides whether the container should be restarted because it cannot recover itself.
  • Defines startupUses a startup probe to protect slow initialization from premature liveness failures.
  • Explains probe-induced outagesWarns against checking shared dependencies in liveness, overly aggressive thresholds, expensive checks, and synchronized restarts.

conway_law1 question

What is Conway's Law, and how should it influence the design and ownership of an API platform?

Answer

  • Defines Conway's LawExplains that system structures tend to mirror the communication structures of the organizations that design them.
  • Connects teams and architectureShows how shared ownership and frequent cross-team coordination create coupled interfaces and releases.
  • Uses the inverse Conway maneuverConsiders aligning team ownership and communication with the desired modular architecture.
  • Avoids determinismTreats the law as a strong influence and validates technical boundaries with domain and operational needs.

core_web_vitals1 question

What are Core Web Vitals, what do the current metrics measure, and how would you use them to investigate a slow storefront?

Answer

  • Names the current metricsCorrectly identifies LCP, INP, and CLS as the core user-centric loading, interaction, and visual-stability metrics.
  • Explains what each measuresDescribes largest meaningful content appearance, interaction response latency across a visit, and unexpected layout movement.
  • Distinguishes field and lab dataUses real-user monitoring for production experience and lab tools for repeatable diagnosis, recognizing that the results can differ.
  • Connects symptoms to causesRelates LCP to server, image, CSS, and render path; INP to long tasks; and CLS to missing dimensions or late content.

CPU-bound Work and Node.js Scaling42 questions

A request performs a 500 ms CPU-heavy transformation. Compare keeping it in the handler, using worker threads, and moving it to a separate background service.

Answer

  • Rejects event-loop blockingExplains that the synchronous transformation delays all requests and health checks in the process.
  • Explains worker-thread fitUses a bounded worker pool for CPU work that benefits from shared process deployment and low transfer overhead.
  • Explains separate-service fitChooses a background service when independent scaling, durable queues, or stronger failure isolation matters.

How would you use several CPU cores for a stateless Node.js API, and what state or connection assumptions must change when multiple processes or containers are running?

Answer

  • Runs multiple service instancesUses multiple processes or containers behind a load balancer to consume more CPU cores.
  • Removes process-local assumptionsStores shared sessions, jobs, locks, or pub/sub state outside one process when consistency requires it.
  • Handles connections during deploymentUses readiness, connection draining, and graceful shutdown so instances can be replaced safely.

cqrs_pattern2 questions

What is CQRS, and what advantage can it provide? Also explain why it is not an alternative to REST.

Answer

  • Defines command-query separationExplains that commands change state while queries read state, with separate code paths or models.
  • Explains independent optimizationShows how read and write models can use different shapes, indexes, scaling, or storage when justified.
  • Names the costMentions synchronization, eventual consistency, duplicated models, operational complexity, and debugging.
  • Separates CQRS from RESTStates that REST is an interface style while CQRS is an internal design pattern and that they can be used together.

A team proposes separate read and write databases for a simple CRUD service. How would you decide whether CQRS is justified?

Answer

  • Looks for a real asymmetryAsks whether reads and writes differ materially in rules, shape, volume, latency, scale, or ownership.
  • Chooses the smallest useful formConsiders separate handlers or models in one application before separate databases and infrastructure.
  • Evaluates consistency and operationsAccounts for event delivery, projection rebuilds, monitoring, data repair, and eventual consistency.
  • Can reject the patternRecommends ordinary CRUD or a modular design when the added complexity has no evidence-backed benefit.

Data Exchange Translation41 question

Several business units and external customers use different representations of the same intellectual-property concepts. How would you design the translation layer?

Answer

  • Defines explicit external contractsUses versioned schemas, validation, ownership, and clear error semantics for each integration surface.
  • Protects bounded contextsMaps at boundaries and avoids making one canonical transport model the internal domain model of every service.
  • Preserves traceabilityKeeps source identifiers, correlation data, mapping version, and processing history for support and replay.
  • Handles partial or unknown dataDefines reject, quarantine, default, and manual-resolution policies with monitoring.

Database Connection Pooling42 questions

How would you choose a connection-pool size for a horizontally scaled Node.js service?

Answer

  • Starts from total database capacityAccounts for the database connection limit, reserved operational capacity, other applications, and maximum instance count.
  • Considers workload behaviorUses query duration, transaction duration, request concurrency, database CPU or I/O capacity, and acceptable queueing.
  • Tunes with pool metricsMonitors active, idle, waiting, acquisition timeout, utilization, and database saturation under load.

API latency rises and logs show connection acquisition timeouts, but individual queries are normally fast. What would you investigate?

Answer

  • Investigates connection hold timeChecks long transactions, calls to external services while holding a connection, unconsumed result streams, and slow commit or rollback.
  • Checks leaks and total multiplicationLooks for missing release paths, failed cleanup, unexpected worker or instance count, and per-process pools.
  • Checks database-side blockingExamines locks, waiting transactions, connection states, resource saturation, and whether fast averages hide a few blocked operations.

Database transactions and concurrent updates42 questions

Two dispatchers edit the same shipment at nearly the same time. How would you prevent the second save from silently overwriting the first?

Answer

  • Identifies the read-modify-write raceExplains that both users read the same old state and later saves can overwrite one another.
  • Uses an explicit concurrency controlProposes a version column or conditional update, and compares it with locking when conflicts are frequent or costly.
  • Handles the conflict visiblyReturns a conflict such as 409 and lets the user reload, merge, or consciously overwrite rather than hiding data loss.

Creating a booking writes a booking row, reserves capacity, and publishes an event. Which operations belong in one database transaction, and how would you handle event publication?

Answer

  • Defines the business invariantGroups the booking and capacity reservation atomically when they must never disagree.
  • Keeps network publication outside the transactionAvoids holding database locks while waiting for a broker or external service.
  • Uses a reliable event handoffWrites an outbox record in the same transaction and publishes it asynchronously with idempotent consumers.

Database Transactions and Isolation52 questions

Two requests try to reserve the final available item at the same time. How would you make the operation correct in PostgreSQL or SQL Server?

Answer

  • States the business invariantDefines that available quantity must never fall below zero and only one reservation may consume the last unit.
  • Enforces concurrency in the databaseUses an atomic conditional update, row lock, serializable transaction, or optimistic version check.
  • Returns a controlled conflictTreats the losing transaction as a normal conflict, rolls back cleanly, and returns a stable response.

A code opens a database transaction, writes an order, calls a payment API, then commits. What problems can this cause and how would you redesign it?

Answer

  • Explains long-transaction costNotes that the external call holds a connection and locks while latency and failure are outside database control.
  • Identifies the dual-write problemExplains that payment and database commit cannot normally be one atomic transaction, so either side can succeed alone.
  • Proposes durable coordinationUses an order state machine with an outbox or durable job, idempotent payment calls, and compensation for failure.

db_transactions1 question

What does a database transaction guarantee, and how would you choose an isolation level for concurrent renewal payments?

Answer

  • Explains the useful ACID guaranteesConnects atomicity, consistency, isolation, and durability to observable behavior rather than only expanding the acronym.
  • Understands concurrency anomaliesMentions dirty, non-repeatable, phantom, lost update, or write-skew risks where relevant.
  • Starts from the business invariantDefines what must not happen, such as charging twice or paying a closed renewal, before choosing a level.
  • Balances isolation and throughputUses constraints, optimistic locking, explicit locks, or retries and accounts for blocking and deadlocks.

DDD Tactical Design41 question

Explain entities, value objects, aggregates, and aggregate roots. How do you decide an aggregate boundary?

Answer

  • Distinguishes entities and value objectsUses identity for entities and value-based immutable semantics for value objects.
  • Defines aggregate and rootExplains that the aggregate is a consistency boundary and external changes go through its root.
  • Chooses boundaries by invariantsGroups only data and rules that must be consistent together immediately.
  • Avoids oversized aggregatesRecognizes that large aggregates increase contention, load cost, and coupling and may communicate through events.

Design System Architecture42 questions

How would you design a reusable Select component for a shared React design system used by both a storefront and an internal CRM?

Answer

  • Defines a focused public APIDesigns controlled and uncontrolled use deliberately, clear value and event contracts, composition points, and a limited variant surface.
  • Builds accessible interactionCovers labels, keyboard navigation, focus management, announcements, validation state, and appropriate semantic patterns.
  • Separates primitive from product rulesKeeps general selection behavior in the design system and customer-specific fetching or permissions in product-owned wrappers.
  • Documents and tests statesProvides Storybook examples, behavior and accessibility tests, visual regression, and migration guidance for API changes.

Two products already contain many inconsistent components. How would you introduce a shared design system without blocking product delivery or creating a permanent second UI stack?

Answer

  • Starts with inventory and prioritiesFinds repeated patterns, accessibility risks, high-change surfaces, and components that offer the greatest product value.
  • Builds foundations before breadthEstablishes tokens, theming, typography, spacing, focus, and a few high-quality primitives rather than copying every existing component.
  • Migrates incrementallyUses wrappers, codemods, feature work, and deprecation milestones to move consumers in shippable slices.
  • Defines governance and exit criteriaCreates contribution rules, ownership, versioning, support policy, adoption metrics, and criteria for removing old components.

design_documentation1 question

What should a systems design document contain for a new API feature, and how do non-functional requirements change the design?

Answer

  • States context and measurable requirementsIncludes goals, non-goals, constraints, workload, stakeholders, and measurable NFRs.
  • Compares realistic alternativesShows at least two viable options with trade-offs, costs, risks, and reasons for the decision.
  • Shows the relevant system behaviorCovers components, data ownership, API contracts, security, failure paths, and operational dependencies at the needed level.
  • Plans delivery and validationIncludes migration, rollout, rollback, testing, observability, ownership, and open questions.

Distributed Consistency41 question

A command returns success, but the query API may show the old state for several seconds. How would you make this behavior correct and understandable?

Answer

  • Defines the authoritative write boundaryKeeps immediate invariants and duplicate prevention in the service or transaction that owns the write.
  • Makes staleness explicitDefines expected delay and response semantics instead of presenting an asynchronously updated read as immediately current.
  • Designs a usable client experienceUses operation status, optimistic UI with confirmation, polling, push updates, or direct command result where appropriate.
  • Provides observability and repairTracks lag, failed projections, retries, dead letters, and reconciliation.

Distributed Failure Handling and Observability52 questions

A public request has a two-second deadline and calls two downstream services. How would you allocate timeouts and retries without exceeding the user deadline?

Answer

  • Propagates an overall deadlineStarts from the two-second budget and passes remaining time rather than giving every call a fresh long timeout.
  • Budgets retries safelyRetries only idempotent transient failures when enough time remains, with a small attempt limit and jitter.
  • Measures dependency outcomesRecords attempt count, timeout reason, downstream latency, and final user outcome in traces and metrics.

A downstream service slows down, callers retry, connection pools fill, and unrelated endpoints fail. How would you stop the cascade and prove recovery?

Answer

  • Contains the failing dependencyApplies short timeouts, circuit breaking, concurrency limits, or temporary traffic reduction.
  • Reduces retry amplificationFinds retries at every layer, removes duplicate attempts, adds backoff and jitter, and enforces an overall budget.
  • Proves recovery end to endUses traces and metrics to show falling queue or pool pressure, restored tail latency, and no continued error amplification.

Docker Delivery Basics31 question

A production Dockerfile copies the whole repository, installs dev dependencies, runs as root and embeds an environment file. What would you change and why?

Answer

  • Builds a small deterministic imageUses .dockerignore, pinned runtime, lockfile installs and a multi-stage build with only production artifacts in the final image.
  • Removes secrets and root executionInjects configuration at runtime, keeps secrets out of layers and runs the process as a non-root user.
  • Makes runtime behavior explicitUses an immutable version tag, clear startup command, signal handling and a meaningful health check.

Docker Packaging for Node.js Services32 questions

What would you include in a production-ready Docker setup for a Node.js and TypeScript service?

Answer

  • Builds a reproducible minimal imageUses pinned base images, lockfile-based installation, multi-stage builds, and only production runtime artifacts.
  • Applies container security basicsRuns as non-root, avoids embedded secrets, scans dependencies or images, and reduces unnecessary packages and permissions.
  • Supports lifecycle operationsHandles SIGTERM, graceful shutdown, readiness or liveness behavior, stdout logs, and runtime configuration.

During a rolling deployment, requests fail when old containers are terminated. How would you diagnose and fix the shutdown sequence?

Answer

  • Stops new traffic firstMarks the instance unready or removes it from routing before termination and allows propagation time.
  • Drains in-flight workHandles SIGTERM, stops accepting work, waits for active requests or messages within a deadline, and closes resources cleanly.
  • Uses shutdown evidenceAdds logs and metrics for signals, active work, forced kills, termination duration, and failed retries.

End-to-End Feature Delivery52 questions

Describe how you would take a request for reusable assignment templates from a research idea to a production feature you can support.

Answer

  • Clarifies the real workflow and outcomeAsks who creates, shares, edits and owns templates, and defines observable acceptance criteria before implementation.
  • Designs the whole change coherentlyCovers UI states, API contract, schema and migration, authorization, testing and error handling as one feature.
  • Plans safe release and iterationUses staged rollout or a flag, monitors usage and failures, gathers pilot feedback and defines rollback or cleanup.

Design a feature where students submit answers and teachers review, comment and publish feedback. Focus on the main components, data consistency, permissions and failure handling.

Answer

  • Clarifies scope and critical flowsDefines roles, draft versus published states, edit rules, expected scale and privacy needs before choosing architecture.
  • Proposes a coherent data and API modelModels submissions, feedback revisions and publication state with transactions, stable contracts and concurrency protection.
  • Covers failures and operationsIncludes idempotent submission, safe retries, notifications outside the core transaction, auditability, metrics and rollout.

End-to-end feature design55 questions

Design an end-to-end feature that lets an operations user manually reprice a shipment. Cover frontend, backend, data, security and rollout.

Answer

  • Traces one complete user flowDefines selection, current price display, edit or command, confirmation and clear success or failure states.
  • Protects business and data integrityUses validation, authorization, optimistic concurrency or versioning, and audit history.
  • Includes tests, telemetry and rolloutDefines contract and end-to-end tests, key metrics, feature flag rollout and rollback.

How would you split and coordinate work when one developer owns both sides of a new feature but frontend and backend may deploy independently?

Answer

  • Defines the contract before coupling implementationsAgrees schemas, error behavior and examples, ideally with generated clients or contract tests.
  • Uses a backward-compatible deployment sequenceDeploys additive backend support first, then the frontend, and removes old behavior only after consumers migrate.
  • Delivers a thin vertical sliceBuilds a small usable path with tests and telemetry before expanding secondary cases.

What does done mean for a business-critical full-stack feature beyond the code being merged?

Answer

  • Validates acceptance behaviorAcceptance criteria and important failure cases pass with representative data and permissions.
  • Includes production readinessDeployment, migration, monitoring, alerting, security and rollback are ready.
  • Clarifies support and measurementThe team knows who owns incidents and which business and technical metrics show success.

A stakeholder says, "We need AI-assisted shipment exception handling." What questions would you ask before proposing a solution, and how would you turn the answers into an end-to-end design?

Answer

  • Clarifies the real workflow and success criteriaAsks who acts, what exception is handled, what decision is automated, current pain, acceptable error, volume, latency, and measurable success.
  • Builds a complete vertical sliceCovers UI states, API and data contract, model or rule invocation, validation, authorization, audit history, and operational telemetry.
  • Chooses a safe incremental scopeStarts with recommendation or draft mode, defines human approval and fallback, evaluates quality, and rolls out behind a feature flag.

The business wants real-time repricing, a full audit history, automatic notifications, and AI explanations in the first release. How would you challenge and sequence the scope without sounding obstructive?

Answer

  • Reframes features as outcomes and risksAsks which user problem is most urgent, what evidence exists, and which failure would be most costly.
  • Proposes a complete but narrow vertical MVPSelects one useful workflow with required validation, permissions, auditability, UI states, and operations rather than building fragments of everything.
  • Sequences dependencies and validates assumptionsUses prototypes, feature flags, staged rollout, metrics, and a clear next-step roadmap based on learning.

End-to-end feature design52 questions

A logistics operator needs to flag a shipment exception, add a reason, notify the responsible team, and track resolution. How would you design this feature end to end?

Answer

  • Defines the workflow and invariantsIdentifies actors, valid status transitions, required reason data, ownership, and what must be auditable.
  • Connects UI, API, and persistence coherentlyProposes an API that enforces transitions, an appropriate data model, and explicit loading, error, conflict, and permission states in the UI.
  • Plans reliable delivery and rolloutDiscusses reliable notification, idempotency, tests, metrics, feature flags, and a safe migration or rollback path.

A stakeholder asks for a real-time dashboard because the current shipment overview feels slow. What would you clarify before choosing WebSockets, polling, or another solution?

Answer

  • Clarifies the actual user problemAsks which decisions are delayed, what feels slow, who uses the dashboard, and what outcome defines success.
  • Quantifies technical constraintsDetermines acceptable freshness, update frequency, user count, fan-out, ordering, reconnect behavior, and infrastructure limits.
  • Chooses the simplest sufficient mechanismCompares refetching, polling, server-sent events, and WebSockets by complexity, latency, bidirectionality, and operational cost.

Engineering Ownership and Technical Debt42 questions

Describe how you would take a new integration feature from an ambiguous request through production delivery and maintenance.

Answer

  • Clarifies behaviour and constraintsIdentifies stakeholders, success and failure cases, non-functional needs, dependencies, and acceptance criteria.
  • Makes the design reviewableDocuments the contract, data flow, risks, trade-offs, rollout, and operational behaviour before implementation hardens assumptions.
  • Owns release and operationIncludes tests, telemetry, deployment, verification, documentation, support ownership, and prioritized follow-up work.

A legacy service has poor tests, outdated dependencies, duplicated code, and occasional production failures. How would you decide what to fix first and obtain agreement?

Answer

  • Uses evidence and impactRanks items by production incidents, security exposure, delivery friction, user impact, and likelihood rather than personal preference.
  • Creates an incremental planChooses enabling work first, such as characterization tests and observability, then fixes high-risk paths in small releasable steps.
  • Makes ownership and outcomes explicitDocuments cost, expected benefit, owner, milestone, and success metric so stakeholders can make a visible trade-off.

Entity Framework Core Persistence42 questions

An EF Core list endpoint is slow and memory-heavy. How would you investigate and improve it?

Answer

  • Inspects the actual queryLooks at generated SQL, execution time, query plan, row count, round trips, and production telemetry.
  • Reduces loaded data and trackingUses projection, pagination, AsNoTracking, and avoids premature materialization.
  • Finds N+1 and loading issuesReviews lazy loading, Include usage, split queries, and repeated navigation access.
  • Connects ORM behavior to database designChecks filters, sorting, cardinality, indexes, statistics, and query selectivity.

How would you handle concurrent updates and deploy a breaking database change safely in an EF Core application?

Answer

  • Uses optimistic concurrency where appropriateExplains row version or concurrency tokens and detects that the stored row changed after it was read.
  • Defines conflict behaviorChooses retry, merge, reload, or user-visible conflict based on the business operation.
  • Uses expand-and-contractAdds compatible schema first, deploys code that tolerates both shapes, backfills, switches reads, and removes later.
  • Plans operational safetyConsiders lock duration, online indexes, batch size, rollback, monitoring, and mixed-version deployment.

Enum and Schema Evolution51 question

Is adding a new value to an enum a breaking change? Answer for both requests and responses, and include generated clients.

Answer

  • Rejects a universal yes or noStates that compatibility depends on direction, schema semantics, client implementation, and unknown-value handling.
  • Explains response-side riskNotes that older clients, generated SDKs, deserializers, or exhaustive switches may reject a new server-produced value.
  • Explains request-side compatibilityNotes that allowing an additional client input is usually compatible for old clients, but servers and validation across versions still matter.
  • Proposes safe enum designMentions open enums, unknown-value fallbacks, capability negotiation, staged rollout, or monitoring.

Error handling and resilience55 questions

A carrier booking request times out. How do you decide whether and how to retry it safely?

Answer

  • Recognizes the ambiguous outcomeA timeout does not prove the carrier failed; the booking may already exist.
  • Requires idempotency or reconciliationUses an idempotency key, provider operation id or status lookup before repeating a side effect.
  • Uses a bounded policyRetries only transient failures with timeout, backoff, jitter and a limit, then moves to recovery.

What problem does a circuit breaker solve, and where would you place it when a Node.js service depends on an unstable pricing API?

Answer

  • Explains failure containmentIt stops repeated calls to a failing dependency so resources and latency are protected.
  • Explains recovery probingAfter opening, it waits and later allows limited probe calls before closing.
  • Places it at the dependency boundaryWraps the pricing client with metrics and a deliberate fallback or error path, not the whole application blindly.

How would errors flow from a database or external client through domain and API layers without being swallowed or leaking implementation details?

Answer

  • Classifies technical and domain failuresSeparates expected domain outcomes, invalid input, missing data and unexpected infrastructure failures.
  • Preserves the original cause and contextAdds operation and identifiers while retaining the cause for logs and tracing.
  • Translates only at boundariesMaps internal failures to stable API errors at the HTTP boundary and avoids leaking database or stack details.

How would you design error handling from a Node.js service through a REST API to a React UI?

Answer

  • Classifies errors by responsibilitySeparates validation, authentication, authorization, conflict, dependency, transient, and unexpected failures.
  • Separates public errors from internal diagnosticsReturns stable codes and safe messages while logging causes, stack traces, correlation ids, and relevant context internally.
  • Defines usable UI recoveryPreserves user input, distinguishes field errors from global failures, and offers retry or an alternative action when appropriate.

A pricing dependency times out after receiving a request, so you do not know whether it completed the operation. Should you retry, and what safeguards are needed?

Answer

  • Recognizes the ambiguous outcomeExplains that a timeout does not prove failure and a repeated write may duplicate the side effect.
  • Requires safe retry semanticsUses an idempotency key, operation identifier, conditional write, or status lookup before repeating the operation.
  • Bounds retries and protects the systemUses timeouts, exponential backoff with jitter, retry limits, circuit breaking, and a fallback or async recovery path.

Event Contracts and Schema Evolution52 questions

Design an OrderPlaced event contract that can be traced, deduplicated, versioned, and safely consumed by teams you do not control.

Answer

  • Defines a clear business factUses past tense and documents exactly what completed business action the event represents.
  • Includes stable metadataIncludes event id, type, occurred time, producer, schema version, correlation, and causation where useful.
  • Keeps a stable consumer-oriented payloadIncludes the business data consumers need without exposing an internal database row or requiring a synchronous callback to the producer.

You need to rename a field and change its meaning while old consumers and historical events still exist. What migration options do you have?

Answer

  • Recognizes semantic breaking changeExplains that renaming or changing meaning can break consumers even if the wire type remains valid.
  • Offers safe coexistence optionsProposes an additive new field, a new event version or type, dual publishing, or an upcaster based on constraints.
  • Plans rollout and removalUses schema checks, consumer inventory, telemetry, a migration window, and explicit retirement criteria.

Frontend Build Tooling32 questions

How would you compare Rspack, Vite, and webpack for a large React application, and which evidence would you gather before migrating?

Answer

  • Compares relevant dimensionsEvaluates development startup and updates, production build, plugin or loader compatibility, output control, debugging, and ecosystem maturity.
  • Starts from current requirementsInventories existing configuration, custom transforms, browser targets, test integration, deployment paths, and team knowledge.
  • Uses measurable baselinesRecords cold start, update latency, CI build time, bundle size, chunk behavior, and production runtime before deciding.
  • Plans migration riskRuns parallel builds or a representative slice, compares assets and tests, and keeps a fallback instead of rewriting everything at once.

A new Rspack build works in development but production shows missing assets and lazy-loaded routes fail. How would you investigate?

Answer

  • Reproduces the production environmentRuns the production build behind the same base path, static server, CDN or cache rules, and browser targets used after deployment.
  • Inspects generated asset referencesChecks public path, asset URLs, chunk manifest, content hashes, case sensitivity, and deployment completeness.
  • Checks dynamic import and routing behaviorVerifies code-splitting boundaries, lazy imports, error handling, and whether old HTML or service-worker caches reference removed chunks.
  • Compares old and new outputsDiffs known-good webpack and Rspack output, source maps, environment substitution, and network requests to isolate the change.

Frontend Quality Gates52 questions

What checks and delivery practices would you use to keep a React storefront, CRM, and shared UI library safe as several teams change them?

Answer

  • Builds a fast base pipelineRuns formatting, ESLint, TypeScript, unit and component tests, and dependency or build checks on every change.
  • Uses targeted higher-level checksAdds accessibility and visual regression for components plus a small number of critical end-to-end journeys.
  • Protects shared-library consumersTests component contracts and representative consuming applications, versions breaking changes, and provides migration guidance.
  • Treats production as validationUses staged rollout, monitoring, Web Vitals, error tracking, and a tested rollback or feature-flag path.

Which tools and checks help guarantee frontend code quality, and what can each one prove or not prove?

Answer

  • Explains static checksDescribes TypeScript, ESLint, formatting, and build validation as fast checks for types, patterns, consistency, and compilation.
  • Explains test layersDistinguishes unit, component or integration, visual, accessibility, and end-to-end tests by the failures they detect.
  • Includes review and CI enforcementMentions code review, CI, branch protection, dependency scanning, and repeatable local commands.
  • States their limitsExplains that passing tools cannot prove product correctness, usability, production behavior, or sound architecture.

Frontend Technical Ownership43 questions

Describe how you would take an ambiguous frontend feature from initial request to production when you are the senior engineer responsible for technical decisions.

Answer

  • Clarifies the problem and constraintsIdentifies user outcome, scope, permissions, data, accessibility, performance, compatibility, timeline, and success measures.
  • Aligns cross-functional contractsWorks with backend, QA, design, and product on API, states, edge cases, test strategy, and ownership boundaries.
  • Makes and records trade-offsCompares options, documents the decision and assumptions, and defines migration or rollback where risk warrants it.
  • Owns incremental deliverySlices work, reviews and mentors, monitors release behavior, and follows through on cleanup and lessons learned.

How would you review code and mentor less experienced developers in a distributed asynchronous team without turning review into gatekeeping?

Answer

  • Sets review prioritiesFocuses first on correctness, security, accessibility, architecture, and user impact while automating style and mechanical checks.
  • Explains reasoning constructivelyDistinguishes blocking issues from suggestions, gives context and alternatives, and asks questions that build understanding.
  • Designs for asynchronous clarityUses small pull requests, clear descriptions, decision links, examples, and response expectations across time zones.
  • Creates learning and autonomyPairs selectively, delegates bounded ownership, follows up on recurring patterns, and updates documentation or tooling.

There is no frontend lead above you. The team needs to choose how to migrate routing across the CRM and storefront. How would you make, communicate, and own that decision?

Answer

  • Clarifies decision contextCollects product goals, public URL constraints, SEO, permissions, analytics, deployment, timelines, and team capability.
  • Compares realistic optionsEvaluates keeping the current router, incremental migration, and replacement against cost, risk, compatibility, and reversibility.
  • Makes the decision visibleWrites a concise decision record, includes rejected alternatives and assumptions, and asks relevant teams to review it.
  • Owns delivery and evidenceBreaks work into safe slices, defines metrics and rollback, mentors contributors, and revises the plan if evidence changes.

Full-Stack Feature Design53 questions

A product stakeholder asks for real-time shipment tracking. What questions would you ask before choosing the technical solution?

Answer

  • Clarifies the business outcomeAsks who needs the information, what decision it supports, and how fresh it must be.
  • Clarifies scale and constraintsAsks about update rate, users, source systems, security, reliability, cost, and regulatory constraints.
  • Defines the first sliceSeparates must-have behavior from later enhancements and defines acceptance criteria.

Describe how you would implement and release the first end-to-end slice of a new pricing rule across React, Node.js, and AWS.

Answer

  • Defines the contract and ruleStarts with examples, acceptance criteria, permissions, and a versioned API contract.
  • Maps the end-to-end pathCovers UI states, API validation, domain logic, persistence or integration, and observability.
  • Plans safe deliveryUses tests, feature flags or limited rollout, migration sequencing, monitoring, and rollback.

How do you decide whether a new feature deserves a new service, belongs in the existing application, or should begin as a prototype?

Answer

  • Uses domain and ownership boundariesLooks for independent ownership, data, scaling, security, and release needs rather than using service count as a goal.
  • Includes operational costConsiders deployment, monitoring, failure modes, testing, and coordination introduced by another service.
  • Uses prototypes to reduce uncertaintyBuilds a time-boxed prototype when the largest risk is technical or product uncertainty, without treating it as production code automatically.

Full-Stack Testing Strategy48 questions

How would you divide tests for a React and Node.js feature among unit, integration, contract, and end-to-end levels?

Answer

  • Maps tests to risksStarts from business rules, component behavior, data integration, external contracts, and critical user journeys.
  • Uses levels deliberatelyPlaces calculations and component behavior low, real infrastructure at integration level, and only key workflows end to end.
  • Balances confidence and feedbackExplains speed, isolation, realism, maintenance, and diagnostic trade-offs.

A React test breaks after a harmless refactor because it asserts internal state and child component calls. How would you rewrite it?

Answer

  • Tests observable behaviorInteracts through accessible UI and asserts what a user can see or do.
  • Mocks at real boundariesMocks network or browser boundaries when necessary rather than internal component implementation.
  • Handles asynchronous behavior correctlyWaits for visible state changes and avoids fixed sleeps or manual internal state updates.

Your CI suite is slow and flaky, so developers rerun failed jobs until they pass. How would you improve it?

Answer

  • Classifies failures and durationCollects timing and flake data by test and separates product failures from environment instability.
  • Fixes root causesRemoves shared state, nondeterministic timing, uncontrolled external services, and poor test data isolation.
  • Reshapes the pipelineRuns fast deterministic gates first, parallelizes safely, and keeps flaky tests visible rather than silently retrying forever.

What is the difference between unit, integration, and end-to-end tests, and how would you distribute them?

Answer

  • Defines the levelsExplains isolation, real boundaries, and complete user flows.
  • Explains trade-offsCompares speed, confidence, maintenance cost, and flakiness.
  • Uses a risk-based mixPlaces many fast checks low and fewer critical flows high.

When is mocking useful, and how can excessive mocking make tests less valuable?

Answer

  • Mocks external boundariesMocks slow, nondeterministic, expensive, or unavailable external systems.
  • Tests behaviorAsserts observable outputs and effects rather than private calls.
  • Recognizes false confidenceNotes that mocks may not match the real API, database, or framework behavior.

You add a shipment cancellation feature across React, Node.js, and SQL. What would you test at unit, integration, contract, and end-to-end levels?

Answer

  • Uses unit tests for business logic and UI logicCovers cancellation rules, state transitions, and focused component behavior without unnecessary infrastructure.
  • Tests real boundaries in integrationChecks API validation, authorization, transaction behavior, repository queries, and the real database where valuable.
  • Keeps contract and end-to-end coverage focusedVerifies the shared API shape and one or two critical user journeys, including a meaningful failure path.

How would you test a shipment status update feature implemented with React, a Node.js REST API, and a relational database?

Answer

  • Tests business rules close to the logicUses unit tests for valid transitions, validation, and deterministic mapping or calculation code.
  • Exercises real boundariesUses API and database integration tests for persistence, authorization, conflict handling, and response contracts instead of mocking everything.
  • Keeps focused user-journey coverageAdds a small end-to-end test for the critical operator flow and makes fixtures and waits deterministic.

A service test mocks the database, message broker, clock, and every internal module. It is fast, but production defects still escape. How would you improve the test design?

Answer

  • Identifies false confidence from excessive mocksExplains that tests verify mock wiring and implementation calls rather than real behavior and contracts.
  • Uses real components at important boundariesReplaces database and broker mocks with containers, fakes, or integration environments where their semantics matter.
  • Keeps doubles for unstable or expensive edgesMocks external services at a narrow adapter, controls time explicitly, and asserts observable outcomes rather than call sequences.

Git collaboration and code review32 questions

What is the difference between merge and rebase, and when is rebasing unsafe?

Answer

  • Explains mergeCombines histories without rewriting existing commits.
  • Explains rebaseReplays commits on a new base and creates new commit identities.
  • Protects shared historyAvoids rebasing commits that other people have based work on.

What do you look for when reviewing a pull request that changes an API and its React client?

Answer

  • Checks behavior and edge casesVerifies requirements, failure paths, validation, and compatibility.
  • Checks maintainabilityLooks at responsibility boundaries, naming, duplication, and unnecessary complexity.
  • Checks safe deliveryReviews tests, migrations, observability, rollback, and independent deployment.

Git workflow and safe CI/CD31 question

Describe a practical CI/CD pipeline for a React frontend and Node.js backend deployed to AWS. What gates and rollback strategy would you use?

Answer

  • Builds fast, deterministic quality gatesRuns formatting or linting, type checks, unit and integration tests, security checks, and build validation.
  • Promotes one versioned artifactBuilds once, records the commit and version, and promotes the same immutable frontend or container artifact through environments.
  • Uses safe deployment and recoveryUses health checks, canary or blue-green rollout where justified, backward-compatible migrations, monitoring, and rollback or roll-forward.

GraphQL Backend Design42 questions

A mobile client needs different combinations of data on many screens. When would GraphQL be a better fit than REST, and what new server-side risks would you accept?

Answer

  • Explains GraphQL fitHighlights flexible field selection and aggregation across a typed graph for several clients.
  • Explains server-side costsNames N+1 access, query complexity, resolver authorization, and less direct HTTP caching.
  • Makes a contextual decisionAvoids treating GraphQL as a universal replacement and keeps simple stable resources in REST when that is clearer.

A GraphQL query returns 100 orders and resolves the customer for each order. Production traces show 101 database calls. How would you fix and verify this?

Answer

  • Identifies the N+1 patternExplains that one parent query triggers one additional customer query for every order.
  • Batches request-scoped accessUses DataLoader or an equivalent batch query keyed by customer id, with request-scoped caching.
  • Verifies behaviour and securityConfirms authorization is still applied and traces show a bounded query count and improved latency.

Idempotent Integration Operations42 questions

How would you make a booking or payment creation endpoint safe to retry after a timeout?

Answer

  • Uses a stable operation keyRequires the same idempotency or business key on every retry and prevents reuse for a different request.
  • Stores state with concurrency safetyUses a unique constraint, conditional write, transaction, or state machine so concurrent attempts cannot both execute the side effect.
  • Defines duplicate behaviorReturns the stored result or current status, defines in-progress behavior and retention, and distinguishes retriable failures.

A queue may deliver the same message more than once. How would you prevent duplicate business effects in the consumer?

Answer

  • Identifies the logical messageUses a stable event or operation ID rather than transport delivery metadata that changes on redelivery.
  • Coordinates deduplication and side effectsRecords processed identity in the same transaction as the database change, or uses an inbox pattern with an equivalent guarantee.
  • Defines practical retentionChooses a deduplication retention window, handles poison messages, and keeps the operation itself safe when possible.

Incremental legacy integration and migration31 question

A legacy PHP module is business-critical but poorly documented. How would you integrate it today and migrate it safely to Node.js over time?

Answer

  • Discovers real behavior and consumersMaps inputs, outputs, side effects, data ownership, hidden rules, traffic, failure modes, and operational dependencies before rewriting.
  • Creates a stable integration boundaryUses an adapter, façade, or API contract with validation and observability so the rest of the system does not depend on PHP details.
  • Migrates and verifies incrementallyUses characterization tests, shadow traffic or result comparison, feature flags, small capability slices, rollback, reconciliation, and an explicit retirement plan.

JavaScript asynchronous execution52 questions

How do synchronous code, promise callbacks, timers, and I/O callbacks get ordered in JavaScript? What practical bugs does this model cause?

Answer

  • Explains run-to-completionSynchronous JavaScript runs on the current call stack until it returns.
  • Places promise reactions in the microtask queueExplains that promise callbacks normally run before timer callbacks after the stack becomes empty.
  • Connects the model to a practical riskMentions blocking CPU work, missing await, unhandled rejection, or completion-order races.

A user changes a search filter quickly. Older requests sometimes finish last and overwrite newer results. How would you diagnose and fix this?

Answer

  • Identifies a completion-order raceExplains that request completion order differs from request start order and the older result is no longer authoritative.
  • Cancels or ignores obsolete workUses AbortController, a request identifier, query-library cancellation, or comparison with the latest input.
  • Keeps UI states consistentAvoids clearing useful data unnecessarily and handles loading, error, and cancellation separately.

JavaScript asynchronous execution52 questions

How would you explain the order in which synchronous code, Promise.then callbacks, and setTimeout callbacks execute?

Answer

  • Synchronous stack runs firstStates that the current call stack must complete before queued callbacks can run.
  • Promise callbacks use the microtask queueExplains that fulfilled promise continuations normally run before timer callbacks after the stack empties.
  • Timers become later tasksNotes that a zero-delay timer means eligible later, not immediate execution.

A page needs data from three independent endpoints. When would you use Promise.all, Promise.allSettled, or sequential awaits, and how would you handle failure?

Answer

  • Parallelizes independent workUses Promise.all or another concurrent pattern when operations do not depend on one another.
  • Chooses failure semantics deliberatelyDistinguishes fail-fast Promise.all from collecting every result with Promise.allSettled.
  • Keeps real dependencies sequentialUses sequential awaits when a later request needs output from an earlier one or ordering is required.

JavaScript Asynchronous Runtime52 questions

Explain how the JavaScript event loop coordinates synchronous code, Promise callbacks and timers. Why can their execution order surprise developers?

Answer

  • Explains single-stack executionStates that synchronous JavaScript runs to completion on the current call stack before queued callbacks execute.
  • Distinguishes Promise microtasksExplains that Promise continuations use the microtask queue and normally run before timer tasks after the stack clears.
  • Connects the model to defectsRelates ordering and blocking to race conditions, stale state, delayed timers or blocked requests.

A Node.js endpoint starts several asynchronous operations, returns success, and later the process logs an unhandled rejection. How would you investigate and fix the design?

Answer

  • Finds unowned promisesLooks for missing await, unreturned Promise chains or fire-and-forget work whose rejection has no owner.
  • Defines request and background semanticsDecides whether the endpoint must wait for completion or persist work for a background worker before returning success.
  • Adds controlled error handlingAdds contextual logging, correlation ids and a deliberate catch or retry policy instead of a global handler that hides the defect.

JavaScript language fundamentals52 questions

What is a closure in JavaScript, and where is it useful in application code?

Answer

  • Defines a closureExplains that a function retains access to variables from its lexical creation scope.
  • Gives a practical useMentions callbacks, factories, encapsulation, memoization, or event handlers.
  • Recognizes a pitfallMentions stale captured values or unintended memory retention.

What happens when an object is assigned to another variable, and how would you update nested data without mutating the original?

Answer

  • Explains reference behaviorStates that both variables point to the same object unless a copy is created.
  • Distinguishes copy depthExplains that spread syntax creates only a shallow copy.
  • Shows an immutable updateCreates new objects for every changed nested level.

js_event_loop1 question

Explain the JavaScript event loop in a browser, including the call stack, tasks, microtasks, rendering opportunities, and why long synchronous work freezes the UI.

Answer

  • Explains single-threaded executionStates that JavaScript runs one call stack at a time and synchronous code must finish before another callback can execute.
  • Distinguishes tasks and microtasksExplains that timers and events enqueue tasks while Promise reactions enqueue microtasks that are drained before the next task.
  • Connects scheduling to renderingExplains that the browser gets rendering opportunities between turns and long tasks block input, painting, and timers.
  • Names practical mitigationMentions splitting CPU work, yielding, workers, avoiding microtask starvation, and measuring long tasks.

Kafka Partitions, Consumer Groups, and Event Logs52 questions

You need ordered events per account and balanced throughput across the cluster. How would you choose and validate the Kafka partition key?

Answer

  • Keys by the ordering entityUses account_id so all events for one account reach the same partition and remain ordered there.
  • Checks load distributionExamines key cardinality and traffic skew so a few accounts do not create hot partitions.
  • Validates with production-like dataTests partition distribution and ordering under realistic keys and considers remapping when partition count changes.

Compare committing a Kafka offset before processing, after processing, and together with a database result. What can each choice lose or duplicate?

Answer

  • Explains commit-before riskStates that a crash after commit but before durable work can lose processing.
  • Explains commit-after duplicatesStates that a crash after the result but before offset commit causes redelivery and possible duplicate effects.
  • Discusses coordinated persistenceUses idempotent database writes, an inbox table, or Kafka transactions where applicable, without claiming universal atomicity across arbitrary systems.

Kubernetes Pods52 questions

What is the difference between a pod and a container in Kubernetes?

Answer

  • Defines each unitExplains that a container is an isolated process environment while a pod is Kubernetes' smallest scheduled and replicated unit.
  • Explains shared pod resourcesMentions shared network namespace, localhost, IP, ports, and optional shared volumes among containers in one pod.
  • Explains lifecycle couplingStates that pod containers are placed and replaced together and usually serve one tightly coupled workload.
  • Explains scaling levelClarifies that controllers create more pod replicas rather than scaling one container independently inside a pod.

Explain how a Kubernetes Deployment, ReplicaSet, Pod, and Service work together to run an API.

Answer

  • Explains the Deployment's roleDefines desired image, replica count, rollout strategy, and updates through a managed ReplicaSet.
  • Explains pods as replaceable instancesTreats pods as ephemeral workload instances selected by labels rather than stable servers.
  • Explains stable service discoveryShows how a Service selects ready pods and provides a stable virtual address or DNS name.
  • Connects rollout and healthMentions readiness, surge or unavailable settings, rollback, and mixed versions during deployment.

kubernetes_secrets1 question

How would you securely deploy and operate an ASP.NET Core API in Kubernetes, including configuration, secrets, image supply chain, and runtime permissions?

Answer

  • Handles secrets outside images and sourceUses an external secret store or protected Kubernetes Secret flow, rotation, and least-access delivery.
  • Secures the image supply chainUses pinned and scanned images, minimal bases, signed provenance, and controlled registries.
  • Applies least privilege at runtimeUses non-root users, read-only filesystems, dropped capabilities, network policies, and narrow service accounts.
  • Includes rollout and detectionCovers probes, resource limits, audit logs, telemetry, rollback, and policy enforcement in CI/CD.

Legacy Frontend Migration51 question

A Rails storefront uses HAML or ERB templates, jQuery, and vanilla JavaScript. How would you migrate it incrementally to a React 19 SPA without stopping feature delivery?

Answer

  • Chooses a safe migration seamSelects routes, pages, or isolated widgets where old and new code can coexist and be released independently.
  • Defines cross-boundary contractsMakes authentication, navigation, data, permissions, analytics, events, and styling boundaries explicit.
  • Protects behavior with evidenceInventories hidden behavior and uses tests, monitoring, visual comparison, and staged rollout to verify parity.
  • Removes temporary architectureDefines exit criteria and deletes old code and bridges after each migrated slice is stable.

Legacy PHP integration and migration22 questions

A business-critical pricing rule lives in a legacy PHP application and must gradually move to Node.js. How would you reduce migration risk?

Answer

  • Captures current behavior and ownershipIdentifies callers, business rules, data ownership, side effects, failure modes, and uses characterization tests plus production evidence.
  • Creates an explicit migration boundaryPlaces an adapter or API around the PHP capability, defines a contract, avoids uncontrolled shared-table writes, and translates legacy concepts into a new model.
  • Migrates and verifies incrementallyUses feature flags, shadow or dual execution, result comparison and reconciliation, metrics, gradual traffic switching, and a rollback path.

A new Node.js service must initially read data from a database owned by a PHP application. What risks do you see, and how would you contain them?

Answer

  • Identifies schema and ownership couplingExplains that direct reads depend on undocumented tables and semantics, bypass domain rules, and can break when the legacy application changes.
  • Contains access behind a narrow adapterUses least-privilege read access, isolates queries in one integration module, maps to an internal model, adds contract checks, and avoids new writes to legacy-owned tables.
  • Plans detection and evolutionMonitors query failures and data anomalies, coordinates schema changes, versions the boundary, and proposes an API, replication stream, or owned read model as the longer-term path.

Legacy PHP Modernization23 questions

How would you integrate or gradually replace a legacy PHP application with new Node.js services?

Answer

  • Starts with discoveryMaps business capabilities, dependencies, data flows, operational constraints, and tests current behavior.
  • Creates a stable boundaryUses an API, adapter, gateway, or anti-corruption layer rather than letting new code depend directly on legacy internals.
  • Migrates incrementallyMoves one capability with explicit data ownership, gradual traffic, comparison, and rollback.

The PHP system and a new Node.js service both need shipment data during a multi-month migration. How would you avoid inconsistent writes?

Answer

  • Defines one write ownerAssigns authoritative ownership for each field or capability and avoids uncontrolled dual writes.
  • Chooses an explicit synchronization methodUses APIs, events, change capture, or replicated read models with clear consistency expectations.
  • Plans reconciliationUses identifiers, idempotency, audit trails, comparison jobs, and a repair process for drift.

What evidence would make you choose a complete rewrite instead of incremental modernization, and what risks would you still plan for?

Answer

  • Builds a rewrite case from constraintsRequires evidence such as an unusable platform, impossible deployment, severe security limits, or a small well-understood scope.
  • Names rewrite risksCovers hidden behavior, long delivery, changing requirements, data migration, cutover, and loss of operational knowledge.
  • Reduces the riskUses behavior characterization, staged migration, parallel run, feature flags, checkpoints, and rollback.

Legacy system integration23 questions

You must add a TypeScript feature that depends on an undocumented PHP pricing module. What would you do before changing or replacing it?

Answer

  • Maps behavior and consumersReviews callers, data flow, production examples, logs and domain experts to find hidden rules.
  • Adds characterization and contract testsCaptures current inputs and outputs, especially important edge cases, before refactoring.
  • Creates an isolating adapterPlaces a stable API or adapter around the PHP module so new code does not depend on its internals.

How would you migrate parts of a PHP system to Node.js without a risky big-bang rewrite?

Answer

  • Chooses a capability boundarySelects a small cohesive business capability with a stable interface and clear data ownership.
  • Validates the new behavior against production realityUses shadow traffic, dual calculation or sampled comparison before switching authority.
  • Uses controlled cutover and rollbackRoutes a limited scope to the new path, monitors differences and preserves a fast fallback.

A quick solution is to let the new Node.js service read and update the PHP application database directly. What are the risks and safer alternatives?

Answer

  • Identifies hidden coupling and invariantsDirect access bypasses validation, transactions, side effects and schema ownership encoded in legacy code.
  • Establishes one writer and clear ownershipKeeps one authoritative writer and exposes behavior through an API, command or event boundary.
  • Allows a controlled temporary bridgeIf direct read is unavoidable, uses a documented read model, least privilege, monitoring and an explicit removal plan.

List Virtualization52 questions

How would you build a scrollable React list backed by roughly one million records without overwhelming React, the DOM, the network, or the browser?

Answer

  • Does not load or mount everythingUses server pagination or range fetching and avoids creating one million row elements in memory or the DOM.
  • Virtualizes the visible windowRenders only visible rows with overscan and a simulated total height using stable item identity.
  • Plans data and interaction behaviorHandles sorting, filtering, selection, deep links, keyboard focus, loading, retries, and preserving position across page fetches.
  • Measures real bottlenecksProfiles rendering, memory, network, long tasks, and dynamic row measurement instead of relying on row count alone.

A virtualized CRM table scrolls smoothly, but keyboard users lose focus and screen readers announce confusing row counts. How would you improve it?

Answer

  • Preserves logical focusUses stable row identity, deliberate focus management, and scroll-to-item behavior when focused content leaves the mounted window.
  • Communicates collection semanticsProvides meaningful table or list semantics, row counts or positions where appropriate, and does not expose spacer elements as content.
  • Supports non-pointer navigationTests keyboard selection, page movement, find or jump behavior, and actions that work without relying on hover.
  • Questions whether virtualization is appropriateConsiders pagination or a simpler accessible view when full table semantics cannot be maintained reliably.

LLM application design45 questions

How would you decide whether a logistics workflow should use an LLM, deterministic code, or a combination of both?

Answer

  • Matches technology to the taskLLMs fit ambiguous language and classification; exact rules, calculations and invariants belong in deterministic code.
  • Considers the cost of a wrong resultUses error tolerance, reversibility, privacy, latency and human review to decide acceptable autonomy.
  • Builds a controlled hybrid flowLets the model interpret or propose while deterministic code validates, calculates and commits consequential changes.

An assistant must answer questions about current pricing rules and shipments. How would you supply trustworthy context and reduce hallucination?

Answer

  • Retrieves from authoritative sourcesUses current approved rules and authorized shipment data rather than relying on model memory.
  • Limits and structures contextFilters by user permission and task relevance, adds source identifiers and controls context size.
  • Handles missing evidence explicitlyRequires the assistant to state when evidence is missing, avoid unsupported claims and route high-risk cases to a person.

What would an evaluation plan look like for an AI feature that explains unusual shipment prices?

Answer

  • Builds a representative evaluation setIncludes common, difficult, missing-data and unsafe cases reviewed by domain experts.
  • Defines task-specific quality and operational metricsMeasures factual grounding, rule coverage, harmful errors, latency and cost rather than one generic score.
  • Compares versions and monitors productionUses a deterministic or human baseline, regression gates and sampled production review with feedback.

How would you design an LLM feature that summarizes shipment incidents for operations staff while limiting hallucination and data exposure?

Answer

  • Bounds the task and riskDefines what the summary is used for, acceptable error, prohibited actions, and when the feature must defer to source records or a human.
  • Controls and grounds contextRetrieves only authorized relevant records, minimizes or redacts sensitive data, treats retrieved text as untrusted, and links output claims to sources.
  • Validates output and evaluates qualityUses a structured schema, validates it, handles refusal or malformed output, and measures representative quality, latency, cost, and safety before and after release.

A stakeholder proposes using an LLM to classify shipment priority from a small set of explicit business rules. How would you evaluate that proposal?

Answer

  • Prefers deterministic logic for explicit rulesExplains that stable enumerable rules are cheaper, testable, explainable, and predictable in ordinary code or a rule engine.
  • Identifies where an LLM may add valueReserves the model for ambiguous unstructured input, extraction, or recommendation, while keeping final policy enforcement deterministic.
  • Requires measurable evidenceProposes an evaluation set and compares accuracy, failure severity, latency, cost, maintenance, and auditability before adoption.

LLM Output Evaluation32 questions

How would you evaluate whether generated feedback is accurate, helpful, age-appropriate and consistent across supported languages?

Answer

  • Defines feature-specific criteriaCreates a rubric for factual correctness, relevance, constructive tone, age suitability, prohibited content and format.
  • Builds a representative evaluation setIncludes normal, difficult, adversarial and multilingual anonymized examples with teacher-approved expected qualities.
  • Uses repeatable comparison and gatesCombines deterministic checks and human scoring, reports results by language or subgroup, and blocks release on critical regressions.

A student writes instructions inside an answer telling the model to ignore the teacher rubric and reveal hidden prompts. How should the system respond?

Answer

  • Treats student content as untrusted dataClearly separates system instructions and rubric from quoted student content, while accepting that prompt text alone is not a hard security boundary.
  • Limits model capabilities and data accessDoes not place secrets in prompts and gives tools or retrieved data only through authorized, minimal, allowlisted operations.
  • Validates and contains the resultChecks output schema and safety, prevents direct execution of model output, logs attempts safely and keeps teacher review.

LLM Product Integration32 questions

Researchers propose using an LLM to generate teacher feedback. What questions would you ask before building the integration?

Answer

  • Clarifies the user problem and successAsks who needs the feedback, what current workflow is painful and what measurable behavior or learning outcome should improve.
  • Surfaces product and system constraintsAsks about acceptable latency, cost, languages, privacy, age suitability, failure tolerance and whether a human reviews the result.
  • Compares simpler alternativesConsiders templates, rules, retrieval or a manual prototype and proposes a pilot before full integration.

Design the backend path for generating draft feedback with an external LLM. Cover validation, privacy, latency, cost, failure and user control.

Answer

  • Builds a minimal validated prompt contextAuthorizes the request, sends only necessary pseudonymized data, limits input size and separates trusted instructions from user content.
  • Controls the provider callUses timeout, token and concurrency limits, suitable retry rules, model version tracking and cost metrics.
  • Validates output and preserves user controlParses a structured response, checks safety and required fields, returns an editable draft, records provenance and falls back cleanly.

LLM Reliability and Security43 questions

What controls would you add before using an LLM response in a business workflow?

Answer

  • Grounds factual outputUses trusted retrieved data, source references, and an explicit response when evidence is missing.
  • Validates structure and rulesUses structured output schemas, range and business-rule checks, and deterministic calculation where possible.
  • Matches control to riskRequires human approval or narrow automation for consequential, external, financial, or irreversible actions.

An agent reads customer documents that may contain malicious instructions. How would you reduce prompt-injection risk?

Answer

  • Treats retrieved content as untrusted dataSeparates instructions from data, labels sources, and never grants authority based on text inside a document.
  • Constrains capabilitiesUses least-privilege tools, allowlists, argument validation, authorization, and approval for sensitive actions.
  • Checks and monitors outcomesScans outputs, prevents secret exposure, logs safe audit events, and tests known attack cases.

How would you decide whether an AI-assisted logistics feature is good enough to release?

Answer

  • Builds a representative evaluation setUses realistic normal, edge, ambiguous, and adversarial cases with expected outcomes.
  • Measures task and safety outcomesMeasures factual accuracy, completion, refusal quality, latency, cost, and unsafe-action rate.
  • Uses staged release and monitoringUses offline evaluation, shadow or limited rollout, human review, feedback capture, and rollback or disable controls.

Message Delivery Guarantees42 questions

Compare at-most-once, at-least-once, and exactly-once delivery. What can an application truly rely on?

Answer

  • Explains at-most-onceStates that processing is not retried after uncertainty, so duplicates are reduced but messages or work can be lost.
  • Explains at-least-onceStates that failed or uncertain deliveries are retried, so loss is reduced but duplicate delivery and processing must be expected.
  • Scopes exactly-once correctlyExplains that exactly-once guarantees are bounded to a broker or transaction model and do not automatically cover external systems.

When should a consumer acknowledge a message relative to its database transaction, and what failure cases remain?

Answer

  • Acknowledges after durable commitCommits the required local side effect and processed-message record before acknowledging the delivery.
  • Recognizes the duplicate windowExplains that a crash after commit but before acknowledgement leads to redelivery and therefore requires idempotency.
  • Handles other failuresDefines retryable versus permanent errors, rollback, nack or reject behavior, maximum attempts, dead-lettering, and alerting.

Message Delivery Semantics and Idempotent Consumers52 questions

A consumer charges a customer successfully, then crashes before acknowledging the message. What happens under at-least-once delivery, and how do you prevent a second charge?

Answer

  • Predicts redeliveryExplains that the broker sees no acknowledgement and delivers the same logical message again.
  • Uses a durable idempotency keyStores a stable message or payment key in durable storage and makes duplicate processing return the original result.
  • Acknowledges after durable successAcknowledges only after the charge result and deduplication state are safely persisted.

One malformed message fails immediately on every delivery and is requeued forever. Design a safer retry and dead-letter policy.

Answer

  • Classifies the failureDoes not retry schema or validation failures like transient network failures.
  • Uses bounded delayed retriesApplies a retry count with backoff and jitter rather than immediate infinite requeue.
  • Dead-letters with contextMoves exhausted messages to a dead-letter path with error metadata, alerts, and a controlled replay process.

Messaging Patterns: Queue, Pub/Sub, Request/Reply, and Topics52 questions

Choose a messaging pattern for distributing image jobs among workers, notifying several services about an order, and asking an inventory service for an immediate answer.

Answer

  • Uses a work queue for jobsChooses competing consumers so each image job is handled by one worker.
  • Uses pub/sub for business eventsChooses separate subscriptions so every interested service receives the order event.
  • Uses request/reply deliberatelyUses a correlated reply with a timeout only when the caller truly needs an immediate answer.

Five systems must react independently after a customer is created. How would you prevent one slow or failing consumer from blocking the others?

Answer

  • Creates independent subscriptionsGives each downstream system its own durable queue or subscription rather than sharing one work queue.
  • Isolates failure and backpressureLets each subscription have its own capacity, retry, dead-letter, and scaling policy.
  • Adds per-consumer observabilityTracks lag, age, failures, retries, and dead-letter counts for every downstream consumer.

Microservice Boundaries and Integration Choices42 questions

A proposed system has Customer, Order, Inventory, Billing, and Notification capabilities. How would you decide which become services and which interactions are synchronous or asynchronous?

Answer

  • Uses business capabilities and invariantsGroups rules that change together and must remain consistent instead of splitting by technical layer.
  • Assigns clear data ownershipGives authoritative writes for each business area to one service and avoids shared write access.
  • Chooses communication by needUses synchronous calls for immediate decisions and events for independent downstream reactions.

An endpoint must call six services in sequence and all six must succeed. What does this reveal about the design, and what redesign options would you consider?

Answer

  • Explains compounded failure and latencyNotes that sequential calls add latency and make request availability depend on every service.
  • Questions the boundariesLooks for business rules or data split too finely across services and considers merging responsibilities.
  • Offers read and workflow alternativesConsiders API aggregation, denormalized read models, parallel safe calls, or asynchronous workflows with explicit state.

microservices_boundaries2 questions

How would you split a growing API and data exchange platform into services without creating a distributed monolith?

Answer

  • Starts from business capabilitiesGroups cohesive rules and workflows rather than splitting by table, controller, or technical layer.
  • Assigns clear data ownershipGives one service authority over writes and prevents cross-service direct database access.
  • Tests independent changeLooks for independent deployment, failure isolation, scaling, security, and team ownership.
  • Accounts for distributed-system costIncludes network failures, observability, versioned contracts, consistency, and operational maturity; considers a modular monolith.

Several services directly read and write the same SQL schema. What risks does this create, and how would you migrate away from it?

Answer

  • Explains hidden couplingCovers schema coordination, bypassed business rules, lock contention, security exposure, and coupled releases.
  • Establishes ownershipAssigns each data set and invariant to one service and routes changes through that service.
  • Plans incremental migrationUses facades, change data capture or events, expand-and-contract, and consumer-by-consumer cutover.
  • Handles cross-service workflowsUses local transactions, outbox, sagas or compensating actions instead of accidental multi-service SQL transactions.

Model Context Protocol Architecture43 questions

What problem does Model Context Protocol solve, and what are the responsibilities of the host, client, and server?

Answer

  • Explains interoperabilityExplains that MCP standardizes discovery and access to context and tools across AI applications and integrations.
  • Separates the rolesExplains that the host controls the AI experience, a client maintains a server connection, and the server exposes capabilities.
  • Names core capabilitiesDistinguishes tools for actions, resources for context, and prompts for reusable interaction templates.

You need an MCP server for shipment information. What would you expose as resources and tools, and how would you keep it safe?

Answer

  • Designs narrow capabilitiesUses resources for readable shipment context and small purpose-specific tools for queries or actions.
  • Enforces identity and authorizationAuthenticates the caller, applies user and tenant permissions, validates arguments, and limits data returned.
  • Adds operational controlsIncludes audit logs, rate limits, timeouts, versioned schemas, error handling, and safe transport configuration.

When would MCP be a better integration boundary than calling a REST API directly from one AI application, and when would it be unnecessary?

Answer

  • Explains MCP reuseUses MCP when several AI hosts need discoverable model-oriented tools and context through a common interface.
  • Explains direct API simplicityPrefers a direct SDK or REST client when one controlled application has a small stable integration and no interoperability need.
  • Includes added responsibilitiesMentions another protocol layer, server lifecycle, capability governance, authentication, and observability.

Model Context Protocol fundamentals33 questions

What is the Model Context Protocol, which components participate, and what problem does it solve?

Answer

  • Defines the interoperability purposeMCP standardizes how AI applications discover and use external tools, resources or prompts.
  • Names host or client and server rolesThe host or client manages model interaction; the server exposes capabilities with schemas.
  • Keeps execution under application controlThe model can request a call, but the host validates permission and executes it.

Design an MCP tool that lets an operations assistant propose a shipment repricing. What should its schema and execution boundary contain?

Answer

  • Defines a narrow explicit tool contractUses a specific action name, shipment id, proposed value, reason and constrained types instead of arbitrary commands.
  • Enforces identity and business authorizationThe backend checks the current user, shipment access and allowed pricing rules independently of model text.
  • Returns bounded auditable outputReturns a proposal or operation id with safe errors, records the invocation and requires confirmation for the write.

An MCP server can expose shipment documents and pricing rules. How would you prevent excessive context, cross-customer access and stale information?

Answer

  • Scopes every request to the authenticated identityAuthorization filters customer, role and resource ownership before content is returned.
  • Returns only relevant bounded contentUses query parameters, pagination, summaries and size limits instead of dumping entire repositories.
  • Makes freshness and source visibleProvides timestamps or versions, retrieves from authoritative stores and avoids caching sensitive stale data blindly.

Mule-to-Node.js Migration52 questions

How would you plan a migration from a Mule-based integration platform to Node.js services without disrupting existing consumers?

Answer

  • Discovers actual behaviorInventories contracts, transformations, dependencies, schedules, security, volumes, errors, retries, and consumers before rewriting.
  • Uses incremental migrationChooses vertical slices and uses strangler routing, feature flags, canaries, or parallel running instead of a big-bang cutover.
  • Verifies parity and rollbackUses contract and regression tests, comparison or shadow traffic, metrics, reconciliation, and a tested rollback path.

A new Node.js implementation produces the same success responses as the Mule flow. What else must be validated before cutover?

Answer

  • Checks failure semanticsCompares validation, timeouts, retry and redelivery behavior, error mapping, partial failures, and dead-letter handling.
  • Checks data semanticsVerifies transformations, ordering, duplicates, time zones, null handling, encoding, and side effects, not only response shape.
  • Checks non-functional behaviorValidates throughput, latency, resource use, security controls, observability, deployment, and recovery under realistic load.

Multilingual UI Design21 question

What technical and UX problems must a React application handle when the same classroom workflow is offered in English, French, German and Luxembourgish?

Answer

  • Externalizes complete messagesUses stable message keys, complete sentences and locale-aware plural rules instead of scattered or concatenated strings.
  • Handles locale-specific formatting and layoutFormats dates and numbers by locale and designs for text expansion, wrapping and accessible language metadata.
  • Defines fallback and quality checksSupports user language choice, reports missing translations and tests critical flows with real translations rather than keys.

NATS Core, Request/Reply, and JetStream42 questions

Choose between Core NATS and JetStream for a low-latency service lookup, a durable background job, and an event consumer that may be offline for hours.

Answer

  • Uses Core NATS for ephemeral lookupChooses Core request/reply with a short timeout when only a currently available responder is useful.
  • Uses JetStream for durable workChooses stored messages, explicit acknowledgements, and redelivery for background jobs.
  • Uses replay for offline consumersUses a durable JetStream consumer that resumes from its stored position after reconnecting.

A NATS request/reply call sometimes has no responder or times out. How should the caller distinguish these outcomes and avoid turning retries into an overload loop?

Answer

  • Distinguishes no-responder and timeoutTreats immediate no-responder information differently from a request whose reply missed the deadline.
  • Uses bounded retry with backoffRetries only safe transient failures with a limit, backoff, jitter, and an overall deadline.
  • Provides a failure pathReturns a controlled unavailable response, uses cached data, or switches to asynchronous processing when appropriate.

Next.js Rendering Strategy31 question

Compare how you would render a public project page, a teacher dashboard and an interactive exercise editor in Next.js.

Answer

  • Chooses static delivery for stable public contentSuggests static generation and caching for public content that changes infrequently.
  • Uses server rendering for protected fresh dataUses authenticated server-side data access where initial personalized content and security benefit from server execution.
  • Keeps interactive state on the clientUses client components for rich interaction while avoiding unnecessary client-side data fetching and hydration.

Node.js API structure and middleware52 questions

Explain how middleware works in Express or a similar Node.js framework. What belongs in middleware?

Answer

  • Explains the chainMiddleware runs in order and can continue, respond, or pass an error.
  • Names appropriate concernsMentions authentication, logging, CORS, parsing, request IDs, or rate limiting.
  • Avoids flow bugsExplains returning after a response and not invoking the continuation twice.

How would you separate route handling, business logic, and data access in a Node.js service?

Answer

  • Keeps routes thinRoutes handle HTTP details and delegate application work.
  • Defines a service boundaryServices own use-case logic and receive explicit dependencies.
  • Separates data accessRepositories or adapters isolate database-specific operations and make integration testing clearer.

Node.js Async Error Handling43 questions

How would you structure error handling across a Node.js route, service layer, and external client?

Answer

  • Keeps failures connectedAwaits or returns promises and avoids detached work unless it is deliberately supervised.
  • Translates errors by layerWraps low-level failures with meaningful typed causes without losing the original error.
  • Handles once at the boundaryUses centralized HTTP error mapping and structured logging rather than repeated catch-and-log blocks.

A client disconnects while a Node.js endpoint is waiting on several downstream calls. How would you avoid continuing expensive work unnecessarily?

Answer

  • Propagates cancellationCreates or receives an AbortSignal and passes it to downstream clients that support cancellation.
  • Uses a deadline or timeoutUses a request-level deadline and ensures child calls do not outlive it.
  • Cleans up safelyReleases resources and handles cancellation separately from an unexpected server failure.

Which failures should a Node.js service retry, and what safeguards are needed before adding retries?

Answer

  • Retries only transient failuresRetries timeouts, throttling, or temporary unavailability rather than validation and permanent business errors.
  • Protects side effectsRequires idempotency or another duplicate-protection mechanism for operations with side effects.
  • Limits retry pressureUses bounded attempts, exponential backoff, jitter, deadlines, and observability.

Node.js asynchronous runtime52 questions

You must enrich 20,000 shipments by calling a carrier API. Why is one Promise.all risky, and how would you design the processing?

Answer

  • Identifies the concurrency burstStarting all calls at once can exhaust sockets, memory, quotas and the carrier service.
  • Uses bounded concurrencyProcesses with a concurrency limit, worker pool or queue that matches dependency capacity.
  • Plans retries and progressUses timeouts, selective retry, idempotency and durable progress so partial failures can resume.

A route-optimization calculation takes several seconds of CPU time. What implementation options would you consider in a Node.js system?

Answer

  • Protects the event loopThe calculation should not run synchronously on the request thread because it delays unrelated traffic.
  • Compares suitable execution optionsConsiders worker threads, a separate service, a queue worker or a specialized runtime depending on duration and scale.
  • Designs asynchronous user experience when neededFor long work, returns a job id and exposes progress or completion instead of holding an HTTP request.

Node.js concurrency and blocking work52 questions

A Node.js API has good database latency, but all endpoints become slow whenever one report endpoint runs. What is your likely hypothesis and how would you fix it?

Answer

  • Suspects event-loop blockingRecognizes that synchronous or CPU-heavy JavaScript can delay unrelated requests in the same process.
  • Measures the blocking workUses profiling, event-loop lag, CPU samples, request traces, and a reproducible workload.
  • Moves or limits the work safelyUses worker threads, separate processes, a bounded job queue, streaming, or algorithmic reduction rather than merely adding more awaits.

One request needs data from 200 shipment providers. Why might Promise.all be dangerous, and how would you design bounded concurrency and partial failure handling?

Answer

  • Explains unbounded concurrency riskShows how simultaneous calls can exhaust sockets, memory, rate limits, or the downstream service.
  • Applies a concurrency limitUses a worker pool, semaphore, queue, batching, or a library limit with timeouts and cancellation.
  • Defines partial-failure semanticsChooses fail-fast versus partial results, records provider-specific errors, and avoids retry storms.

Node.js concurrency and blocking work42 questions

A Node.js API becomes slow for every user while one request generates a large report. How would you confirm the cause and redesign the work?

Answer

  • Identifies event-loop blockingExplains that CPU-heavy synchronous work delays unrelated request callbacks in the same process.
  • Measures before changing architectureUses CPU profiles, event-loop lag, latency traces, or load tests to confirm the bottleneck.
  • Moves heavy work off the request threadUses worker threads, a job queue, a separate service, and streaming according to latency and scale needs.

You must export several gigabytes of logistics data. Why is loading everything into memory risky, and how would Node.js streams and backpressure help?

Answer

  • Avoids unbounded memory usageExplains that buffering the whole export can exhaust heap memory and increase garbage-collection pauses.
  • Processes data incrementallyUses a readable-transform-writable pipeline or async iteration to handle chunks rather than the full dataset.
  • Respects backpressure and cancellationSlows reading when the destination is busy and handles client disconnects and stream errors.

Node.js Event Loop53 questions

How can Node.js handle many concurrent requests if JavaScript normally runs one callback at a time?

Answer

  • Explains the event loopExplains that ready JavaScript callbacks run sequentially on the event loop.
  • Explains delegated I/OExplains that network and filesystem operations can wait outside the JavaScript thread and notify it when ready.
  • Identifies the limitExplains that CPU-heavy or synchronous work blocks progress for other requests.

A Node.js API has low CPU most of the day, but p99 latency occasionally jumps for every endpoint. How would you investigate event-loop blocking?

Answer

  • Measures event-loop delayUses event-loop lag, CPU profiles, flame graphs, or request traces around the incident.
  • Checks blocking operationsLooks for synchronous APIs, large JSON processing, compression, crypto, image or document work, and unbounded loops.
  • Moves or limits heavy workUses worker threads, a job queue, streaming, chunking, or another service and verifies latency afterward.

For a Node.js service, when would you choose ordinary async I/O, worker threads, multiple processes, or a separate background service?

Answer

  • Uses async I/O for waiting workChooses normal asynchronous APIs for network, database, and filesystem waiting.
  • Uses workers for CPU workChooses worker threads or a dedicated service for CPU-heavy tasks.
  • Uses processes for isolation and scalingUses multiple processes or containers for fault isolation, memory boundaries, and horizontal capacity.

Node.js Event Loop and Concurrency52 questions

Explain how Node.js can handle many concurrent requests despite JavaScript running primarily on one event-loop thread.

Answer

  • Explains the concurrency modelStates that JavaScript callbacks run serially on the event loop while I/O waits overlap through the OS or runtime.
  • Mentions delegated workRecognizes that some filesystem, DNS, crypto, compression, or explicit worker-thread tasks use background threads.
  • Explains blocking riskIdentifies synchronous calls and CPU-heavy JavaScript as causes of event-loop delay and high tail latency.

A Node.js service receives large payloads, performs transformations, and calls several downstream APIs. How would you prevent it from becoming unresponsive?

Answer

  • Bounds expensive workLimits payload size, validation complexity, batch size, and concurrent downstream work instead of accepting unbounded input.
  • Streams or offloads workUses streams for large data and worker threads, queues, or separate services for CPU-heavy transformations.
  • Measures runtime pressureMonitors event-loop delay, memory, GC, latency percentiles, active handles, and downstream saturation.

Node.js Event Loop and Non-blocking I/O52 questions

How can Node.js handle many concurrent I/O operations with one main JavaScript thread, and what kinds of work still block it?

Answer

  • Explains the JavaScript threadStates that JavaScript callbacks normally run one at a time on the event-loop thread.
  • Explains I/O delegationExplains that the operating system or Node.js worker pool performs waiting I/O work.
  • Identifies blocking workNames synchronous or CPU-heavy JavaScript as work that delays all other callbacks.

A Node.js API has low database latency and moderate CPU usage, but p99 response time suddenly rises. How would you investigate whether the event loop is blocked?

Answer

  • Measures event-loop delayUses event-loop delay or utilization together with request latency and CPU profiles.
  • Finds the blocking code pathCorrelates traces, profiles, or controlled load tests to a synchronous or CPU-heavy operation.
  • Verifies the remediationMoves or bounds the heavy work and repeats the same workload while watching tail latency.

Node.js Failure Handling and Graceful Shutdown42 questions

How do you distinguish expected operational errors from programmer errors in a Node.js service, and why should the distinction affect process behaviour?

Answer

  • Defines operational errorsGives examples such as invalid input, not found, conflict, timeout, or unavailable dependency.
  • Defines programmer errorsDescribes bugs or broken invariants that can leave the process in an unknown state.
  • Chooses different behaviourHandles operational errors at the request boundary, but logs and restarts after an unsafe uncaught failure.

A container receives SIGTERM during a rolling deployment. What should a Node.js service do before exiting, and how long should it wait?

Answer

  • Stops receiving new workMarks the instance unready or closes the listener so the load balancer stops sending traffic.
  • Drains and closes resourcesWaits for in-flight work within a deadline and closes database, broker, timer, and worker resources.
  • Uses a bounded shutdown deadlineChooses a deadline shorter than the platform kill timeout and forces exit if cleanup does not finish.

Node.js Memory Leaks and Heap Diagnosis52 questions

A service grows from 300 MB to 1.5 GB over several hours and restarts. Walk through how you would determine whether this is a JavaScript heap leak and find the retaining code.

Answer

  • Confirms a real leak patternSeparates heap growth after garbage collection from temporary peaks or external memory.
  • Compares heap snapshotsCaptures snapshots under a repeatable workload and inspects growing object groups and retaining paths.
  • Fixes and verifies ownershipRemoves the retaining reference or adds bounded eviction, then repeats the same test.

A process-wide Map is used as a cache and memory rises with traffic. What design questions would you ask before calling it a leak, and how would you make the cache safe?

Answer

  • Requires a bounded cacheAsks for maximum entries or memory, an eviction policy, and expiry where appropriate.
  • Examines key cardinality and lifetimeChecks whether keys are unbounded, user-controlled, or retained longer than their useful lifetime.
  • Adds cache and memory metricsMeasures hit rate, entry count, evictions, heap growth, and behaviour after traffic falls.

Node.js Service Runtime41 question

A new document-analysis feature performs heavy parsing inside an API route, and all endpoints become slow. Explain the cause and propose a production design.

Answer

  • Identifies event-loop blockingExplains that CPU-heavy synchronous work occupies the JavaScript execution thread and delays unrelated callbacks and requests.
  • Moves work out of the request threadUses worker threads, a separate worker service or a durable background job depending on size and operational needs.
  • Controls workload and lifecycleBounds concurrency, exposes job status, handles retries and cancellation, and measures queue time and processing time.

Node.js Streams and Backpressure42 questions

How would you implement a Node.js endpoint that validates and forwards very large uploads without loading each file fully into memory?

Answer

  • Uses a streaming pipelineProcesses or forwards chunks instead of buffering the complete file.
  • Preserves backpressureLets the destination slow the source rather than accumulating an unbounded queue.
  • Handles errors and limitsPropagates errors across all stages, aborts downstream work, and enforces size and timeout limits.

A producer emits data faster than your custom writable can process it, and process memory keeps rising. What is probably wrong and how would you fix it?

Answer

  • Identifies ignored backpressureExplains that the producer continues after the writable buffer says it is full.
  • Uses pause and drain correctlyPauses production when write returns false and resumes after drain, or uses pipeline.
  • Verifies memory stabilityRepeats the same sustained workload and confirms bounded buffers and stable memory.

Object-Oriented Analysis and Design41 question

Take a renewal-payment use case and show how you move from object-oriented analysis to object-oriented design.

Answer

  • Starts with the problem modelIdentifies actors, use cases, domain language, rules, events, and invariants before selecting classes.
  • Assigns cohesive responsibilitiesPlaces decisions with objects or services that have the relevant information and reason to change.
  • Designs collaborations and boundariesExplains commands or messages between objects and separates domain decisions from HTTP and persistence.
  • Tests the design against scenariosUses happy path, failure cases, concurrency, and future changes to evaluate the model.

Observability and production debugging43 questions

What is the difference between logs, metrics, and traces, and what question is each best suited to answer?

Answer

  • Explains metricsUses numeric aggregates for rates, latency percentiles, saturation, and alerting.
  • Explains logsUses event details and structured context for a specific occurrence.
  • Explains tracesConnects spans across services to show one request path and latency.

Shipment creation intermittently fails after a release. Walk through how you would investigate and stabilize the system.

Answer

  • Scopes impact and timelineChecks affected users, error rate, release time, inputs, and dependencies.
  • Reduces impact firstRolls back, disables a feature, shifts traffic, or applies a safe mitigation.
  • Investigates systematicallyUses correlation IDs, signals, and recent diffs to test one hypothesis at a time.

After a release, some users report slow shipment search, but the average API latency looks normal. How would you investigate?

Answer

  • Scopes the affected population and timeChecks browser, region, tenant, endpoint, query shape, time window, and the exact release or feature flag.
  • Looks beyond averagesInspects p95 or p99 latency, error rates, saturation, database time, cache misses, and downstream timings.
  • Correlates evidence and verifies the hypothesisUses trace ids and structured logs to follow slow requests, compares them with the change, and confirms the fix with the original signal.

Observability and production debugging42 questions

A shipment search endpoint is usually fast but occasionally takes eight seconds. How would you investigate it in production?

Answer

  • Scopes the symptom before guessingChecks time range, affected users or filters, traffic volume, error rate, and recent deployments or data changes.
  • Correlates metrics, traces, and logsUses percentiles rather than only averages, follows slow traces, and queries structured logs by request and dependency identifiers.
  • Tests likely bottlenecks safelyCompares database plans, pool saturation, external calls, retries, cache behavior, and event-loop delay, then mitigates with minimal change.

A team receives hundreds of alerts for individual exceptions, but users sometimes notice outages before the team does. How would you redesign the alerting approach?

Answer

  • Alerts on user-visible impactPrioritizes availability, latency, correctness, and critical workflow success over individual exception events.
  • Defines meaningful service indicatorsUses rates, ratios, percentiles, sustained windows, and segmentation to avoid noisy one-off failures and hidden partial outages.
  • Makes alerts actionableAdds severity, owner, dashboard and runbook links, deduplication, and a clear condition for paging versus ticketing.

Observability and Troubleshooting43 questions

What different questions do logs, metrics, and distributed traces answer in a production full-stack system?

Answer

  • Explains logsUses logs for detailed discrete events and context around a specific operation or failure.
  • Explains metricsUses metrics for trends, rates, percentiles, saturation, and alerting over time.
  • Explains tracesUses traces to follow one request across components and locate latency or failure boundaries.

Users report that some price quotes take ten seconds, but average latency looks normal. How would you investigate?

Answer

  • Uses percentiles and segmentationLooks at p95 or p99 and segments by route, customer, region, dependency, and release version.
  • Follows affected requestsUses trace exemplars or correlation ids to identify where the slow tail spends time.
  • Correlates with changes and capacityChecks deployments, errors, retries, saturation, and downstream service behavior during the same period.

How would you design alerts for a business-critical logistics API without creating alert fatigue?

Answer

  • Alerts on user impactUses availability, error rate, latency, freshness, or failed business operations rather than every resource fluctuation.
  • Makes alerts actionableIncludes ownership, runbook, context, severity, and a clear response expectation.
  • Controls noiseUses sustained windows, deduplication, routing, and separate warning versus paging thresholds.

PostgreSQL and Oracle Portability42 questions

What differences would you consider when the same Node.js integration service must support PostgreSQL and Oracle?

Answer

  • Identifies semantic and syntax differencesMentions pagination, date or string behavior, nulls, functions, sequences or identities, locking, and data types.
  • Considers drivers and migrationsAccounts for parameter binding, result representations, connection behavior, transaction APIs, and separate migration paths.
  • Tests both real enginesUses shared behavioral tests plus engine-specific performance and execution-plan checks instead of relying on mocks or one database.

A Mule flow contains Oracle-specific SQL and stored procedures, but the new Node.js service may use PostgreSQL. How would you approach the migration?

Answer

  • Inventories database behaviorFinds queries, stored-procedure logic, side effects, transaction boundaries, schedules, data types, and performance expectations.
  • Separates business and database concernsMoves portable business rules into tested application code while deliberately retaining set-based or database-specific logic where it is the better boundary.
  • Validates migration outcomesUses reconciliation, dual or shadow runs, representative volumes, execution plans, and rollback or replay procedures.

Pragmatic architecture decisions53 questions

A small business-oriented team is starting a new logistics capability. How would you decide between a modular monolith and microservices?

Answer

  • Starts from context rather than patternConsiders team ownership, change rate, domain boundaries, scale and isolation needs.
  • Makes distribution costs explicitMicroservices add deployment, networking, observability, data consistency and operational complexity.
  • Keeps an extraction pathUses internal module boundaries and extracts only when independent ownership, scaling or release needs become real.

Describe how you would present a technical decision to product and engineering stakeholders when no option is clearly best.

Answer

  • Frames the decision around an outcomeExplains the business goal, constraints and quality attributes in plain language.
  • Compares realistic alternativesShows two or three options including cost, risk, delivery speed and operational consequence.
  • Records assumptions and revisit signalsStates the recommendation, what makes it reversible and which evidence triggers review.

How do you design for scalability without overengineering a system whose future load is uncertain?

Answer

  • Separates known demand from guessesUses current load, credible growth scenarios and explicit service objectives instead of vague internet scale.
  • Chooses scalable basics with low complexityKeeps services stateless where useful, uses indexes and bounded work, and avoids unnecessary distribution.
  • Defines measurable evolution triggersLoad tests and production metrics define when to add caching, partitioning or independent scaling.

Product Discovery with Pilot Schools31 question

A researcher proposes an AI hint generator, while teachers say the real problem may be finding suitable exercises quickly. How would you decide what to build first?

Answer

  • Separates problem from proposed solutionClarifies the teacher outcome, frequency and cost of both problems rather than accepting AI as the requirement.
  • Tests the riskiest assumption cheaplyUses interviews, observation, a clickable prototype or manual concierge flow before a full model integration.
  • Chooses using evidence and defines next learningCompares task completion, time saved, adoption and qualitative feedback, then selects or narrows the next iteration.

Production Debugging Across Services42 questions

An API intermittently fails across several services and a third-party dependency. Walk through your investigation.

Answer

  • Defines scope and timelineEstablishes exact symptoms, status or error types, affected users or routes, start time, frequency, and recent deployments or configuration changes.
  • Correlates evidence across servicesUses trace or correlation IDs, latency and error metrics, structured logs, dependency spans, and message identifiers to locate the failing boundary.
  • Mitigates and verifies safelyChooses a small reversible mitigation such as rollback, feature disablement, traffic shift, or circuit opening, then checks user and system metrics.

What information should an integration service record so production failures can be diagnosed without leaking sensitive data?

Answer

  • Records structured contextUses timestamp, service and version, operation, error category and code, duration, dependency, attempt, and outcome as structured fields.
  • Carries correlation identifiersPropagates trace, span, correlation, message, and operation IDs across HTTP, queues, jobs, and database activity where practical.
  • Protects sensitive dataAvoids credentials, tokens, full personal payloads, and payment data; uses redaction, allowlists, hashing or references, access controls, and retention limits.

Production Observability42 questions

Explain the different questions answered by logs, metrics and distributed traces. What would you instrument for the assignment submission flow?

Answer

  • Uses structured logs for events and detailDescribes logs as contextual event records and includes request, release and safe resource identifiers.
  • Uses metrics for trends and alertsTracks submission rate, error rate, p95 latency and dependency or database saturation over time.
  • Uses traces for request pathsLinks frontend or API work, database calls and external dependencies for one request and propagates correlation context.

Teachers report that saving feedback is occasionally slow, but average latency looks normal. How would you investigate?

Answer

  • Looks beyond averagesChecks p95, p99 and latency distributions because a small slow tail can disappear in the average.
  • Segments the affected trafficGroups by school size, endpoint, release, region, database query, model provider or payload size to find a pattern.
  • Correlates traces and resource signalsInspects slow traces and compares database, external-call, queue and saturation timing around the same period.

Queue and Publish-Subscribe Semantics52 questions

What is the practical difference between a work queue and publish-subscribe messaging, and give a suitable use case for each.

Answer

  • Explains recipient semanticsStates that competing consumers share one queue delivery, while each subscription receives its own event stream.
  • Connects command and event intentUses queues naturally for owned work or commands and pub-sub for facts that several independent capabilities may react to.
  • Mentions independent operationRecognizes separate offsets, retries, scaling, and dead-letter handling per subscription or consumer group.

A booking update must trigger customer notification, loyalty points, audit storage, and one inventory recalculation. How would you model the messages?

Answer

  • Publishes the business eventPublishes a BookingUpdated or equivalent event so independent notification, loyalty, and audit subscriptions each receive it.
  • Gives recalculation one ownerUses one command queue or one subscribed inventory capability so competing workers share the recalculation workload without duplicate ownership.
  • Defines reliable contractsIncludes stable IDs, schema versioning, timestamps, correlation or causation IDs, idempotency, and independent retry policies.

Queues, pub/sub, and message reliability42 questions

What is the difference between a work queue and pub/sub, and when would you use each?

Answer

  • Explains work distributionOne message is normally processed by one competing consumer.
  • Explains event broadcastEach independent subscription receives its own event copy.
  • Gives fitting examplesUses a queue for jobs and pub/sub for one event feeding several domains.

A consumer receives the same shipment event twice and may crash after writing to the database. How would you design it?

Answer

  • Makes the side effect idempotentUses an event ID, unique constraint, inbox table, or state transition check.
  • Acknowledges after successThe message is removed only after the durable write commits.
  • Handles repeated failuresUses bounded retries, backoff, DLQ, alerts, and replay tooling.

RabbitMQ Exchanges and Routing52 questions

Explain the relationship between producers, exchanges, bindings, queues, and consumers in RabbitMQ.

Answer

  • Explains publish and routingStates that producers publish to an exchange and the exchange evaluates type, routing key, and bindings.
  • Explains queue and consumersStates that routed messages enter queues and competing consumers receive deliveries from a queue.
  • Explains acknowledgementDescribes acknowledgement after successful durable processing and redelivery when a delivery is rejected or the consumer disappears.

Design RabbitMQ routing for several booking event types consumed independently by notifications, accounting, and analytics.

Answer

  • Uses business routing keysUses a topic or appropriate exchange and stable keys such as booking.confirmed or booking.cancelled.
  • Creates independent queuesGives notifications, accounting, and analytics separate queues so each receives, scales, retries, and fails independently.
  • Includes operational controlsDefines durability, publisher confirmation, mandatory routing or alternate exchange, manual ack, prefetch, DLQ, and metrics as needed.

RabbitMQ Exchanges, Queues, and Reliability42 questions

Design RabbitMQ routing for order.created events where regional processors need only their region and an audit service needs every order event.

Answer

  • Uses a topic exchangePublishes with hierarchical keys such as order.created.eu and order.created.us.
  • Defines correct bindingsBinds regional queues to exact or single-level patterns and the audit queue to a broad order pattern.
  • Includes durability and confirmsDeclares durable infrastructure, persistent messages, and publisher confirms when loss is unacceptable.

One slow consumer has hundreds of unacknowledged messages while other consumers are idle. What setting and processing behaviour would you inspect?

Answer

  • Inspects prefetchExplains that high prefetch lets one consumer reserve many messages before others can receive them.
  • Checks acknowledgement timingEnsures acknowledgement happens after processing and that failures reject or dead-letter correctly.
  • Tunes using measured capacitySets prefetch near safe per-consumer concurrency and measures throughput, latency, and memory.

React Component and State Design43 questions

How do you decide whether state should be local, lifted to a parent, stored in the URL, or placed in a shared store?

Answer

  • Starts from ownership and consumersIdentifies who reads and writes the value and chooses the lowest owner that serves them.
  • Uses lifecycle and persistenceDistinguishes temporary UI state, navigable URL state, shared application state, and remote server state.
  • Avoids premature global stateKeeps state local until sharing, persistence, or coordination justifies a broader owner.

You need a reusable shipment status component used in a table, a details page, and an edit form. How would you design its API without making it overly generic?

Answer

  • Defines a focused responsibilitySeparates status display from status editing and keeps business meaning explicit.
  • Designs a small typed APIUses typed props, controlled values when editing, and composition instead of many boolean flags.
  • Preserves usabilityMentions semantic markup, loading or error states where relevant, and accessibility for interactive variants.

A form copies an API object into local state. When the API refetches, the form sometimes overwrites user edits. How would you redesign the data flow?

Answer

  • Separates draft from server dataTreats the form as an explicit draft with an initialization point rather than continuously mirroring props.
  • Defines refresh and conflict behaviorDecides what happens when remote data changes while the user has unsaved edits.
  • Makes submission explicitBuilds a request from the draft, validates it, then updates or invalidates cached server data after success.

React effects and asynchronous data52 questions

How do you decide what belongs in a useEffect dependency array, and what do you do when adding a dependency causes the effect to run too often?

Answer

  • Includes every reactive value readExplains that props, state, and functions or values created in the component are dependencies when the effect reads them.
  • Does not use dependencies as a manual scheduleAvoids removing dependencies merely to force mount-only behavior and recognizes stale closures.
  • Refactors the cause of repeated executionMoves derived calculations out of the effect, stabilizes only necessary callbacks, or moves logic inside the effect.

A user changes a filter quickly and an older request finishes after the newest request. How would you prevent the old response from replacing current data?

Answer

  • Recognizes an out-of-order raceIdentifies that completion order differs from start order and the older result is no longer relevant.
  • Cancels or invalidates obsolete workUses AbortController, a request token, or cleanup state so obsolete results are ignored.
  • Uses server-state tooling appropriatelyMentions query keys, cancellation, deduplication, or stale handling in a dedicated data-fetching library.

React effects and external synchronization55 questions

Give examples of logic that developers often put in useEffect but should instead calculate during render or run from an event handler.

Answer

  • Moves derived data to renderFiltering, formatting or combining current props and state usually belongs in render, optionally memoized if expensive.
  • Moves user-triggered work to the eventA submit, save or notification caused by a click should normally start in that event handler.
  • Defines the legitimate effect roleAn effect is for synchronization with an external system after render.

A user changes shipment selection quickly and an older request finishes after the newer one, overwriting the UI. How would you fix it?

Answer

  • Identifies out-of-order completionThe requests are valid but their completion order differs from the selection order.
  • Prevents stale updatesCancels the old request or ignores a response whose request key no longer matches current state.
  • Considers a server-state libraryA query library can key, cancel, deduplicate and cache requests consistently.

Explain the dependency array and cleanup function for an effect that subscribes to live shipment updates.

Answer

  • Includes every reactive inputThe shipment id and other reactive values used by the subscription belong in the dependency list.
  • Cleans up the previous resourceCleanup unsubscribes before the effect is replaced or the component unmounts.
  • Explains stale closuresMissing dependencies can make callbacks keep old state or props even while the UI changed.

What problem is useEffect meant to solve, and how do you decide its dependencies and cleanup?

Answer

  • Defines effects as external synchronizationUses effects for network, timers, subscriptions, browser APIs, or other systems outside React.
  • Derives dependencies from used reactive valuesIncludes props, state, and functions read by the effect instead of manually choosing a desired rerun schedule.
  • Reverses the previous synchronizationUnsubscribes, clears timers, or aborts work before rerun or unmount.

A component fetches twice in development and sometimes uses an old filter value. How would you investigate without simply disabling Strict Mode or the dependency lint rule?

Answer

  • Understands development double invocationRecognizes that Strict Mode can expose missing cleanup by intentionally remounting or rerunning development behavior.
  • Fixes the stale closure or dependency flowIncludes the current filter, stabilizes callbacks where necessary, or restructures the effect rather than suppressing warnings.
  • Makes fetching idempotent and cancellableUses cleanup, cancellation, deduplication, or a server-state library so duplicate execution is harmless.

React Effects and Lifecycle53 questions

What is a React Effect for, and what kinds of logic should usually not be placed in an Effect?

Answer

  • Defines external synchronizationExplains that Effects synchronize with systems outside React after a commit.
  • Avoids derived-state EffectsSays calculations from props or state should usually happen during render, not through an Effect and another state update.
  • Separates event logicPlaces user-triggered actions in event handlers when they are caused by a specific interaction.

A user changes filters quickly. An older API request finishes last and overwrites the newer result. How would you prevent this?

Answer

  • Recognizes the raceExplains that completion order can differ from request order and an old closure may commit stale data.
  • Cancels or ignores obsolete workUses AbortController, request identifiers, or cleanup that marks old work as obsolete.
  • Keeps loading and errors consistentModels pending, success, error, and cancellation so old requests cannot corrupt the current state.

Why can removing a value from a React Effect dependency list create a stale-closure bug, and how would you fix the design without disabling the lint rule?

Answer

  • Explains stale closuresExplains that the Effect keeps values from the render in which it was created.
  • Respects reactive dependenciesIncludes reactive values used by the Effect or restructures the code so they are no longer dependencies.
  • Stabilizes only when neededMoves nonreactive logic out, uses functional updates, or stabilizes callbacks and objects when identity is genuinely the problem.

React Forms Architecture42 questions

Design a production-ready customer-edit form in React. Cover state ownership, validation, submission, server errors, accessibility, and unsaved changes.

Answer

  • Separates draft and server dataInitializes a form draft from the record but avoids silently overwriting edits when the query refreshes.
  • Designs validation and errorsUses client feedback for usability, server validation for authority, field-level mapping, and a clear summary or focus strategy.
  • Models submission statesHandles pending, duplicate submit prevention, success, failure, retry, cancellation, and conflict or stale-record cases.
  • Builds accessible interactionConnects labels, descriptions, errors, keyboard order, focus, and status announcements with semantic controls.

A large form becomes sluggish because every keystroke re-renders the whole page. How would you diagnose and improve it without sacrificing validation correctness?

Answer

  • Profiles the update pathUses React Profiler to find which state owner and components rerender on each field change and measures actual interaction delay.
  • Narrows field ownershipKeeps draft state close to fields or uses a form library with subscriptions so unrelated sections do not update.
  • Controls expensive validationSeparates cheap synchronous rules from debounced or server validation and cancels obsolete asynchronous checks.
  • Uses memoization after structureApplies stable props and memoization only to measured expensive sections and keeps correctness independent from skipped renders.

React Hooks52 questions

What are React Hooks, why were they introduced, and what rules must code follow for Hook state to remain predictable?

Answer

  • Defines Hooks clearlyExplains that Hooks let function components use state, effects, context, refs, and other React capabilities.
  • Explains reusable stateful logicDescribes custom Hooks as composition of behavior without sharing one component instance or using inheritance.
  • States the Rules of HooksCovers top-level calls only, React components or custom Hooks only, and stable call order across renders.
  • Avoids lifecycle shorthandRecognizes that effects synchronize with external systems and should not be treated as a direct replacement for every class lifecycle method.

A component uses an effect to calculate filtered data, another effect to reset state when a prop changes, and a third effect to subscribe to a browser API. Which effects would you keep, remove, or redesign?

Answer

  • Removes pure derivation effectsCalculates filtered data during rendering or memoizes it only if the calculation is measured as expensive.
  • Questions reset-on-prop-changeConsiders component identity, keys, lifted state, or explicit event handling instead of synchronizing duplicated state after render.
  • Keeps genuine external synchronizationUses an effect for browser subscriptions with correct setup, dependency handling, and cleanup.
  • Handles races and stale closuresMentions cancellation, current values, cleanup order, and avoiding stale state in asynchronous callbacks.

React Memoization51 question

A React page feels slow and appears to re-render too much. How would you investigate and optimize it, and when would virtualization be more important than memoization?

Answer

  • Measures before changing codeUses React Profiler or browser tooling to identify the expensive interaction and component rather than guessing.
  • Fixes state and component boundariesNarrows state ownership, splits expensive subtrees, and avoids passing unnecessary changing props before adding caches.
  • Applies memoization selectivelyExplains when React.memo, useMemo, and useCallback help and how fresh references can defeat them.
  • Uses virtualization for large DOMsRecognizes that a huge mounted list needs windowing or pagination because memoization alone does not reduce DOM size.

React Performance46 questions

When do React.memo, useMemo, and useCallback help, and when can they make the code worse?

Answer

  • Starts with measurementRequires a measured expensive render, calculation, or identity-sensitive child before adding memoization.
  • Distinguishes the toolsExplains memoizing a component result, a computed value, or a function identity for a concrete consumer.
  • Explains costs and limitsMentions comparison overhead, dependency complexity, stale values, and the fact that memoization does not fix poor state placement.

A logistics dashboard becomes sluggish when users update one filter. Walk through how you would investigate the problem before changing code.

Answer

  • Defines and reproduces the slow interactionUses a realistic dataset and identifies the user-visible latency or frame problem.
  • Profiles across layersChecks React renders, browser main-thread work, network requests, and DOM size rather than assuming the cause.
  • Chooses the largest fixConsiders state scope, request deduplication, list virtualization, algorithm changes, and only then selective memoization.

A table may display 50,000 shipment rows with live updates. What frontend techniques would you consider, and what trade-offs do they introduce?

Answer

  • Uses windowing or paginationAvoids rendering every row at once through virtualization, pagination, or server-side querying.
  • Controls update frequency and scopeBatches or throttles updates, normalizes data, and rerenders only affected rows.
  • Discusses trade-offsMentions accessibility, variable row heights, scroll behavior, memory, and freshness requirements.

A shipment table becomes slow while typing into a filter. Describe how you would diagnose the bottleneck before changing the code.

Answer

  • Defines a measurable interactionReproduces with representative data and observes input latency, render duration and network behavior.
  • Uses profiling evidenceUses React Profiler and browser performance tools to find expensive components, JavaScript or layout.
  • Separates frontend and backend causesChecks response size and timing so a network or data-volume problem is not misdiagnosed as rendering.

Profiling shows that a large table rerenders every row on each keystroke. What options would you consider, and how would you choose?

Answer

  • Reduces rendered workConsiders virtualization, pagination or deferring the expensive result update.
  • Stabilizes only useful boundariesUses memoization or stable props only where profiling shows repeated expensive work.
  • Measures after the changeRepeats the same profile and checks responsiveness, memory and complexity trade-offs.

When are useMemo, useCallback and React.memo useful, and when do they make a codebase worse?

Answer

  • Explains what memoization reusesIt reuses a calculation, function identity or component result while relevant inputs stay equal.
  • Names evidence-based casesIt helps with expensive calculations or memoized children sensitive to reference identity.
  • Recognizes maintenance and runtime costMemoization adds comparisons, retained values and dependency complexity, so cheap work may become less clear without meaningful gain.

React rendering and reconciliation52 questions

What can cause a React component to render again, and how would you diagnose and reduce unnecessary work without blindly adding memoization?

Answer

  • Names the main render triggersCovers state updates, parent renders with new props, and consumed context changes.
  • Understands reference identityExplains how newly created objects, arrays, and callbacks can defeat shallow memoization.
  • Measures before optimizingUses React profiling or browser measurements and applies memoization only around expensive, stable boundaries.

A shipment list can be filtered, reordered, and edited inline. Why can using the array index as the React key produce incorrect UI state, and what should the key represent?

Answer

  • Keys define item identityExplains that React uses key and element type to match an item between renders.
  • Explains the index-key failureDescribes state or DOM being attached to the wrong logical item after insertion, deletion, filtering, or reordering.
  • Chooses a stable domain identifierUses a unique, stable shipment ID and notes that index is acceptable only for truly static lists.

React Rendering and State56 questions

How does a React state update lead to a UI change, and why should state objects and arrays be treated as immutable?

Answer

  • Describes render schedulingExplains that setting state schedules a render and each render sees a snapshot of state.
  • Explains immutable updatesExplains that new references make changes explicit and avoid modifying state used by previous renders.
  • Separates render and DOM commitRecognizes that rendering calculates UI and React then commits necessary DOM changes.

A shipment table sometimes fails to update after a nested property is changed directly. How would you diagnose and fix it?

Answer

  • Identifies mutationLooks for direct writes to an object or array already held in state or a store.
  • Creates a new update pathCreates new references for every changed level or uses an immutable update helper.
  • Checks state designConsiders normalized data, derived values, and whether the affected data should be local or shared.

What makes a good React list key, and what bugs can appear when an array index is used for a list that can be reordered?

Answer

  • Defines a stable keyUses an identifier that is stable and unique among siblings for the same logical item.
  • Explains index-key bugsExplains that component state or DOM identity may move to the wrong item after insertions, deletions, or reordering.
  • Understands key scopeNotes that keys are for React's sibling matching and are not passed as a normal prop.

A page has a shipment table, filters and a detail panel. Where would you keep the selected shipment and filters, and why?

Answer

  • Places state at the closest shared ownerState shared by table and detail panel belongs at their closest common owner or a focused route/store boundary.
  • Separates local and shareable stateDistinguishes local UI details from filters that should survive navigation or be represented in the URL.
  • Avoids duplicated selected objectsStores an id or canonical entity and derives the selected object rather than copying it.

A component copies an API result into local state and later shows stale data after a background refresh. What is likely wrong, and how would you redesign it?

Answer

  • Finds duplicated sources of truthThe server result and copied local state can diverge because updates reach only one copy.
  • Derives display from canonical dataRenders from query or parent state and stores only user edits or identifiers that are genuinely local.
  • Recognizes an intentional editable draftA separate draft is valid when editing is explicit, with reset and conflict behavior defined.

How do you decide whether React state belongs in a component, context, URL, server-state library or global store?

Answer

  • Classifies the stateDistinguishes local UI, shareable navigation, remote server data and cross-cutting client state.
  • Uses scope and lifetimeChooses the narrowest owner that matches who needs the value and how long it should survive.
  • Mentions operational trade-offsConsiders caching, invalidation, persistence, debugging and rerender impact rather than one universal rule.

React Rendering and State52 questions

A student table becomes sluggish when a filter changes. How would you determine why rows re-render and decide whether memoization is appropriate?

Answer

  • Measures before optimizingUses React profiling or targeted instrumentation to identify expensive components and render causes.
  • Checks state and identity changesLooks for lifted state that is too broad, recreated objects or callbacks, unstable keys and expensive derived work.
  • Applies selective memoizationUses React.memo, useMemo or useCallback only when stable inputs and measured savings justify their complexity.

For an assignment editor, how would you decide which data is local component state, shared client state, URL state or server state?

Answer

  • Uses ownership and scopeKeeps state as close as possible to the components that own and change it, lifting only when several consumers need one source.
  • Separates server stateTreats fetched assignments as server state with loading, caching, invalidation and refetch behavior rather than copying them into arbitrary global state.
  • Uses URL state for shareable navigationPuts filters, selected tabs or identifiers in the URL when they should survive refresh, navigation or sharing.

React rendering and state updates52 questions

What causes a React component to render again, and how is that different from updating the DOM?

Answer

  • Names the main render triggersState updates, changed context, and a parent render can cause the component function to run again.
  • Separates render from DOM commitReact calculates a new element tree and only commits the DOM changes that reconciliation finds necessary.
  • Explains state snapshots and referencesUses immutable updates and functional state updates when the next value depends on the previous one.

A shipment table becomes slow with several hundred rows. How would you find the real bottleneck and decide whether memoization, virtualization, or a backend change is appropriate?

Answer

  • Measures before optimizingUses the React Profiler, browser performance tools, network timings, and concrete user interactions.
  • Distinguishes likely causesSeparates excessive renders, expensive calculations, too many DOM nodes, large payloads, and slow backend queries.
  • Chooses a targeted fixUses memoization for repeated expensive work, virtualization for many visible rows, or pagination/query changes for excessive data.

React Rendering Model52 questions

What can cause a React function component to render again, and which of those renders necessarily produce DOM changes?

Answer

  • Names the main triggersCovers state updates, parent renders, and changes to consumed context, while noting that external stores can also schedule updates.
  • Separates render from commitExplains that component execution calculates a candidate UI and does not automatically mean that the DOM changes.
  • Mentions identity and bailoutsExplains that memoization, equal props, unchanged state, and stable element identity can let React avoid or minimize work.

After a state update, how does React determine what should be preserved, updated, or replaced in the UI?

Answer

  • Creates a new element descriptionExplains that React calls the affected components to calculate a new element tree from current state and props.
  • Compares type, position, and keysExplains that reconciliation uses element type and sibling position, with keys providing stable identity in lists.
  • Commits only required host changesDistinguishes the comparison from the commit that applies selected DOM mutations and effects.

React state ownership42 questions

How do you decide whether a value should stay in local component state, move to a parent, go into context or a global store, or be managed as server state?

Answer

  • Uses scope and lifetimeKeeps state close to the components that need it and considers how long it must survive.
  • Lifts or shares only when coordination requires itMoves state to a common parent, context, or store according to the number and distance of consumers.
  • Separates server state from client stateRecognizes that remote data needs caching, invalidation, refetching, and stale handling.

A component stores a list of shipments and also stores a filteredShipments list that is recalculated in an effect. What risks do you see, and how would you redesign it?

Answer

  • Identifies duplicated truthExplains that the filtered list can become out of sync with the source list or filter.
  • Derives the value during renderCalculates filteredShipments from shipments and filter instead of storing it independently.
  • Uses memoization only for measured costAdds useMemo only when the filtering is expensive and dependencies are stable.

React state ownership and server state42 questions

For a React logistics dashboard, how would you decide whether a value belongs in component state, Context, a global store, the URL, or a server-state cache?

Answer

  • Uses ownership and lifetimeKeeps transient state close to the components that own and change it.
  • Separates URL and server stateUses the URL for shareable navigation and a query cache for remote data with freshness and invalidation needs.
  • Uses global state only for genuine coordinationChooses Context or a store when distant features need one client-owned source of truth, not merely to avoid a few props.

A component stores API data, a filtered copy, and a selected object in three separate state variables. What problems can this cause, and how would you redesign it?

Answer

  • Identifies synchronization driftExplains that copied state can become inconsistent when one variable updates without the others.
  • Stores only authoritative valuesKeeps the server result or cache plus filter criteria and derives the filtered list during render or with measured memoization.
  • Stores selection by stable identityKeeps a selected id and resolves the object from current data so updates do not leave a stale selected copy.

React State Strategy42 questions

A team proposes putting all application state into Redux Toolkit. How would you decide what should remain local, what belongs in the URL, what is server state, and what genuinely needs a shared client store?

Answer

  • Classifies state by ownershipDistinguishes local UI state, shared client state, URL state, server state, and derived values.
  • Keeps ownership narrowPlaces state at the smallest common owner and avoids global storage for temporary interaction details.
  • Uses specialized tools deliberatelyUses URL state for shareable navigation, TanStack Query for remote data, and Redux only for cross-cutting client-owned domains that need it.
  • Avoids duplicate sources of truthWarns against copying query results or derived values into another store and maintaining manual synchronization.

For a CRM page with filters, a customer record, an unsaved edit form, an open modal, and the logged-in user's permissions, place each kind of state and justify the ownership.

Answer

  • Places navigation state in the URLStores shareable filters, sort order, selected tab, or pagination in the URL where appropriate.
  • Treats records as server stateKeeps the customer record in a query cache with freshness and mutation handling rather than duplicating it globally.
  • Keeps drafts and ephemeral UI localPlaces unsaved form values and modal visibility in the feature or component that owns the interaction.
  • Handles permissions as shared session dataTreats logged-in identity and permissions as shared, stable session data consumed through a focused boundary.

React Upgrade Strategy52 questions

How would you migrate an older production React application to React 18 safely?

Answer

  • Creates an upgrade inventoryChecks deprecated APIs, ReactDOM entry points, third-party compatibility, Strict Mode warnings, tests, and browser requirements.
  • Separates compatibility changesUpdates supporting libraries and warnings in smaller changes before enabling the new root and rendering behavior.
  • Tests behavior, not only compilationRuns component, integration, visual, accessibility, performance, and production-like tests, including effect and timing-sensitive behavior.
  • Rolls out and observesUses a limited entry point, feature exposure, error monitoring, and rollback while expanding the migration.

The greenfield storefront uses React 19 while another product remains on React 18. How would you manage compatibility across the shared UI library and avoid forcing an unsafe synchronized upgrade?

Answer

  • Defines supported version policyUses peer dependency ranges, a tested compatibility matrix, and explicit support or deprecation windows.
  • Avoids version-specific internalsKeeps shared components on stable public APIs and isolates features that require only the newer React version.
  • Tests representative consumersRuns the library's behavior, visual, and type tests against both React versions and representative applications.
  • Plans independent migrationAllows products to upgrade separately with release notes, codemods or migration guidance, and rollback.

Redis Caching and Coordination Patterns42 questions

How would you add Redis cache-aside to a product endpoint while controlling stale data, stampedes, memory growth, and Redis outages?

Answer

  • Defines cache-aside flowReads Redis first, loads the database on a miss, stores with TTL, and invalidates after successful writes.
  • Controls stampede and memoryUses bounded keys, jittered TTL or single-flight loading, and monitors evictions and hot keys.
  • Degrades safely on Redis failureTreats Redis as optional for caching, uses short timeouts, falls back to the database within capacity, and avoids retry storms.

A rate limiter increments a counter and then sets its TTL in a separate command. What race or failure can occur, and how would you make the operation atomic?

Answer

  • Identifies the partial-operation riskExplains that a crash between increment and expiry can leave a permanent key or inconsistent window.
  • Uses an atomic Redis operationUses a Lua script, transaction where suitable, or a single command pattern that performs the change atomically.
  • Defines rate-limit semanticsClarifies fixed or sliding window behaviour, key granularity, clock assumptions, and response headers.

Relational Data Integrity52 questions

Creating a class also creates memberships and an audit event. Which operations belong in one database transaction, and what should not be kept inside it?

Answer

  • Groups invariant-preserving writesIncludes database writes that must all exist or all be absent for the class to be valid.
  • Keeps external calls outsideAvoids waiting for email, analytics or remote services while locks and a database transaction remain open.
  • Handles post-commit events reliablyUses an outbox or committed job record when an external event must eventually follow the database change.

Which rules would you enforce in the application and which in PostgreSQL for class memberships and assignment submissions?

Answer

  • Uses both layers for different purposesUses application validation for clear feedback and database constraints as the final integrity barrier.
  • Names suitable database constraintsUses foreign keys, unique constraints, not-null and checks for rules expressible in the schema.
  • Keeps contextual rules in domain logicHandles rules requiring permissions, time, several aggregates or external context in application logic, still using transactions where needed.

Relational Data Modeling41 question

Design the core relational model for applications, renewals, deadlines, and payments. Which rules would you enforce in the database?

Answer

  • Identifies entities and relationshipsSeparates stable business concepts and models one-to-many or optional relationships explicitly.
  • Chooses identifiers and uniquenessUses primary keys plus business unique constraints such as one renewal per application and year.
  • Uses database integrity constraintsApplies foreign keys, nullability, checks, and atomic constraints for rules that must survive concurrent writers.
  • Connects the model to access patternsConsiders common queries, indexes, data volume, history, and audit requirements.

Relational Database Indexing42 questions

Explain how a relational database index helps a query and why the database may still choose not to use it.

Answer

  • Explains index lookupDescribes an ordered or specialized structure that narrows candidate rows and may support joins or ordering.
  • Explains optimizer choiceStates that low selectivity, small tables, stale statistics, functions, casts, or cost estimates can make a scan cheaper.
  • Explains index costMentions additional storage, cache pressure, and maintenance on inserts, updates, and deletes.

A slow query filters by status and departure date, joins by customer ID, and orders by creation time. How would you decide which index to create?

Answer

  • Starts from the actual workloadUses query frequency, parameter distribution, result size, latency goal, and existing indexes rather than designing from SQL text alone.
  • Reasons about key orderConsiders equality predicates, ranges, join columns, ordering, selectivity, and the database’s left-prefix or access rules.
  • Verifies the index empiricallyCompares execution plans and timings with realistic data and checks write overhead, lock duration, and rollout method.

Reliable API command handling42 questions

A client times out while creating a transport booking and sends the same request again. How would you prevent duplicate bookings while still allowing safe retries?

Answer

  • Recognizes the uncertain outcomeExplains that the first command may have succeeded even though the client did not receive the response.
  • Uses a stable idempotency keyRequires the same logical command to reuse one key and stores the key with the result atomically.
  • Returns the original outcome on repetitionDoes not execute the business side effect again and handles key reuse with a different payload as an error.

How should a client decide whether to retry after receiving a timeout, 400, 409, 429, or 503 response?

Answer

  • Classifies failures correctlyTreats validation and many conflicts as permanent until input or state changes, while timeout, rate limit, and service unavailability may be transient.
  • Checks whether repeating the operation is safeRetries reads or idempotent commands and avoids blindly repeating side effects.
  • Controls retry pressureUses Retry-After when present plus bounded exponential backoff, jitter, and metrics.

Reliable LLM integration31 question

You want an LLM to extract shipment details from free-form emails. How would you design the feature so that it is useful, measurable, secure, and safe to operate?

Answer

  • Defines a narrow, measurable taskSpecifies required fields, acceptable error, latency, cost, privacy, supported languages, and what happens when confidence is low.
  • Keeps validation and side effects deterministicRequests structured output, validates it with a schema and business rules, protects data, and requires normal authorization and human confirmation before creation.
  • Builds evaluation and operational feedbackUses a representative labelled set, tracks field-level quality, monitors cost and failure categories, versions prompts and models, and provides fallback.

Resilience Patterns52 questions

A critical third-party service becomes slow and intermittently unavailable. Which resilience techniques would you combine and why?

Answer

  • Uses deadlines and bounded resourcesSets connection and request timeouts, an overall deadline, bounded concurrency, and queue or pool limits.
  • Prevents failure amplificationUses selective bounded retries with jitter, circuit breaking, bulkheads, rate limiting, or load shedding to avoid retry storms and exhaustion.
  • Defines degradation and recoveryChooses business-safe fallback or explicit failure, communicates stale state, monitors dependency health, and restores traffic gradually.

Explain how a circuit breaker works, what it protects, and what it does not solve by itself.

Answer

  • Explains breaker statesDescribes closed calls, opening after classified failures, fast rejection while open, and limited probes in half-open state.
  • Explains protection goalStates that the breaker reduces repeated load and waiting on an unhealthy dependency and gives it time to recover.
  • Explains limitationsNotes that it still needs timeouts, correct failure classification, fallback or error semantics, concurrency limits, and observability.

Resilient external dependencies42 questions

A carrier API becomes slow and starts returning intermittent 503 errors. How would you stop it from degrading your entire application?

Answer

  • Bounds waiting and retriesUses separate connection and request deadlines, retries only transient idempotent operations, and applies exponential backoff with jitter and a strict attempt budget.
  • Isolates the dependency failureLimits per-carrier concurrency, protects pools and event-loop resources, and uses a circuit breaker or load shedding after sustained failure.
  • Defines controlled degradation and recoveryReturns a clear temporary failure or acceptable cached data, instruments dependency health, and probes recovery without a retry storm.

During an outage, traffic to a dependency becomes five times higher even though user traffic is unchanged. What is likely happening, and how would you fix it?

Answer

  • Recognizes retry amplificationExplains that clients, gateways, services, and libraries may each retry, multiplying attempts and extending request lifetime.
  • Creates one bounded retry policyChooses the appropriate retry layer, limits attempts within an end-to-end deadline, and adds exponential backoff, jitter, and retryable-error classification.
  • Adds overload protection and evidenceUses concurrency limits, circuit breaking or load shedding, exposes attempt metrics, and tests failure behavior under load.

Resilient External Integrations43 questions

What patterns would you use when a Node.js service depends on an unreliable external pricing API?

Answer

  • Uses deadlines and timeoutsSets a request budget and shorter downstream timeout so the service can still respond or recover.
  • Retries safely and narrowlyRetries transient failures only with bounded attempts, backoff, jitter, and idempotency.
  • Limits blast radiusUses circuit breaking, concurrency limits, queues, cache, or a clear degraded mode.

During a partner outage, request volume to your service increases because clients and several internal layers all retry. How would you stop the retry storm?

Answer

  • Finds multiplied retriesMaps every retry layer and removes or coordinates overlapping attempts.
  • Reduces pressureUses backoff, jitter, rate limits, circuit breaking, queues, and bounded concurrency.
  • Uses a total retry budgetLimits attempts by deadline and fleet-wide or request-level budgets and monitors retry volume.

A new logistics workflow may take between two seconds and several minutes depending on partners. Should the API keep one request open or use an asynchronous job model?

Answer

  • Uses duration and reliabilityChooses asynchronous work when duration is long or unpredictable and a connection should not remain open.
  • Designs the async contractUses job creation, status polling or events, stable identifiers, idempotency, and terminal states.
  • Handles user experience and operationsCovers progress, cancellation, retry, dead-letter handling, retention, and notification.

responsive_design1 question

A design from Figma looks correct at one desktop width but breaks in real content and smaller viewports. How would you diagnose and redesign the CSS rather than adding one-off overrides?

Answer

  • Reproduces with realistic constraintsTests long text, localization, zoom, different viewport sizes, loading states, and actual browser DevTools measurements.
  • Examines layout mechanicsChecks containing blocks, intrinsic sizes, flex or grid constraints, min-width behavior, overflow, and box sizing.
  • Designs fluid behaviorUses content-driven breakpoints, wrapping, minmax or clamp where suitable, and avoids fixed dimensions copied blindly from Figma.
  • Protects consistency and accessibilityUses shared tokens, semantic order, keyboard and zoom checks, and visual regression for representative states.

REST API and HTTP semantics52 questions

Design the main REST endpoints for creating, reading, updating, and cancelling a shipment. Explain your method and status-code choices.

Answer

  • Models domain resources clearlyUses nouns and stable identifiers, such as POST /shipments and GET /shipments/{id}, rather than RPC-style action URLs everywhere.
  • Uses HTTP methods and statuses intentionallyDistinguishes creation, retrieval, partial update, accepted asynchronous work, not found, validation, and conflict responses.
  • Makes dangerous operations retry-safeUses idempotency keys or conditional updates for creation or cancellation where network retries could duplicate effects.

A shipment list grows to millions of rows and changes continuously. How would you design pagination, filtering, ordering, and API evolution?

Answer

  • Selects a stable pagination strategyExplains why cursor or keyset pagination is usually safer and faster for large, changing datasets.
  • Defines deterministic ordering and filtersUses an indexed, unique tie-breaker and validates allowed filters and sort fields.
  • Evolves the contract compatiblyAdds optional fields and tolerant enum handling where possible; versions or coordinates unavoidable breaking changes.

REST API and HTTP Semantics53 questions

What does it mean to design a REST-style API, and how do HTTP method semantics help clients?

Answer

  • Models resourcesUses stable business resources and representations rather than arbitrary RPC-like endpoint names for every action.
  • Uses method semanticsExplains GET safety and the intended semantics of POST, PUT, PATCH, and DELETE.
  • Uses HTTP as a contractUses status codes, headers, caching, content types, and conditional requests consistently.

Design the API behavior for creating a shipment, partially updating it, and cancelling it. Include success and error responses.

Answer

  • Chooses clear resources and methodsUses coherent paths and appropriate methods for creation, partial update, and cancellation.
  • Uses meaningful status codesUses responses such as 201, 200 or 204, 400 or 422, 404, 409, and 401 or 403 where appropriate.
  • Handles repeat and concurrent changesDiscusses idempotency keys, version fields, ETags, or conflict responses for repeated or concurrent operations.

How would you evolve a REST API used by independently deployed web and partner clients without breaking them?

Answer

  • Prefers additive compatible changesAdds optional fields or new endpoints and avoids changing existing meaning or removing values unexpectedly.
  • Uses explicit versioning when neededUses URL, header, or media-type versioning for real breaking changes and documents support periods.
  • Plans migration and observationUses contract tests, deprecation notices, telemetry, and a staged consumer migration.

REST API contract design52 questions

Design a small REST API for creating a shipment, reading its current status, and updating selected shipment details. Which resources, methods, and status codes would you choose?

Answer

  • Models clear resources and methodsUses shipment resources and appropriate GET, POST, and PATCH or PUT semantics.
  • Uses meaningful status codesDistinguishes successful creation, normal reads, validation errors, missing resources, conflicts, and accepted asynchronous work.
  • Defines a stable contractKeeps transport models intentional, validates input, and avoids exposing database details directly.

A business team wants to rename a response field and change an enum value used by several clients. How would you evolve the API safely?

Answer

  • Recognizes breaking changesExplains that removing or renaming a field and changing an existing enum meaning can break consumers.
  • Uses an additive migration pathAdds the new field or value, serves both forms temporarily, and updates consumers before removal.
  • Manages deprecation operationallyTracks client usage, publishes a timeline, tests contracts, and introduces a new version only when coexistence cannot preserve compatibility.

REST API contracts53 questions

Design the main endpoints for reading a shipment, updating selected fields and requesting a repricing operation. Explain your HTTP choices.

Answer

  • Models stable resourcesUses clear shipment identifiers and resource-oriented paths for retrieval and ordinary updates.
  • Uses method semantics deliberatelyUses GET safely, PATCH for partial changes, and a clear command or subresource for repricing.
  • Defines outcomes and concurrency behaviorCovers validation, not found, authorization, accepted async work and conflicting updates.

Which API changes are breaking for existing clients? Discuss removing a field, adding an optional field and adding a new enum value.

Answer

  • Defines breaking from the consumer viewA change is breaking when a previously valid client can no longer parse, call or interpret the contract correctly.
  • Classifies common field changesRemoving or changing meaning is usually breaking; a truly optional additive field is usually compatible.
  • Recognizes enum expansion riskA new enum value can break exhaustive or closed-enum clients even though the schema change looks additive.

What should a consistent REST API error response contain, and how should it differ for validation, authentication and unexpected server failures?

Answer

  • Defines a stable machine-readable shapeIncludes a stable code, human-safe message, optional field details and correlation id.
  • Uses meaningful HTTP status codesDistinguishes invalid input, missing or invalid identity, forbidden action and unexpected server failure.
  • Separates client and internal diagnosticsClients get stable safe information; structured logs retain stack and dependency context using the correlation id.

REST API Contracts and HTTP Semantics52 questions

Design create, read, full update, partial update, and delete operations for an order resource. Which HTTP methods and key status codes would you use, and why?

Answer

  • Uses method semanticsMaps create to POST, read to GET, full replacement to PUT, partial change to PATCH, and removal to DELETE.
  • Uses meaningful status codesUses outcomes such as 201, 204, 400, 404, 409, and 412 according to the contract.
  • Discusses idempotency and retriesExplains which methods are intended to be idempotent and how create retries need an idempotency mechanism.

A team wants to rename a response field, make an optional request field required, and add a new enum value. Which changes can break clients, and how would you release them safely?

Answer

  • Identifies obvious breaking changesTreats field removal or rename and optional-to-required input as breaking for existing clients.
  • Treats enum expansion carefullyExplains that adding an enum value can break clients that assume the set is closed or use exhaustive matching.
  • Proposes compatible rolloutUses additive changes, deprecation, dual fields or versioning, telemetry, and a migration window.

REST Architectural Style54 questions

What does REST stand for, what are its central constraints, and how is a RESTful HTTP API different from any API that happens to use JSON over HTTP?

Answer

  • Expands and defines RESTStates Representational State Transfer and explains that resources are manipulated through representations under a constrained architectural style.
  • Covers core constraintsMentions client-server separation, stateless requests, cacheability, uniform interface, layered system, and optional code-on-demand.
  • Connects HTTP semanticsUses resource-oriented URLs, standard methods, status codes, idempotency, and content negotiation meaningfully.
  • Rejects JSON-over-HTTP shorthandExplains that using HTTP and JSON alone does not satisfy REST constraints or create a uniform resource interface.

What is REST? Give a definition that distinguishes the architectural style from simply using HTTP and JSON.

Answer

  • Defines REST as an architectural styleExplains that REST is a set of architectural constraints for distributed hypermedia systems, not a protocol or file format.
  • Names the central constraintsMentions a uniform interface and stateless requests, with caching, layering, or client-server separation as supporting constraints.
  • Separates REST from HTTP conventionsStates that HTTP is a common implementation platform and that JSON-over-HTTP alone does not make an API RESTful.

Walk through the main REST constraints and explain one practical design consequence of each.

Answer

  • Explains the uniform interfaceConnects consistent methods, status codes, representations, and resource identifiers to lower client coupling.
  • Explains statelessnessClarifies that each request carries the context needed for processing and that server-side domain data may still exist.
  • Covers caching and layeringExplains how explicit cache semantics and intermediaries can improve performance and operational flexibility.
  • Acknowledges trade-offsNotes that strict REST constraints may not fit every interaction, especially highly conversational or action-heavy protocols.

An API currently exposes POST /calculateRenewal, POST /approveRenewal, and POST /cancelRenewal. How would you review or redesign it using resource-oriented principles?

Answer

  • Identifies stable resources and state transitionsFinds concepts such as renewal, approval, or cancellation request and gives them stable identities where useful.
  • Uses HTTP semantics deliberatelyMaps safe reads, idempotent updates, creation, and status codes consistently instead of choosing verbs mechanically.
  • Preserves domain rulesKeeps authorization, valid transitions, concurrency checks, and audit requirements explicit rather than assuming CRUD removes business behavior.
  • Stays pragmaticAccepts action resources or commands when they make the contract clearer and explains the trade-off.

Retries and Dead-letter Handling42 questions

How would you design a retry policy for calls to a slow or unstable downstream service?

Answer

  • Classifies retryable failuresRetries transient network, timeout, throttling, or selected 5xx failures and avoids retrying validation, authentication, and deterministic business errors.
  • Ensures safety and bounded effortRequires idempotency, sets per-attempt timeouts, maximum attempts or deadline, exponential backoff, and jitter.
  • Protects the dependency and callerUses circuit breaking, concurrency or rate limits, cancellation, fallback, and metrics so retries do not amplify an outage.

What information and operational process should surround a dead-letter queue so failed messages are recoverable?

Answer

  • Preserves useful diagnosticsKeeps original message identity and payload reference plus error category, attempts, timestamps, source, schema version, and correlation context without leaking secrets.
  • Defines ownership and alertingAssigns an owner, metrics, alert thresholds, age or backlog SLOs, dashboards, and a triage procedure.
  • Provides controlled replaySupports inspection, cause correction, filtering, dry run or staged replay, idempotency, authorization, and audit history.

retry_strategies1 question

A partner API is slow, intermittently fails, and sometimes completes a request after your timeout. How would you design the integration?

Answer

  • Uses explicit timeouts and budgetsSets connect and operation timeouts within an overall request or job deadline.
  • Makes retries safeUses idempotency keys or operation identifiers and distinguishes retryable from permanent failures.
  • Controls retry pressureUses limited attempts, exponential backoff, jitter, circuit breaking, and bounded concurrency.
  • Handles unknown outcomesStores operation state, queries status where possible, reconciles later, and supports manual recovery.
  • Adds operational visibilityTracks dependency latency, error categories, retry counts, circuit state, and SLO impact.

Reviewing AI-Generated UI33 questions

The company generates much of its UI from Figma with AI. How would you design the workflow so that automation improves throughput without lowering code quality?

Answer

  • Defines machine-readable constraintsSupplies design-system components, tokens, naming, API schemas, examples, forbidden patterns, and a clear output boundary.
  • Generates small reviewable unitsProduces one component or feature slice with traceable design inputs rather than a large opaque application rewrite.
  • Runs independent quality gatesApplies types, lint, behavior, accessibility, visual, security, performance, and consumer checks outside the generation model.
  • Measures end-to-end valueTracks generation time, review and rework cost, escaped defects, reuse, and lead time rather than lines of generated code.

An AI-generated React component passes visual review and unit tests. What security and correctness risks would you still inspect manually or with independent tooling?

Answer

  • Checks untrusted data renderingReviews HTML injection, dangerous rendering APIs, URL handling, link behavior, and sanitization at the correct boundary.
  • Checks authorization assumptionsEnsures hidden controls are not treated as security, permission decisions come from trusted server enforcement, and errors do not leak data.
  • Checks browser and supply-chain behaviorReviews target blank safety, third-party packages, secrets, analytics data, storage, and network requests.
  • Challenges generated testsAdds adversarial and integration cases, validates external inputs at runtime, and verifies behavior in the actual host application.

An AI tool generates React UI directly from a Figma design. Walk through the review you would perform before allowing the code into a shared production codebase.

Answer

  • Validates behavior beyond appearanceChecks loading, empty, error, permission, responsive, interaction, and data states that a static design may not show.
  • Aligns with the existing systemReuses design-system primitives, feature boundaries, API types, naming, and established patterns instead of accepting duplication.
  • Checks user and technical qualityReviews semantic HTML, keyboard and screen-reader behavior, security, image loading, rendering cost, and bundle impact.
  • Requires independent evidenceRuns types, linting, behavior tests, visual regression, and the actual application, and keeps the diff small enough to review.

Runtime validation at system boundaries53 questions

Walk through how you would validate and handle a shipment creation request in a TypeScript Node.js API.

Answer

  • Treats external input as untrustedThe raw body starts as unknown and is not cast directly to a domain type.
  • Uses an executable schemaChecks required fields, formats, ranges and cross-field rules at the boundary.
  • Returns stable validation feedbackMaps failures to a documented 400 response with field-level information and no internals.

A third-party carrier API sometimes returns a field with the wrong type. TypeScript says the client response is valid. How would you diagnose and fix the design?

Answer

  • Explains the static type limitationThe declared client type is an assertion about code, not proof about the network payload.
  • Parses the response at runtimeValidates the response schema before mapping it into an internal trusted model.
  • Handles provider failure explicitlyRecords provider context, returns or queues a controlled failure, and monitors contract violations.

How would you choose between handwritten checks, a schema library and generated validation from an API specification?

Answer

  • Positions handwritten checks appropriatelySimple local rules may justify direct checks, but large contracts become repetitive and inconsistent.
  • Explains schema-library valueA schema can validate at runtime and infer or align TypeScript types from one definition.
  • Explains contract generation trade-offsGenerated validators help external contracts but add tooling and require disciplined specification ownership.

Scalability and architecture trade-offs41 question

A modular React and Node.js application is growing quickly. When would you keep a modular monolith, and what evidence would justify extracting a service?

Answer

  • Explains why a modular monolith can scaleNotes that one deployable can still be horizontally scaled and can maintain clear internal module boundaries with lower operational cost.
  • Requires concrete extraction signalsLooks for independent scaling, release cadence, ownership, reliability isolation, technology constraints, or persistent coupling pain.
  • Accounts for distributed-system costsIncludes network failures, data ownership, consistency, observability, deployment, testing, and on-call complexity.

scrum1 question

How do you perform architecture work in Scrum without either doing big design up front or letting every sprint create accidental architecture?

Answer

  • Uses just-enough upfront designClarifies high-risk decisions, boundaries, NFRs, and irreversible choices while leaving low-risk details to implementation.
  • Evolves architecture incrementallySlices work into vertical increments, preserves compatibility, and uses refactoring and migration steps.
  • Uses spikes for uncertaintyTime-boxes experiments and records decisions instead of letting research become open-ended.
  • Builds feedback into deliveryUses review, tests, telemetry, retrospectives, and architecture checkpoints based on risk rather than ceremonial approval.

Service Resilience Basics42 questions

An optional language service becomes slow and unreliable. How would you keep the core exercise workflow available?

Answer

  • Sets a bounded timeout budgetUses a dependency timeout shorter than the user-facing request budget and cancels abandoned work where possible.
  • Retries only safe transient failuresLimits retries, uses backoff and jitter, and avoids retrying validation or persistent failures.
  • Isolates and degrades gracefullyStops repeated calls when unhealthy, protects connection or worker capacity, and returns the exercise without the optional enhancement.

Explain how retries can cause a retry storm. What controls would you add to a Node.js service calling a constrained database or API?

Answer

  • Explains load amplificationShows that many callers retrying at the same time add traffic to an already failing dependency and delay recovery.
  • Bounds retry and concurrencyUses low attempt limits, exponential backoff with jitter, concurrency limits, timeouts and a circuit breaker or load shedding.
  • Checks operation safetyRetries only transient failures and ensures state-changing operations are idempotent or deduplicated.

SOA and Microservices Trade-offs52 questions

How would you explain the difference between SOA and microservices, and when might a more centralized SOA approach still be reasonable?

Answer

  • Compares service independenceExplains that microservices normally emphasize smaller business boundaries, independent deployment, and decentralized ownership.
  • Explains centralized SOA characteristicsMentions shared enterprise services, stronger central governance, or an integration platform such as an ESB.
  • Makes a contextual choiceAvoids declaring one style universally better and connects the choice to organizational, operational, and legacy constraints.

A new integration domain contains booking, payment, and customer-notification workflows. How would you decide the service boundaries?

Answer

  • Starts from business capabilitiesUses business responsibilities and ownership rather than controllers, tables, or technical layers.
  • Considers data and consistencyDiscusses which service owns each data set and where strong transactions are truly required.
  • Tests boundaries against changeUses coupling, deployment, failure isolation, and expected change patterns to validate the proposed split.

solid_layers2 questions

Give a concrete example of using SOLID principles in an API service. Focus on responsibility and dependency direction rather than reciting the acronym.

Answer

  • Starts from a concrete change problemDescribes code with mixed responsibilities, volatile dependencies, or difficult substitution and testing.
  • Applies SRP or dependency inversion correctlySeparates cohesive policy from infrastructure and makes high-level logic depend on an inward-owned abstraction.
  • Preserves behavioral contractsMentions focused interfaces and substitutability rather than merely adding interfaces.
  • Avoids over-engineeringExplains when an abstraction is unnecessary and keeps the solution proportional to expected change.

A base class PaymentProcessor promises that Process either succeeds or returns a business rejection, but one subclass throws NotSupportedException for valid card payments. What is wrong with this design?

Answer

  • Identifies the broken behavioral contractExplains that callers cannot safely use the subtype wherever the base abstraction is expected.
  • Explains strengthened preconditionsShows that the subtype accepts fewer valid inputs than promised by the base contract.
  • Proposes a clearer abstractionSuggests capability-specific interfaces, composition, separate strategies, or a contract that explicitly models unsupported methods.
  • Uses contract testsTests every implementation against the shared behavior expected by callers.

SQL and relational database fundamentals42 questions

A query lists recent shipments with customer names and is becoming slow. How would you investigate it?

Answer

  • Chooses the join intentionallyDistinguishes inner and left joins based on whether missing related rows should remain.
  • Inspects the execution planUses EXPLAIN or an equivalent plan to find scans, join cost, and row estimates.
  • Designs for the access patternIndexes filter, join, and ordering columns in a useful order and recognizes write cost.

Two workers may update the same shipment status at the same time. What can go wrong, and how can the database help?

Answer

  • Identifies concurrency anomaliesMentions lost updates, stale reads, duplicate transitions, or invalid ordering.
  • Uses concurrency controlSuggests optimistic version checks, row locks, constraints, or suitable isolation.
  • Keeps the transaction focusedAvoids long external calls and includes only related atomic changes.

SQL data modelling and query performance41 question

A GET /shipments endpoint becomes slow as data grows. Walk through how you would determine whether the problem is the SQL query, the application, or the payload.

Answer

  • Breaks down the latencyUses endpoint traces or timings to separate database time, application processing, serialization, network, and frontend rendering.
  • Inspects SQL execution and access patternsChecks the execution plan, filters, joins, sorting, row counts, indexes, and N+1 behavior.
  • Applies and verifies a focused fixChooses pagination, a matching index, query rewrite, projection, batching, caching, or payload reduction based on evidence.

SQL Execution Plans and Query Optimization42 questions

What do you look for first when analyzing a slow query with an execution plan?

Answer

  • Uses actual runtime metricsLooks at actual time, rows, loops, buffers or I/O, and the operations responsible for most work.
  • Compares estimates with realityFinds large differences between estimated and actual rows that can cause a poor join or access strategy.
  • Interprets physical operationsExamines scans, index access, join algorithms, sorts, spills, and repeated inner operations in context.

A parameterized query is fast for most customers but extremely slow for a few large customers. How would you investigate?

Answer

  • Compares parameter casesCaptures slow and fast parameter values, row distributions, result sizes, and their actual execution plans.
  • Recognizes plan sensitivityConsiders data skew, cached or generic plans, bind peeking, stale statistics, and selectivity differences.
  • Chooses a robust fixEvaluates statistics, query rewrite, indexes, plan controls, partitioning, or separate paths and tests all major parameter groups.

SQL Joins and Aggregation52 questions

Explain INNER JOIN and LEFT JOIN, including a common way a LEFT JOIN is accidentally turned into an INNER JOIN.

Answer

  • Explains join semanticsStates that INNER JOIN keeps matched pairs while LEFT JOIN preserves every left row and uses nulls for missing right rows.
  • Separates ON and WHERE rolesRecognizes that a right-table predicate in WHERE rejects null-extended rows, while placing the condition in ON preserves unmatched left rows.
  • Checks cardinalityMentions one-to-one, one-to-many, or many-to-many relationships and their effect on result row counts.

A report joins flights to bookings and baggage items. Counts and total weight are too high. How would you diagnose and correct the query?

Answer

  • Defines output grainStates what one result row should mean and checks row counts after each join.
  • Finds fan-outRecognizes that two independent one-to-many joins create a cross multiplication within each parent.
  • Uses correct aggregation strategyPre-aggregates each child table, uses correlated aggregates, or otherwise aggregates before combining branches rather than hiding the issue with DISTINCT.

SQL query performance42 questions

A shipment-list endpoint became slow after the table grew from thousands to millions of rows. How would you investigate and improve it?

Answer

  • Measures the real workloadCaptures endpoint traces, query timings, query counts, parameters, and representative data volume.
  • Uses the execution planLooks for full scans, poor row estimates, expensive sorts or joins, and missing or unused indexes.
  • Improves the access pattern and verifies itConsiders selective composite indexes, keyset pagination, smaller projections, N+1 removal, and before-after load testing.

A frequent query filters by customer_id and status, then sorts by created_at descending. How would you reason about a composite index and its trade-offs?

Answer

  • Matches the index to the access patternConsiders equality predicates first and whether the index order can support the requested sorting.
  • Considers selectivity and data distributionDoes not assume a status-only index is useful when most rows share the same status.
  • Explains index costs and verifies the planMentions additional storage, slower writes, maintenance, and confirms the actual plan and latency after the change.

SQL Query Performance42 questions

A dashboard is fast for small schools but takes eight seconds for large ones. Walk through how you would diagnose the database and application path.

Answer

  • Measures the complete requestReproduces with representative data and uses tracing or timing to separate frontend, network, API and database cost.
  • Inspects query behaviorChecks execution plans, actual row counts, scans, joins, sorts and whether an N+1 pattern multiplies calls.
  • Chooses and verifies a targeted fixConsiders batching, pagination, query rewrite or a matching index, then compares latency and write cost after the change.

A submissions endpoint must support stable browsing while new rows are continuously inserted. Compare offset and cursor pagination and choose one.

Answer

  • Explains offset trade-offsNotes that offset is simple and supports page numbers but can scan or skip many rows and shift under concurrent inserts.
  • Explains cursor paginationUses a stable ordered key and a cursor condition to continue after the last seen item efficiently.
  • Defines a deterministic contractChooses cursor pagination for the live list, adds a unique tiebreaker and treats the cursor as opaque.

SQL Query Performance and Indexes52 questions

A list endpoint becomes slow only for a few tenants with large data sets. How would you investigate the query and decide whether an index is the right fix?

Answer

  • Captures the real slow caseCollects the exact query, parameters, tenant data size, frequency, and timing breakdown.
  • Reads the execution planChecks actual rows, estimates, scans, joins, sorts, and whether a candidate index matches the predicates and ordering.
  • Measures the full trade-offTests the index with realistic data and also measures write cost, storage, and other affected queries.

An endpoint issues hundreds of short queries and times out under load. How would you separate database execution time from an N+1 problem and connection-pool waiting?

Answer

  • Traces query count and timingUses request traces to count queries and split connection wait, database execution, and application time.
  • Recognizes N+1 accessLooks for one parent query followed by repeated per-row queries and replaces it with a join, batch, or prefetch.
  • Treats the pool as capacity controlAvoids blindly increasing the pool and instead aligns concurrency with database capacity after fixing excess queries.

sql_performance1 question

A query filtering by customer, status, and deadline and sorting by deadline becomes slow at scale. How would you diagnose and index it?

Answer

  • Starts with the execution plan and measurementsChecks actual plan, rows, scans, estimates, waits, duration, and representative production parameters.
  • Designs the index for the access patternConsiders equality filters, range or sort columns, selectivity, key order, and included columns.
  • Accounts for index costMentions write overhead, storage, maintenance, duplicate indexes, and changing workloads.
  • Verifies instead of assumingRe-runs the plan and load test, watches production metrics, and checks regressions for other queries.

sql_vs_nosql1 question

For a new data exchange component, how would you decide between a relational database and a NoSQL store?

Answer

  • Starts from data and access patternsExamines relationships, query shapes, update patterns, volume, and schema variability before naming a product.
  • Explains relational strengthsUses SQL for joins, transactions, constraints, flexible querying, and strong integrity where these matter.
  • Explains NoSQL strengths and limitsConnects a particular NoSQL model to predictable key access, scale, flexible documents, or high write volume and notes trade-offs.
  • Includes operational and team factorsConsiders managed support, backup, observability, migration, expertise, cost, and failure modes.

SSR vs CSR53 questions

You are choosing an architecture for a public storefront and an authenticated internal CRM. Where would you use CSR, SSR, or static generation, and does choosing Next.js automatically improve SEO?

Answer

  • Starts from product requirementsUses public discoverability, first content, personalization, update frequency, and operational constraints to choose a rendering model.
  • Explains rendering optionsCorrectly distinguishes CSR, request-time SSR, and build-time static generation, including hydration where needed.
  • Rejects framework-as-SEO guaranteeExplains that Next.js enables rendering strategies but SEO also depends on rendered content, crawlability, metadata, performance, and site quality.
  • Accounts for complexityMentions server cost, caching, hydration mismatches, browser-only APIs, and deployment complexity as trade-offs.

What is the primary advantage of server-side rendering, and in which applications might that advantage not justify the added complexity?

Answer

  • States the initial HTML advantageExplains that useful content can arrive as HTML before the client application finishes loading and running.
  • Connects it to users and crawlersRelates the advantage to first content, constrained devices or networks, link previews, and search-engine discovery.
  • Names cases with limited benefitRecognizes that authenticated internal tools or highly interactive applications may gain little from SSR relative to its cost.

Does a plain React application or a Next.js application have an inherent search-ranking advantage? Explain what actually determines whether a page is discoverable and indexable.

Answer

  • Rejects an inherent ranking bonusExplains that search engines do not rank a site higher merely because it uses Next.js or lower merely because it uses React.
  • Explains rendering and crawlabilityCovers whether meaningful HTML, links, metadata, status codes, and canonical URLs are available to crawlers.
  • Includes performance and content qualityMentions user-centric performance, mobile usability, structured data where relevant, and useful unique content.

Student Data Privacy31 question

An LLM provider can generate feedback, but the current payload includes the student’s name, school, history and full profile. How would you redesign the data flow?

Answer

  • Minimizes data to the taskSends only the answer and necessary assignment context, excluding names, full history and unrelated profile fields.
  • Uses privacy-preserving identifiers and contractsReplaces internal identifiers, reviews provider retention and training use, data location, access and contractual safeguards.
  • Defines lifecycle and accountabilitySets temporary retention, auditability, deletion behavior and a clear user or teacher review path.

TanStack Query and Server State42 questions

When would you use TanStack Query instead of Redux Toolkit or local state, and what problems does it solve beyond calling fetch?

Answer

  • Identifies server stateUses TanStack Query for remote data with independent ownership, freshness, latency, and possible concurrent changes.
  • Explains lifecycle featuresCovers caching, deduplication, retries, cancellation, stale handling, background refetch, and mutation coordination.
  • Keeps client state separateUses local state for ephemeral UI and Redux or Context only for genuinely shared client-owned state.
  • Avoids duplicate ownershipDoes not copy query results into another store unless a deliberate snapshot or transformation requires it.

A user edits a customer, but different CRM screens continue showing stale data. How would you design the mutation and cache update strategy?

Answer

  • Maps affected query keysIdentifies every cache view derived from the changed customer, including detail, lists, counts, and dependent summaries.
  • Chooses update or invalidation deliberatelyDirectly updates cache when the authoritative result is known and invalidates narrowly when refetching is safer.
  • Handles optimistic failureSnapshots previous data, applies a reversible optimistic change, rolls back on failure, and reconciles with the server result.
  • Prevents race-related stale writesCancels obsolete fetches or ensures an older response cannot overwrite the newer mutation result.

TanStack Router32 questions

How would you migrate a mature React SPA from its current router to TanStack Router while preserving public URLs, permissions, analytics, and browser behavior?

Answer

  • Inventories routing behaviorMaps route hierarchy, layouts, redirects, params, search state, loaders, guards, analytics, and scroll behavior.
  • Preserves external contractsKeeps public URLs and deep links stable or defines explicit redirects and compatibility rules.
  • Migrates by route branchRuns old and new routing behind a clear boundary and moves one independently testable branch at a time.
  • Tests browser and permission flowsCovers direct load, refresh, back or forward, invalid params, denied access, analytics, and error boundaries.

What value does typed routing provide, and how would you model path parameters and search parameters without treating every value in the URL as trusted?

Answer

  • Explains compile-time navigation safetyShows how typed route names, parameters, and search values reduce broken links and refactoring mistakes.
  • Validates at runtimeRecognizes that URLs are external input and validates, parses, defaults, or rejects path and search values at the boundary.
  • Uses URL state appropriatelyKeeps shareable, bookmarkable navigation state in the URL while excluding secrets and unsuitable ephemeral details.
  • Plans compatibilityConsiders old bookmarked URLs, defaults for missing values, canonical forms, and redirect behavior during schema evolution.

Technical Leadership42 questions

Two senior developers strongly disagree about introducing a message broker. As the architect or technical lead, how would you reach and communicate a decision?

Answer

  • Frames the decision with requirementsClarifies the problem, NFRs, constraints, decision deadline, and what success means before debating technology.
  • Compares options with evidenceDocuments alternatives, trade-offs, risks, operational cost, and uses a spike or data where uncertainty is material.
  • Creates a fair decision processInvites relevant builders and operators, names a decision owner, prevents endless consensus seeking, and records dissent.
  • Communicates and revisits the decisionWrites the rationale, consequences, rollout, review date, and signals that would trigger reconsideration.

How would you improve architecture and code quality across a team without becoming the reviewer and decision bottleneck?

Answer

  • Creates risk-based shared standardsDefines a small set of examples, design principles, review checklists, and quality gates tied to real failure modes.
  • Automates repeatable checksUses formatting, static analysis, tests, security scans, templates, and CI policies so humans focus on judgment.
  • Builds distributed ownershipUses pairing, rotating reviewers, design-review facilitation, and progressively delegates decisions.
  • Measures outcomes and adaptsTracks defects, lead time, incidents, review quality, and team feedback rather than counting rules or meetings.

Testing Strategy42 questions

For the assignment creation feature, what would you test at unit, integration and end-to-end level, and why?

Answer

  • Uses unit tests for focused logicTests pure validation, permission helpers and transformations quickly with controlled inputs.
  • Uses integration tests at real boundariesTests the endpoint with real routing, validation and database behavior, including transaction and constraint failures.
  • Keeps end-to-end tests focusedCovers one critical teacher journey through the browser while avoiding exhaustive duplication of lower-level cases.

An end-to-end test sometimes fails because the Save button is not enabled quickly enough. What would you investigate instead of adding a longer sleep?

Answer

  • Waits for a real conditionWaits for an observable UI or network state rather than a fixed time delay.
  • Finds the underlying raceChecks asynchronous validation, state updates, debouncing, missing awaits and backend response timing.
  • Makes failures diagnosableUses deterministic fixtures and captures logs, network traces or screenshots when the assertion fails.

testing_strategy1 question

What is TDD, and how would you create a test strategy for a .NET microservice platform without relying mainly on end-to-end tests?

Answer

  • Explains red-green-refactorWrites a failing behavior test, implements the smallest change, and improves the design while keeping tests green.
  • Matches test type to riskUses unit tests for domain rules, integration tests for infrastructure, contract tests for service interfaces, and few E2E flows.
  • Avoids meaningless mocksUses real database or broker integration where their behavior matters and keeps mocks at controlled external boundaries.
  • Covers quality beyond test countIncludes deterministic tests, maintainability, failure diagnosis, CI speed, production monitoring, and safe rollout.

Third-party Integration Design52 questions

How would you integrate an external service whose API and availability you do not control?

Answer

  • Creates an isolation boundaryUses an adapter or anti-corruption layer so vendor models and behavior do not spread through the application.
  • Defines failure behaviorUses explicit timeouts, selective retries, circuit breaking, fallback, and idempotency where appropriate.
  • Plans testing and observabilityMentions contract tests or stubs, secure secret handling, provider-specific metrics, logging, and tracing.

A third-party service has intermittent latency spikes and occasional malformed responses. How would you diagnose and contain the issue?

Answer

  • Collects provider-specific evidenceUses dependency latency, status or error categories, traces, correlation IDs, and payload validation failures to isolate the external call.
  • Contains the blast radiusApplies strict timeouts, bounded concurrency, circuit breaking, queueing, or degradation so the provider cannot exhaust the service.
  • Handles malformed data safelyValidates at the boundary, rejects or quarantines invalid payloads, and avoids silently accepting partial or corrupt data.

Transactions and Isolation Levels52 questions

What does a database transaction guarantee, and what does the isolation level add to those guarantees?

Answer

  • Explains transaction atomicityStates that the database changes inside a successful transaction commit together and a rollback removes the uncommitted group.
  • Explains isolationDescribes visibility and conflicts between concurrent transactions, including anomalies such as non-repeatable reads, phantoms, or write conflicts.
  • Explains trade-offsRecognizes that stronger isolation can increase blocking, aborts, contention, and the need for retries.

Two requests attempt to reserve the last available seat at the same time. Design the database operation that prevents double booking.

Answer

  • States the invariantDefines a database-enforceable rule such as capacity not becoming negative or one active reservation per seat.
  • Uses an atomic concurrency controlUses row locking, a conditional UPDATE, optimistic version check, or a unique constraint inside a transaction.
  • Handles the losing requestChecks affected rows or constraint errors, returns a clear conflict, and safely retries only appropriate transient database failures.

Translating business needs into technical design53 questions

A stakeholder says: “We need faster pricing.” What questions would you ask before proposing a technical solution?

Answer

  • Clarifies what faster meansDistinguishes UI response time, end-to-end processing time, throughput and time to business decision.
  • Walks through actors and exceptionsAsks who uses it, current steps, data sources, cut-offs, manual work and important exceptional cases.
  • Defines a measurable targetRequests a baseline, target percentile or throughput and the business metric expected to improve.

How would you discover edge cases for a shipment booking or pricing workflow without trying to predict every possible exception alone?

Answer

  • Uses concrete scenario walkthroughsWalks through real recent cases, including delayed, missing, duplicate and conflicting information.
  • Collaborates with domain and operations peopleInvolves users, support and operational experts and inspects incident or exception history.
  • Prioritizes by risk and frequencyTurns important cases into acceptance criteria and defers extremely rare low-impact behavior deliberately.

A requested solution appears expensive and does not address the stated business outcome. How would you challenge it without blocking progress?

Answer

  • Starts from the shared outcomeConfirms the desired result and constraints instead of attacking the stakeholder suggestion.
  • Explains cost and risk concretelyUses delivery effort, operational burden, dependency or data evidence rather than vague technical preference.
  • Offers a smaller testable alternativeProposes a thin solution or experiment that tests the assumption and preserves momentum.

TypeScript and Runtime Validation42 questions

Why is a TypeScript interface insufficient for validating a third-party API response, and what would you do instead?

Answer

  • Explains type erasureStates that interfaces and most types disappear at runtime and cannot inspect incoming JSON.
  • Uses runtime validationTreats input as unknown and validates with an explicit schema, parser, guards, or equivalent executable checks.
  • Separates external and internal modelsMaps the validated provider representation into an internal type and returns controlled errors for invalid data.

A provider changes a nullable field into several possible shapes without notice. How should a TypeScript integration react?

Answer

  • Fails at the boundaryDetects the mismatch before business logic and produces a typed, categorized integration error rather than undefined behavior.
  • Uses an explicit compatibility policySupports multiple known shapes through a versioned or union parser only when semantics are understood, without accepting arbitrary data.
  • Makes provider drift visibleRecords safe samples or fingerprints, metrics and alerts by provider or schema version, and coordinates a contract fix.

TypeScript at runtime boundaries52 questions

A TypeScript frontend calls a REST endpoint. How would you model the response and make sure the runtime data is actually safe to use?

Answer

  • Separates compile-time types from runtime dataExplains that an interface or cast cannot validate a network response at runtime.
  • Parses unknown input at the boundaryTreats external data as unknown and validates it with a schema, parser, or explicit type guard.
  • Keeps the internal model preciseMaps validated transport data to a stable domain type and handles optional or new variants deliberately.

An untyped package returns any and that value is spreading through the application. How would you contain the risk without rewriting the package?

Answer

  • Wraps the unsafe dependencyCreates one adapter or declaration boundary instead of allowing any to leak through the codebase.
  • Converts uncertainty to unknown and narrows itUses runtime checks, guards, or a schema before exposing a typed result.
  • Keeps the solution pragmaticTypes the used surface first, tests the adapter, and avoids pretending to fully model undocumented behavior.

TypeScript at runtime boundaries52 questions

An HTTP client returns JSON from a third-party logistics API. How would you type and validate that response, and why is casting it with as ShipmentResponse not enough?

Answer

  • Separates compile-time types from runtime dataExplains that TypeScript annotations disappear at runtime and cannot guarantee an external payload.
  • Uses unknown and runtime validationReceives the value as unknown and validates required fields with a schema or type guard.
  • Maps transport data to a domain modelKeeps integration details at the boundary and returns a stable internal representation or a controlled validation error.

A React screen can be idle, loading, successful, or failed. How would you model these states in TypeScript so impossible combinations are difficult to create?

Answer

  • Uses a discriminated unionModels each valid state as a separate variant selected by a shared status field.
  • Prevents impossible combinationsAvoids combinations such as isLoading true while both data and error are present.
  • Handles variants exhaustivelyUses narrowing and an exhaustive switch so a new variant creates a compiler-visible gap.

TypeScript at Runtime Boundaries52 questions

An HTTP client is declared to return StudentProfile, but the external service sometimes omits a required field. Why does TypeScript not protect you, and how would you handle the boundary?

Answer

  • States the compile-time limitationExplains that TypeScript types are erased and a declared return type does not inspect the actual JSON at runtime.
  • Treats external data as unknownUses unknown or an untrusted transport type instead of asserting that the response already matches the domain type.
  • Validates and narrows the valueParses required fields and allowed values, then returns a validated typed object or a controlled error.

A UI has loading, success and error states, but optional fields allow impossible combinations such as loading=true with data and error. How would you redesign the type?

Answer

  • Uses a discriminated unionModels each valid state as a separate union member selected by a status or kind field.
  • Keeps payloads state-specificPlaces data only on the success variant and error details only on the failure variant.
  • Handles variants exhaustivelyUses narrowing and an exhaustive switch so a new state produces a compile-time reminder.

TypeScript Generics and Contracts43 questions

What problem do generics solve in TypeScript, and how do you know whether a generic is useful rather than unnecessary complexity?

Answer

  • Explains type relationshipsExplains that generics preserve a relationship between inputs and outputs or between multiple values.
  • Explains constraints and inferenceMentions constraints when behavior requires properties and inference when callers should not need explicit type arguments.
  • Recognizes overuseSays a generic is weak when the parameter appears only once, adds no safety, or hides a simpler concrete design.

You need one reusable TypeScript API client for several endpoints with different response shapes. How would you design it without pretending that network data is already safe?

Answer

  • Preserves endpoint result typesUses a generic result type or endpoint definition so each call returns the correct application type.
  • Combines generics with validationRequires a parser or schema so the generic type is backed by runtime validation.
  • Models failure separatelyKeeps transport, HTTP, validation, and domain errors explicit rather than throwing an untyped value everywhere.

Should a React frontend and Node.js backend share TypeScript types directly? Discuss the benefits, risks, and a practical compromise.

Answer

  • Explains the benefitMentions reduced duplication and faster detection of contract changes.
  • Explains coupling and false safetyRecognizes deployment independence, versioning, and the fact that shared compile-time types do not validate network traffic.
  • Proposes a safe compromiseSuggests shared schemas or generated clients from an API specification plus runtime validation.

TypeScript Runtime Boundaries53 questions

What is the difference between TypeScript type checking and runtime validation, and where would you use each?

Answer

  • Explains static type checkingExplains that TypeScript checks source code before runtime and does not validate network data by itself.
  • Identifies runtime boundariesNames API responses, user input, files, environment variables, or messages as places that require runtime validation.
  • Uses safe narrowingPrefers unknown plus validation or type guards over any or unchecked assertions.

A React screen receives an API response that TypeScript describes as Shipment[], but production data sometimes contains invalid records. How would you make this path safe?

Answer

  • Validates at the boundaryValidates the response before business logic or rendering uses it.
  • Handles validation failure explicitlyReturns a typed error, logs useful context, and presents a controlled UI state.
  • Improves the contractMentions contract tests, shared schemas, or monitoring to prevent repeated mismatches.

When would you choose unknown, any, or a type assertion in TypeScript? Give an example where the wrong choice could hide a bug.

Answer

  • Chooses unknown for uncertain valuesExplains that unknown preserves safety because the caller must narrow or validate it.
  • Explains the risk of anyExplains that any removes checking and spreads unsafety through later code.
  • Limits assertions to proven casesUses assertions only when runtime facts are already guaranteed by another mechanism or the compiler cannot infer them.

TypeScript type system53 questions

How would you model a shipment status that has a fixed set of values and may gain new values later? Explain how you would make missing handling visible.

Answer

  • Uses a finite domain typeUses a string-literal union or equivalent finite type instead of an unrestricted string.
  • Makes handling exhaustiveAn exhaustive switch or never check reveals an unhandled new status.
  • Separates runtime validationNotes that external status values must still be validated at runtime.

What is the practical difference between any and unknown in TypeScript, and where would you use unknown in a full-stack application?

Answer

  • Explains any as an escape hatchany disables useful type checking and lets unsafe operations spread.
  • Explains unknown as safe uncertaintyunknown requires checking or parsing before properties or methods can be used.
  • Gives a system-boundary use caseUses unknown for parsed JSON, request bodies, caught errors or third-party responses.

Would you share TypeScript types directly between a React frontend and Node.js backend? Describe the benefits, risks and a practical approach.

Answer

  • Identifies consistency benefitsShared or generated types reduce duplication and catch client-server drift early.
  • Recognizes false safety and couplingCompile-time sharing does not validate runtime data and can couple internal backend models to public contracts.
  • Proposes a contract-first boundaryUses an API schema or dedicated contract package and generates or validates both sides.

typescript_essentials1 question

How does TypeScript improve a large React codebase, and which important classes of runtime problems can it still not prevent?

Answer

  • Explains compile-time contractsDescribes types as executable feedback for component props, function inputs, state shapes, and refactoring across module boundaries.
  • Uses narrowing and domain modelingMentions unions, discriminated states, generics, unknown, and exhaustiveness to model valid application states.
  • States the runtime boundaryExplains that external JSON, storage, user input, permissions, and server behavior require runtime validation and tests.
  • Avoids false safetyWarns that any, unsafe assertions, incorrect declarations, and logically wrong code can all compile.

Vanilla Extract Styling22 questions

What benefits and trade-offs does Vanilla Extract bring compared with runtime CSS-in-JS, CSS Modules, or plain stylesheets?

Answer

  • Explains static extractionDescribes type-safe definitions and composition that produce static CSS without a client-side style-generation runtime.
  • Describes design-system strengthsConnects theme variables, tokens, recipes, typed variants, and shared package integration to consistent component styling.
  • Names build and dynamic-style costsMentions tool integration, generated class debugging, restrictions on runtime-dependent values, and possible variant complexity.
  • Chooses by contextCompares team skills, SSR or runtime cost, theming needs, existing code, and migration cost rather than declaring a universal winner.

How would you organize tokens, themes, component styles, and product-specific overrides across a shared library, a storefront, and a CRM?

Answer

  • Creates explicit style layersSeparates foundation tokens, semantic theme values, component styles, utilities, and product-specific composition.
  • Controls override mechanismsUses supported variants, class composition, CSS variables, and limited escape hatches rather than specificity battles.
  • Prevents product leakageKeeps storefront or CRM business styling out of shared primitives and avoids circular dependencies between packages.
  • Supports evolution and themesVersions token changes, tests representative consumers, and plans dark mode, brand themes, or deprecations without global breakage.

Visual Regression Testing32 questions

What roles do Storybook and Chromatic play in a shared component library, and what should a high-quality component story contain?

Answer

  • Explains Storybook's roleDescribes isolated development, documentation, state cataloging, interaction examples, and a review surface for designers and developers.
  • Explains Chromatic's roleDescribes hosted story builds, screenshot comparison, change review, and approved visual baselines.
  • Includes representative statesCovers default, disabled, loading, error, focus, overflow, localization, responsive, and theme variations where relevant.
  • Keeps stories deterministicControls data, time, animation, fonts, and network behavior so visual and interaction checks remain stable.

Chromatic reports many visual changes on every run even when developers did not modify the UI. How would you diagnose and reduce the noise?

Answer

  • Finds nondeterministic inputsChecks random data, current time, animation, asynchronous fonts, network content, generated IDs, and unstable layout measurement.
  • Stabilizes the environmentPins browser and viewport settings, mocks data, waits for readiness, disables motion, and loads exact fonts before capture.
  • Uses focused thresholds and storiesAvoids one huge page screenshot, chooses meaningful component states, and adjusts thresholds only after understanding the difference.
  • Repairs review disciplineTracks flaky stories, makes noise visible, and prevents habitual approve-all behavior from destroying the gate's value.

Web Accessibility41 question

Review a quiz form that uses placeholder-only labels, clickable divs, color-only errors and automatic focus jumps. What would you change?

Answer

  • Uses semantic controls and labelsReplaces clickable divs with buttons or inputs and connects persistent labels to form controls.
  • Preserves keyboard and focus behaviorEnsures logical tab order, visible focus and intentional focus movement only when it helps recovery.
  • Communicates errors accessiblyUses text plus visual cues, links errors to fields and announces updates appropriately to assistive technology.

Web application and API security boundaries41 question

A logistics platform is multi-tenant. How would you prevent a user from reading or modifying another customer’s shipments, even if they manipulate the frontend request?

Answer

  • Separates authentication from authorizationValidates the identity, then checks whether that identity may perform the action on the specific resource.
  • Derives tenant scope from trusted identityDoes not trust a tenant id supplied by the browser; scopes queries by claims or server-side membership.
  • Adds layered controls and auditabilityUses parameterized queries, least privilege, safe error responses, tests for horizontal privilege escalation, and audit logs.

Web Security Basics42 questions

A teacher can change the class id in the URL and view another school’s class. The user is authenticated. What failed, and how should the backend prevent it?

Answer

  • Distinguishes authentication and authorizationExplains that knowing the user identity does not prove permission to access the requested class.
  • Checks authorization on the serverLoads or scopes the resource through the user’s school and role, denying access regardless of UI visibility.
  • Adds systematic protectionUses centralized policy or query scoping, audit logs and negative authorization tests for cross-tenant ids.

Students can enter rich text that teachers later view, and the backend stores it in PostgreSQL. What controls would you use against XSS and SQL injection?

Answer

  • Uses parameterized database accessUses query parameters or a safe ORM instead of concatenating user input into SQL.
  • Renders untrusted content safelyEscapes text by default and, if rich HTML is required, sanitizes with a strict allowlist before rendering.
  • Adds supporting browser and validation controlsValidates size and format, applies Content Security Policy and avoids relying on input filtering as the only defense.