Senior Software Engineer interview questions & answers

20 Senior Software Engineer interview questions with complete model answers, spanning Technical, Coding, System design, Behavioral. The bank holds 27 Senior Software Engineer questions in total, tagged by round and difficulty.

BehavioralMediumSenior Software EngineerBehavioral interview

1. How have you adapted to unexpected changes, such as a last-minute requirement change or having to learn something quickly?

Model answer

  1. Situation — On a project to improve an internal workflow, a partner team changed a requirement late in the schedule: an operation that had been assumed to be synchronous now needed to handle much longer-running work and provide progress to users. The change mattered because the existing design would have held requests open and failed under realistic workloads. I had not previously built a production workflow around that team's eventing platform.
  2. Task — I needed to understand the new requirement and the platform quickly, then help the team choose a design that met the user need without putting the delivery date or service reliability at risk.
  3. Action
  • I first clarified what had actually changed: expected job duration, whether users needed live progress or just completion status, and what behavior they expected after a retry or disconnect.
  • I read the platform's operational guidance and existing service examples, then built a small end-to-end prototype to verify delivery, retry, and failure semantics rather than relying on assumptions.
  • I compared keeping the synchronous path with an asynchronous job model. I recommended returning a job identifier immediately and exposing status, because it handled long-running work and made client timeouts harmless.
  • I wrote down the trade-offs and walked them through with the partner team and product owner. To preserve the date, we agreed to launch with clear queued/running/completed states and defer finer-grained progress updates.
  • I added idempotency and failure-path tests, and worked with the team to instrument queue age and completion time so we could detect a backlog after launch.
  1. Result — We delivered the revised workflow without blocking requests for the duration of the work, and the team had a measurable way to monitor it. I learned that adapting quickly does not mean coding faster before the problem is clear. A short period spent clarifying the user contract and validating unfamiliar technology can prevent a much larger redesign. Since then, I use small prototypes to answer the riskiest technical questions early.
BehavioralMediumSenior Software EngineerBehavioral interview

2. What problems have you had at work, how did you solve them, and what did you learn?

Model answer

  1. Situation — A recurring problem on a service I worked on was that a small number of slow downstream calls could cause request timeouts across the whole service. The issue was difficult to diagnose because each team could see its own component, but no one had a complete view of the request path. It affected customer-facing reliability and consumed time from several engineering teams.
  2. Task — I took ownership of narrowing down the failure mode and coordinating a fix that improved resilience without hiding genuine downstream failures or adding unnecessary latency to healthy requests.
  3. Action
  • I assembled a timeline from traces, service metrics, and incident reports, then showed that the timeouts clustered around a particular dependency during traffic spikes.
  • I worked with that dependency's team to validate the hypothesis and agree on a shared set of latency and error signals. This helped us replace debate about whose service was at fault with evidence about where time was being spent.
  • I proposed bounded timeouts, limited retries with jitter, and a circuit breaker. I was careful not to add retries indiscriminately, because retrying overload can amplify it.
  • I tested the behavior with injected latency and failures, including cases where only a subset of calls failed. We also documented how to distinguish a dependency outage from a regression in our own service.
  • I shared the rollout plan with the partner team, released the changes gradually, and watched both customer-facing success rates and downstream load.
  1. Result — The service became more predictable during dependency slowdowns, and the teams had clearer signals for investigating future incidents. The main lesson I took away was that cross-service reliability is a shared responsibility: local fixes work best when teams agree on observable contracts and failure behavior. I now look for ways to make the system easier to diagnose as well as harder to break.
BehavioralMediumSenior Software EngineerBehavioral interview

3. When was the last time you messed up at work?

Model answer

  1. Situation — The last significant mistake I made was during a service deployment last year. I was responsible for a change to a backend API used by several client teams. I tested the new behavior, but I missed that one client still depended on a legacy response field that my change removed.
  2. Task — Once the change reached production, I needed to restore compatibility quickly, limit customer impact, and make sure the fix addressed the cause rather than just the symptom.
  3. Action
  • I checked the deployment and request metrics, confirmed the failures were concentrated among older client versions, and told the incident lead what I knew instead of speculating.
  • I coordinated a rollback while another engineer prepared a backward-compatible patch. We restored the field and kept the new behavior additive, so clients could migrate on their own schedule.
  • I made sure support and the affected client teams had a clear status update and workaround, rather than letting them discover the issue through repeated failures.
  • After recovery, I reviewed why our tests had missed the dependency. Our contract tests covered the latest client but not supported older versions, and the API review checklist did not make compatibility explicit.
  • I added versioned contract tests and a staged rollout check that compares error rates by client version. I also documented the migration and deprecation expectations for future API changes.
  1. Result — We restored the affected requests within the incident window and avoided repeating the same compatibility gap in later releases. I learned that a change can be correct for the newest client and still be a bad service change if it breaks supported consumers. Since then, I treat compatibility as part of the feature definition, not a final testing detail, and I raise risks early when I am uncertain.
BehavioralMediumSenior Software EngineerChat with the VP

4. What is your role in your current company?

Model answer

  1. Situation — I’m currently a [role] at [company], working on [product or domain] with a team of [team size or partner teams]. My work matters because [customer or business impact] depends on the reliability and usability of what we ship. The role combines hands-on delivery with making sure the team is solving the right problem.
  2. Task — I’m responsible for taking work from [problem discovery or technical design] through implementation, release, and follow-up. I also help the team make good trade-offs among customer needs, delivery timelines, and maintainability.
  3. Action
  • I work with product, design, and other engineers to clarify requirements and identify edge cases before implementation. For example, on [recent project], I helped turn a broad request into a smaller, testable first release.
  • I own the technical approach for my area: I compare options, document important trade-offs, and involve the people who will operate or depend on the system.
  • I contribute directly to the code, tests, and reviews, while keeping quality attributes such as reliability, accessibility, and observability in view.
  • I communicate risks early rather than waiting until a deadline is threatened. When [specific constraint] came up, I proposed [decision or mitigation] and aligned the team on the impact.
  • After release, I look at [usage, support signals, or reliability metrics] and use what we learn to prioritize follow-up work.
  1. Result — That approach helped us deliver [specific outcome], measured by [metric or observable result], while keeping [quality or customer guardrail] intact. More broadly, I see my role as owning outcomes—not just tickets—and helping a cross-functional team make progress with clear decisions and dependable execution.
CodingEasySenior Software Engineer

5. How do you write a basic recursive function, such as one that calculates a factorial?

Model answer

function factorial(n) {
  // Factorial is defined for non-negative integers.
  if (!Number.isInteger(n) || n < 0) {
    throw new RangeError("n must be a non-negative integer");
  }

  // Base case: stop the recursion.
  if (n <= 1) return 1;

  // Recursive case: reduce the problem to a smaller input.
  return n * factorial(n - 1);
}

console.log(factorial(5)); // 120
  • The base case prevents infinite recursion; each recursive call reduces n by one.
  • For large n, an iterative solution avoids recursion-stack limits.

Complexity: Time O(n); space O(n) due to the call stack.

CodingMediumSenior Software EngineerJavaScript Platform & DSA

6. Implement debounce and its variations using promises.

Model answer

function debouncePromise(fn, wait, { leading = false, trailing = true } = {}) {
  if (!leading && !trailing) {
    throw new Error("At least one of leading or trailing must be enabled");
  }

  let timer = null;
  let pending = [];
  let latestThis;
  let latestArgs;
  let lastLeadingPromise;

  function invoke(context, args, waiters = []) {
    const execution = Promise.resolve().then(() => fn.apply(context, args));
    execution.then(
      value => waiters.forEach(waiter => waiter.resolve(value)),
      error => waiters.forEach(waiter => waiter.reject(error))
    );
    return execution;
  }

  function onTimer() {
    timer = null;
    if (pending.length === 0) return Promise.resolve(undefined);

    const batch = pending;
    pending = [];
    return invoke(latestThis, latestArgs, batch);
  }

  function debounced(...args) {
    const context = this;

    if (timer === null && leading) {
      // Invoke the first call immediately, then start the debounce window.
      lastLeadingPromise = invoke(context, args);
      timer = setTimeout(onTimer, wait);
      return lastLeadingPromise;
    }

    if (trailing) {
      latestThis = context;
      latestArgs = args;
      const promise = new Promise((resolve, reject) => {
        pending.push({ resolve, reject });
      });
      clearTimeout(timer);
      timer = setTimeout(onTimer, wait);
      return promise;
    }

    // In leading-only mode, suppressed calls share the first call's result.
    return lastLeadingPromise;
  }

  debounced.cancel = () => {
    clearTimeout(timer);
    timer = null;
    const error = new Error("Debounced call cancelled");
    pending.forEach(waiter => waiter.reject(error));
    pending = [];
  };

  debounced.flush = () => {
    if (timer === null) return Promise.resolve(undefined);
    clearTimeout(timer);
    return onTimer();
  };

  return debounced;
}

// Trailing: only the final call runs after the quiet period.
const search = debouncePromise(query => fetchResults(query), 250);

// Leading + trailing: run immediately, then run once more with the final call
// if additional calls arrive during the debounce window.
const save = debouncePromise(value => persist(value), 500, {
  leading: true,
  trailing: true,
});
  • Each trailing caller gets a promise; callers in the same debounce window receive the result or rejection of the final invocation.
  • leading runs the first call immediately; trailing controls whether later calls are coalesced and run at the end. cancel() rejects queued callers; flush() runs them now.
  • Complexity: O(1) scheduling per call, plus O(k) to settle k coalesced promises; O(k) space for pending callers.
CodingMediumSenior Software EngineerJavaScript Platform & DSA

7. Deep-flatten an object.

Model answer

// Flattens nested objects and arrays into dot-separated paths.
// Arrays use numeric path segments, e.g. "servers.0.name".
function flattenObject(input, separator = ".") {
  const result = Object.create(null);

  function isContainer(value) {
    if (Array.isArray(value)) return true;
    if (value === null || typeof value !== "object") return false;
    const prototype = Object.getPrototypeOf(value);
    return prototype === Object.prototype || prototype === null;
  }

  function visit(value, path) {
    if (!isContainer(value)) {
      // A root primitive has no natural path, so store it under the empty key.
      result[path] = value;
      return;
    }

    const entries = Array.isArray(value)
      ? value.map((item, index) => [String(index), item])
      : Object.entries(value);

    // Preserve empty nested objects and arrays instead of dropping them.
    if (entries.length === 0) {
      if (path !== "") result[path] = value;
      return;
    }

    for (const [key, child] of entries) {
      const childPath = path === "" ? key : `${path}${separator}${key}`;
      visit(child, childPath);
    }
  }

  visit(input, "");
  return result;
}

const input = {
  cluster: { name: "prod", nodes: [{ id: 1 }, { id: 2 }] },
  labels: {},
};
console.log(flattenObject(input));
// { "cluster.name": "prod", "cluster.nodes.0.id": 1,
//   "cluster.nodes.1.id": 2, "labels": {} }
  • I recurse through plain objects and arrays, using array indices as path segments.
  • Empty containers are retained; dates and other non-plain objects are treated as leaf values.
  • Complexity: O(n) time for n visited values; O(n) output space, excluding recursion stack.
CodingHardSenior Software EngineerOnline Assessment

8. Given JSON data from two endpoints containing people’s availability in different countries and the number of events in each country, what JSON woul…

The full question

Given JSON data from two endpoints containing people’s availability in different countries and the number of events in each country, what JSON would you post to an endpoint with event dates chosen to maximize how many people can attend?

Model answer

/**
 * availability: [{ personId, country, availableDates: ["YYYY-MM-DD", ...] }]
 * eventCounts: { [country]: number } OR [{ country, eventCount }]
 *
 * Assumption: each event is in one country on one distinct date. The goal is to
 * maximize the sum of attendees across events; a person attending two events
 * counts once for each event. Dates are compared as ISO date strings.
 */
function buildEventSchedule(availability, eventCounts) {
  const counts = Array.isArray(eventCounts)
    ? Object.fromEntries(eventCounts.map(({ country, eventCount }) => [country, eventCount]))
    : eventCounts;

  // Count distinct people available for each country/date.
  const peopleByCountryAndDate = new Map();
  for (const { personId, country, availableDates = [] } of availability) {
    for (const date of availableDates) {
      const key = `${country}\u0000${date}`;
      if (!peopleByCountryAndDate.has(key)) peopleByCountryAndDate.set(key, new Set());
      peopleByCountryAndDate.get(key).add(personId);
    }
  }

  const candidatesByCountry = new Map();
  for (const [key, people] of peopleByCountryAndDate) {
    const [country, date] = key.split("\u0000");
    if (!candidatesByCountry.has(country)) candidatesByCountry.set(country, []);
    candidatesByCountry.get(country).push({ date, attendeeCount: people.size });
  }

  const events = [];
  for (const [country, requestedCount] of Object.entries(counts)) {
    const candidates = candidatesByCountry.get(country) ?? [];
    // Highest attendance first; use the earlier date to break ties consistently.
    candidates.sort((a, b) => b.attendeeCount - a.attendeeCount || a.date.localeCompare(b.date));

    for (const candidate of candidates.slice(0, Math.max(0, requestedCount))) {
      events.push({ country, date: candidate.date });
    }
  }

  return { events };
}

// Example:
const availability = [
  { personId: "p1", country: "US", availableDates: ["2025-06-10", "2025-06-11"] },
  { personId: "p2", country: "US", availableDates: ["2025-06-10"] },
  { personId: "p3", country: "US", availableDates: ["2025-06-11"] }
];
const eventCounts = { US: 1 };
console.log(JSON.stringify(buildEventSchedule(availability, eventCounts)));
// {"events":[{"country":"US","date":"2025-06-10"}]}
  • I count distinct people per country and date, then choose the highest-attendance dates up to that country’s event count.
  • The tie-break makes the output deterministic. If the business goal is to maximize unique people across all events instead, that is a different maximum-coverage objective and needs an explicit attendee-counting rule.

Complexity: Time O(A + D log D), where A is the number of person-date availabilities and D is the number of country-date candidates; space O(A).

CodingHardSenior Software EngineerLow Level Design Round

9. Implement the complete logic for a snake game.

Model answer

class SnakeGame {
  constructor(rows, cols, options = {}) {
    if (!Number.isInteger(rows) || rows < 1 || !Number.isInteger(cols) || cols < 1) {
      throw new Error("rows and cols must be positive integers");
    }

    this.rows = rows;
    this.cols = cols;
    this.random = options.random ?? Math.random;
    this.initialLength = Math.min(options.initialLength ?? 3, cols);
    if (this.initialLength < 1) throw new Error("initialLength must be positive");
    this.reset();
  }

  reset() {
    const startRow = Math.floor(this.rows / 2);
    const headCol = Math.min(this.cols - 1, this.initialLength - 1);

    // Store the head first; the rest of the body extends left.
    this.snake = Array.from({ length: this.initialLength }, (_, i) => ({
      row: startRow,
      col: headCol - i,
    }));
    this.direction = { row: 0, col: 1 };
    this.pendingDirection = this.direction;
    this.score = 0;
    this.gameOver = false;
    this.won = false;
    this.food = this.spawnFood();
    return this.getState();
  }

  setDirection(name) {
    const directions = {
      up: { row: -1, col: 0 },
      down: { row: 1, col: 0 },
      left: { row: 0, col: -1 },
      right: { row: 0, col: 1 },
    };
    const next = directions[name];
    if (!next || this.gameOver) return false;

    // Compare with the queued direction so two inputs between ticks
    // cannot make the snake reverse into itself.
    const current = this.pendingDirection;
    if (next.row + current.row === 0 && next.col + current.col === 0) return false;
    this.pendingDirection = next;
    return true;
  }

  step() {
    if (this.gameOver) return this.getState();

    this.direction = this.pendingDirection;
    const head = this.snake[0];
    const next = {
      row: head.row + this.direction.row,
      col: head.col + this.direction.col,
    };
    const eating = this.food !== null && next.row === this.food.row && next.col === this.food.col;

    // When not eating, the tail moves away this tick, so it is not a collision.
    const bodyToCheck = eating ? this.snake : this.snake.slice(0, -1);
    const hitsBody = bodyToCheck.some(cell => cell.row === next.row && cell.col === next.col);
    const hitsWall = next.row < 0 || next.row >= this.rows || next.col < 0 || next.col >= this.cols;

    if (hitsWall || hitsBody) {
      this.gameOver = true;
      return this.getState();
    }

    this.snake.unshift(next);
    if (eating) {
      this.score += 1;
      this.food = this.spawnFood();
      if (this.food === null) {
        this.won = true;
        this.gameOver = true;
      }
    } else {
      this.snake.pop();
    }
    return this.getState();
  }

  spawnFood() {
    const occupied = new Set(this.snake.map(cell => `${cell.row},${cell.col}`));
    const empty = [];
    for (let row = 0; row < this.rows; row++) {
      for (let col = 0; col < this.cols; col++) {
        if (!occupied.has(`${row},${col}`)) empty.push({ row, col });
      }
    }
    if (empty.length === 0) return null;
    return empty[Math.floor(this.random() * empty.length)];
  }

  getState() {
    // Return copies so callers cannot mutate the game's internal state.
    return {
      snake: this.snake.map(cell => ({ ...cell })),
      direction: { ...this.direction },
      food: this.food ? { ...this.food } : null,
      score: this.score,
      gameOver: this.gameOver,
      won: this.won,
    };
  }
}

// Example: const game = new SnakeGame(20, 20);
// game.setDirection("up");
// const stateAfterOneTick = game.step();
  • setDirection validates input and prevents a 180-degree turn; step advances one game tick.
  • Food is selected from unoccupied cells. The game ends on a wall/body collision or when the board is full.

Complexity: step is O(L + R·C) with this straightforward food-placement scan, where L is snake length and R·C is board area. State copying is O(L); food placement uses O(R·C) temporary space.

System designMediumSenior Software EngineerKarat Screening Round

10. A system is scaling from x to y users.

The full question

A system is scaling from x to y users. What would you consider upgrading to ensure it scales smoothly?

Model answer

1. Requirements & scale

  • First, I would clarify what x and y mean: registered users, daily active users, concurrent users, or peak request rate. Users alone are a poor capacity metric.
  • I would identify the workload mix, latency and availability targets, data growth, geographic distribution, and whether the system is multi-tenant. I would preserve correctness and security while scaling; for a collaboration product, tenant isolation and permission checks are critical.
  • For an illustrative estimate, assume growth from 1M to 10M daily active users, each making 20 API actions per day. That is about 2,315 average requests/second at 10M DAU; at a 5× peak, plan for roughly 12K RPS. If the average response is 20 KB, peak egress is about 240 MB/s, before cache hits and compression.
  • At 2 KB of new durable data per action, raw growth is about 400 GB/day. Replication, indexes, and history can multiply that several-fold, so I would measure real payloads and retention before choosing storage capacity.

2. High-level architecture

I would scale stateless request handling horizontally, then use load tests and traces to find which stateful dependency needs sharding or optimization. I would avoid scaling every component blindly.

flowchart TD
  subgraph Client
    U[Web and mobile clients]
  end
  subgraph EdgeCDN["Edge / CDN"]
    E[Static assets and API edge]
  end
  subgraph LoadBalancer["Load Balancer"]
    L[Regional load balancer]
  end
  subgraph APIServices["API / Services"]
    A[API gateway]
    S[Stateless collaboration services]
    I[Identity and authorization]
  end
  subgraph Cache
    C[Distributed cache]
  end
  subgraph Datastores
    D[Partitioned relational database]
    O[Object storage]
    X[Search index]
  end
  subgraph MessageQueue["Message Queue"]
    Q[Durable event stream]
  end
  subgraph Workers
    W[Async workers]
  end
  U -->|HTTPS requests| E
  E -->|Dynamic requests| L
  L -->|Route request| A
  A -->|Authenticate and dispatch| I
  A -->|Read and write| S
  S -->|Hot reads| C
  S -->|Transactions| D
  S -->|Upload and download| O
  S -->|Publish domain events| Q
  Q -->|Consume events| W
  W -->|Index and notify| X
  W -->|Update derived data| D
Diagram

3. API design

  • GET /v1/projects/{projectId}/items?cursor=... — paginated, permission-checked reads.
  • POST /v1/projects/{projectId}/items — create an item; accept an idempotency key to make retries safe.
  • PATCH /v1/items/{itemId} — conditional update using a version or ETag to prevent lost writes.
  • GET /v1/operations/{operationId} — inspect long-running asynchronous work.

I would keep APIs versioned, enforce per-tenant quotas, and use cursor pagination rather than expensive offsets.

4. Data model & storage

  • Keep canonical collaboration records and tenant membership in a relational database for transactions, constraints, and permission-sensitive updates. Partition by tenant or tenant-plus-project, with a plan for exceptionally large tenants so one customer cannot become a hot shard.
  • Store attachments in blob storage and keep metadata and access-control references in SQL. Use a search index for text queries, treated as a rebuildable projection rather than a source of truth.
  • Cache frequently read, permission-safe data with bounded TTLs and explicit invalidation. Include tenant and authorization context in cache keys; never let a cache hit bypass access checks.
  • Publish transactional outbox events alongside database commits so downstream indexing and notifications do not miss committed changes.

5. Deep dive

I would start by measuring the current system at representative load: request rate and mix, p50/p95/p99 latency, queue lag, database CPU and I/O, cache hit rate, and error rate. Then I would load-test at the target peak plus headroom, using realistic tenant skew and write contention. If the database is the bottleneck, I would first remove inefficient queries, add appropriate indexes, batch reads, and reduce unnecessary writes. Only then would I introduce partitioning or read replicas, because both add operational and consistency complexity.

For a write-heavy path, I would commit the source-of-truth change and outbox record in one transaction. A worker consumes the event and updates search or sends a notification. Consumers must be idempotent because delivery is at least once; retries use backoff, and poison messages go to a dead-letter queue with alerting.

sequenceDiagram
  participant C as Client
  participant A as API
  participant D as SQL database
  participant Q as Event stream
  participant W as Worker
  participant X as Search index
  C->>A: Create item with idempotency key
  A->>D: Commit item and outbox event
  D-->>A: Return committed version
  A-->>C: 201 Created
  D->>Q: Publish outbox event
  Q->>W: Deliver event
  W->>X: Idempotently update search projection
Diagram

6. Scale, bottlenecks & trade-offs

  • Use autoscaling for stateless services, with capacity limits and graceful overload behavior. Scale on concurrency, latency, and queue depth as well as CPU; CPU alone can miss saturated databases or blocked workers.
  • Add read replicas for suitable read workloads, while routing read-after-write requests to the primary or using version-aware reads. Replicas improve throughput but introduce replication lag.
  • Partition gradually, monitor per-shard load, and maintain a resharding plan. A single hot tenant may require dedicated capacity or finer-grained partitioning.
  • Prefer asynchronous work for non-critical side effects, but keep user-visible writes strongly consistent. Define explicit degradation: for example, accept a valid write while temporarily delaying search indexing, not while skipping authorization.
  • Roll out with canaries, load tests, SLO dashboards, and rollback criteria. The goal is sustainable capacity at the target workload, not simply a larger fleet.
System designMediumSenior Software EngineerKarat Screening Round

11. An electronic system for a smart freezer currently performs processing on an external computer.

The full question

An electronic system for a smart freezer currently performs processing on an external computer. If you migrate that code to an internal microcontroller, such as a Raspberry Pi, what should you consider?

Model answer

1. Requirements & scale

  • I would first clarify what processing moves onto the freezer: sensor filtering, temperature control, alarms, inventory prediction, or all of these. I would identify which functions are safety-critical, what must work without internet, and the acceptable temperature and response-time ranges.
  • I would also clarify the hardware: a Raspberry Pi is a single-board computer running an operating system, not a traditional microcontroller. It offers more memory and easier updates, but Linux is not inherently real-time; I would not make a hard safety guarantee depend on an ordinary userspace process.
  • For an illustrative fleet of 100,000 freezers sending one 1 KB telemetry message per minute, the cloud receives about 1,667 messages/second and 144 GB/day raw. Batching, compression, and retention policies affect actual storage and bandwidth. Local control-loop load is more important than cloud QPS: define the sensor sampling rate and worst-case control deadline from the refrigeration and safety requirements.
  • Requirements should include offline operation, safe behavior on sensor or actuator faults, secure updates, recoverability after power loss, and a way to diagnose deployed devices.

2. High-level architecture

I would separate deterministic local control from cloud optimization. The freezer should keep food safe when disconnected; the cloud should not be in the critical control loop. For high-consequence cutoffs, I would keep an independent hardware thermostat or interlock rather than trusting the Pi alone.

flowchart TD
  subgraph Client
    T[Technician app]
    S[Sensors and actuators]
  end
  subgraph EdgeCDN["Edge / CDN"]
    F[Signed firmware and model delivery]
  end
  subgraph LoadBalancer["Load Balancer"]
    L[Device ingress load balancer]
  end
  subgraph APIServices["API / Services"]
    A[Device API]
    R[Device registry and configuration]
    M[Monitoring and alert service]
  end
  subgraph Cache
    C[Desired configuration cache]
  end
  subgraph Datastores
    D[Device and event database]
    O[Telemetry object storage]
  end
  subgraph MessageQueue["Message Queue"]
    Q[Telemetry and command stream]
  end
  subgraph Workers
    W[Rules and analytics workers]
  end
  S -->|Samples and actuator state| Pi[Freezer edge controller]
  Pi -->|Local control decisions| S
  T -->|Pair and inspect device| A
  Pi -->|Authenticated telemetry| L
  L -->|Ingest| A
  A -->|Read desired settings| C
  A -->|Registry and audit writes| D
  A -->|Publish telemetry| Q
  Q -->|Consume events| W
  W -->|Store history| O
  W -->|Raise alerts| M
  F -->|Signed versioned updates| Pi
  R -->|Provision device settings| C
Diagram

3. API design

  • POST /v1/devices/{deviceId}/telemetry:batch — upload timestamped, sequence-numbered readings; tolerate duplicate batches.
  • GET /v1/devices/{deviceId}/desired-state — fetch versioned settings and command state after reconnect.
  • POST /v1/devices/{deviceId}/events — report alarms, boot status, faults, and update outcomes.
  • POST /v1/devices/{deviceId}/firmware:check — return an eligible signed update manifest.
  • POST /v1/devices/{deviceId}/commands/{commandId}:ack — acknowledge a command or report its rejection.

Authenticate devices with individual certificates, authorize by device identity, and make command IDs and versions explicit so retries do not apply a command twice.

4. Data model & storage

  • Store device identity, hardware revision, installed software version, and ownership in a relational registry. Keep configuration versioned, auditable, and validated against device capabilities.
  • Store recent alarms and operational state in a database for fast fleet queries. Put high-volume time-series history in time-series or partitioned object storage; partition by device and time, with retention and downsampling policies.
  • Keep local configuration, recent telemetry, last known safe state, and a durable command journal on the Pi. Use a transactional local database or carefully managed append-only records, with bounded disk use and recovery checks.
  • Sign firmware and configuration bundles. Protect device keys in hardware-backed storage where available, restrict debug access, encrypt transport and sensitive local data, and support credential revocation.

5. Deep dive

The key design is a local, bounded control loop with explicit fault handling. I would first map each input to its required sampling rate, filtering, validity range, and control deadline. I would isolate sensor drivers behind a hardware abstraction layer and test the same control logic with recorded traces and simulated faults. The loop should avoid network calls, disk I/O, dynamic allocation, and long-running analytics. A watchdog should detect a stalled process; startup should validate configuration before enabling outputs. I would define a safe state for each fault, such as a sensor disagreement, corrupted configuration, low disk space, or unexpected reboot, and verify it against hardware and refrigeration experts.

Cloud connectivity should only update non-critical desired settings or provide advisory analytics. Updates should be staged, signed, checked for hardware compatibility, installed atomically, and rolled back if health checks fail. Because fleet failures can be correlated, I would canary across a small device cohort before expanding rollout.

sequenceDiagram
  participant S as Sensor
  participant C as Local control loop
  participant H as Hardware interlock
  participant D as Local journal
  participant Cloud as Device service
  S->>C: Sample with timestamp and validity
  C->>C: Validate and compute bounded control action
  C->>H: Request actuator change
  H-->>C: Enforce independent safety limits
  C->>D: Record state and sequence number
  C-->>Cloud: Upload telemetry when connected
  Cloud-->>C: Versioned desired settings or signed update
  C->>C: Validate; apply only if safe and supported
Diagram

6. Scale, bottlenecks & trade-offs

  • Reliability: A Pi adds local autonomy but also introduces SD-card wear, power-loss corruption, operating-system updates, and boot failures. Use industrial-rated storage or a read-only root filesystem, atomic writes, watchdogs, brownout handling, and recovery testing. Keep independent hardware protection for critical temperature limits.
  • Timing: Ordinary Linux scheduling may have unbounded latency. Measure worst-case loop latency under CPU, disk, and network stress. If hard real-time guarantees are required, use a real-time kernel, a dedicated microcontroller for the control loop, or hardware interlocks; let the Pi handle orchestration and analytics.
  • Connectivity: Buffer telemetry locally with sequence numbers, bounded retention, and backpressure. Reconnect with jittered retries and send current alarms and state before old bulk history. Cloud outages must not stop local control.
  • Fleet operations: Use a device registry, per-device credentials, staged rollouts, health metrics, and remote rollback. Monitor missed heartbeats, temperature excursions, reboot loops, storage pressure, and software-version distribution.
  • Trade-off: Moving processing to the freezer reduces network dependence and can improve response time, but shifts complexity to hardware qualification, security, and lifecycle support. I would migrate one function at a time, prove safety and recovery on pilot devices, and keep a tested fallback path before broad deployment.
System designHardSenior Software EngineerDesign round

12. How would you design a URL shortener?

Model answer

1. Requirements & scale

Functional requirements

  • Create a short URL for a long URL, optionally with a custom alias and expiration.
  • Redirect short URLs quickly and reliably; support disabling or deleting links.
  • Provide basic click analytics and protect the service from abuse.

Non-functional requirements

  • Redirects should be highly available and typically complete in under 100 ms at the edge.
  • Codes must be unique, difficult to enumerate, and durable after creation.
  • Analytics may be eventually consistent; link creation and alias uniqueness must be strongly consistent.

Estimates

  • Assume 10 million new links/day and 1 billion redirects/day: about 116 creates/s and 11,600 redirects/s on average. Plan for 10x peaks.
  • At roughly 500 bytes per link, link data grows by 5 GB/day, or about 1.8 TB/year before indexes and replication.
  • At 1 KB per redirect response, outbound traffic averages about 12 MB/s, with peaks near 120 MB/s. The read-to-write ratio is about 100:1.

2. High-level architecture

flowchart TD
  subgraph Client
    B[Browser]
    A[Admin Client]
  end
  subgraph Edge
    CDN[CDN and Edge Cache]
    WAF[WAF and Rate Limits]
  end
  subgraph LoadBalancer
    LB[Load Balancer]
  end
  subgraph Services
    API[Link API]
    REDIR[Redirect Service]
    ANALYTICS[Analytics Collector]
  end
  subgraph Cache
    C[Distributed Link Cache]
  end
  subgraph Datastores
    DB[Link Metadata Store]
    EVENTS[Analytics Store]
  end
  subgraph MessageQueue
    Q[Click Event Queue]
  end
  subgraph Workers
    WORKER[Analytics Workers]
    ABUSE[Abuse Scanner]
  end
  B -->|short URL request| CDN
  CDN -->|cache miss| WAF
  WAF --> LB
  LB -->|redirect lookup| REDIR
  LB -->|create or manage link| API
  REDIR -->|read code| C
  C -->|cache miss| DB
  REDIR -->|record click| Q
  REDIR -->|redirect response| B
  A -->|link management| API
  API -->|write metadata| DB
  API -->|scan destination| ABUSE
  Q -->|click events| WORKER
  WORKER -->|aggregates| EVENTS
Diagram

3. API design

  • POST /v1/links — create a link; accept long_url, optional custom_alias, expires_at, and an idempotency key.
  • GET /{code} — resolve a code and return a 301 or 302 redirect.
  • GET /v1/links/{code}/analytics?from=&to= — retrieve aggregated click metrics for the owner.
  • DELETE /v1/links/{code} — disable a link; make deletion idempotent.

4. Data model & storage

  • Store link metadata in a distributed key-value store keyed by code: destination URL, owner ID, creation and expiry times, status, and redirect policy. A strongly consistent conditional write enforces alias uniqueness.
  • Keep ownership and billing records in a relational store if transactional queries are needed. Keep high-volume click events in a queue and an analytics-oriented store, rather than writing each click into the metadata database.
  • Cache hot code-to-destination mappings in memory and Redis with a TTL bounded by link expiry. Negative-cache unknown codes briefly to reduce repeated misses.
  • Partition metadata by code hash. Replicate across availability zones; use regional replicas or globally distributed storage when low-latency worldwide reads justify the added consistency complexity.

5. Deep dive

Code generation and redirect path

  • Generate a unique 64-bit ID using a distributed ID service or leased ID ranges, then encode it as base62. A 64-bit space provides ample capacity; the encoding is compact, but sequential IDs are guessable, so permute the ID with a reversible keyed function or use random IDs with collision checks when opacity matters.
  • Do not rely on a truncated hash alone: collisions need detection and resolution. For custom aliases, normalize and validate the requested string, then conditionally insert it; return 409 Conflict if it already exists.
  • On a redirect, check the edge cache, then the regional cache, then the metadata store. Validate status and expiry before returning the destination. Return 404 for unknown codes and 410 for expired or disabled links.
  • Use 302 by default when destinations can change or click tracking matters, since browsers and intermediary caches may retain 301 responses. Permit 301 only when the owner explicitly requests permanent caching.
  • Emit a compact click event asynchronously. If the queue is unavailable, redirects should still succeed; use bounded local buffering or drop nonessential analytics rather than making the redirect depend on analytics storage.
sequenceDiagram
  participant U as User
  participant E as Edge
  participant R as Redirect Service
  participant C as Cache
  participant D as Link Store
  participant Q as Event Queue
  U->>E: Request short code
  E->>R: Cache miss lookup
  R->>C: Get code
  alt Cache hit
    C-->>R: Destination and status
  else Cache miss
    R->>D: Read metadata
    D-->>R: Destination and status
    R->>C: Populate cache
  end
  R->>Q: Publish click event
  R-->>U: Redirect response
Diagram

6. Scale, bottlenecks & trade-offs

  • Cache hot links aggressively and use CDN caching only where redirect semantics and invalidation are acceptable. A mutable or revoked destination needs short TTLs or explicit cache purges.
  • Replicate link reads across regions, but route writes for a code to a home region or globally consistent store. This favors fast reads while keeping alias creation correct.
  • Apply per-IP and per-account rate limits, destination reputation checks, malware scanning, and abuse reporting. Avoid fetching arbitrary destinations synchronously in the redirect path.
  • Keep click events asynchronous and aggregate them in batches. This trades immediate analytics freshness for redirect availability and lower write cost.
  • Protect against enumeration and phishing with nonsequential-looking codes, abuse controls, and safe preview/reporting mechanisms. Log minimal personal data and define retention limits for click metadata.
TechnicalEasySenior Software Engineer

13. What is the difference between a HashMap and a TreeMap?

Model answer

Both HashMap and TreeMap implement Map<K, V>, but they organize keys differently.

HashMapTreeMap
OrganizationHash bucketsBalanced search tree, typically a red-black tree
Key orderNo ordering guaranteeKeys kept in natural order or a supplied Comparator
Typical get/putO(1) average; can degrade with collisionsO(log n)
Useful operationsFast key-based lookupSorted iteration, firstKey, lastKey, and range views such as subMap
Null keysAllows one null keyGenerally disallows null keys with natural ordering; a comparator may change that behavior

Use HashMap when lookup speed matters and key order does not. Use TreeMap when you need sorted keys or efficient range queries. Both rely on stable key equality; HashMap relies on hashCode and equals, while TreeMap uses comparison ordering.

TechnicalEasySenior Software Engineer

14. What is the difference between a server and a service?

Model answer

  1. A server is a runtime or machine that accepts requests and provides resources or computation. The term can refer to hardware, a process, or software such as an HTTP server.
  2. A service is a capability or business function exposed through an interface—for example, a billing service or Wix site-publishing service. It may run on one server or be distributed across many servers.
  3. The distinction is about role versus capability: a server provides the execution environment; a service describes what users or other systems can use. In practice, people sometimes use the terms loosely, such as calling a long-running server process “a service.”

For example, an HTTP server running on several hosts can route requests to a publishing service, which may itself consist of multiple processes and dependencies.

TechnicalEasySenior Software Engineer

15. What is the difference between a process and a thread?

Model answer

  1. Process: An instance of a running program, with its own virtual address space and operating-system resources. Processes are isolated from one another; communication usually requires an explicit mechanism such as sockets or shared memory.
  2. Thread: A unit of execution within a process. Threads in the same process share its heap and resources, but each has its own stack, registers, and program counter.
  3. Key trade-off: Threads are typically cheaper to create and switch between, and make sharing data straightforward. That sharing also creates synchronization and race-condition risks. A process boundary provides stronger isolation, but communication and context switching can cost more.
TechnicalMediumSenior Software EngineerTechnical interview

16. What is your opinion about working with the Node.js core team to introduce performance hooks that would enable application performance monitoring a…

The full question

What is your opinion about working with the Node.js core team to introduce performance hooks that would enable application performance monitoring and OpenTelemetry integration in ES6?

Model answer

I’d be strongly in favor, provided the hooks are designed as small, stable runtime primitives, rather than making Node.js core responsible for an APM or OpenTelemetry SDK. Good hooks can make instrumentation more consistent across vendors and reduce the need for fragile monkey-patching.

  1. Start from concrete gaps. I’d work with the Node.js Diagnostics and core teams, APM vendors, and OpenTelemetry maintainers to identify operations that are difficult to observe reliably today—such as important async boundaries or runtime-level events. Node already has useful building blocks like perf_hooks, diagnostics_channel, and async_hooks; the proposal should complement those rather than duplicate them.
  2. Keep the API opt-in and low overhead. Hooks should do almost no work when nobody is listening, avoid allocations on hot paths, and expose enough information for observers to build useful telemetry without leaking private runtime details. I’d compare a callback or diagnostics-channel approach with polling, and require benchmarks for both the disabled and enabled cases.
  3. Make it composable with OpenTelemetry. Core should expose stable events and lifecycle information; an OpenTelemetry integration should translate those into spans and metrics outside the runtime. Context propagation needs particular care: it must behave correctly across async boundaries without imposing surprising costs or conflicting with existing mechanisms.
  4. Prove the design before standardizing it. I’d prototype the API, test it against real workloads and multiple instrumentation consumers, and measure overhead, event volume, and behavior under concurrency. Then I’d document versioning and compatibility expectations and follow the Node.js project’s normal design and review process.
flowchart LR
    A[Node.js runtime] -->|stable opt-in events| B[Diagnostics hooks]
    B --> C[OpenTelemetry SDK]
    B --> D[APM integrations]
    C --> E[Traces and metrics]
    D --> E
Diagram

The key trade-off is observability versus runtime cost and API stability. I’d support adding hooks when they expose information that cannot be obtained robustly elsewhere, have demonstrably small overhead, and serve multiple consumers. That gives Datadog and the broader ecosystem a more reliable foundation without coupling Node.js core to any one telemetry product.

TechnicalMediumSenior Software EngineerKarat Screening Round

17. A system is running very slowly.

The full question

A system is running very slowly. How would you debug the slowness?

Model answer

I’d first establish what is slow, for whom, and since when. “The system is slow” could mean high latency for one endpoint, elevated error rates, slow background jobs, or a recent regression. I’d compare the affected time window with a healthy baseline and check whether the issue is global or limited to a region, tenant, endpoint, or deployment.

  1. Measure the symptom: Use dashboards and traces to inspect latency percentiles (especially p95/p99), throughput, errors, and saturation. Break latency down by service and dependency rather than relying only on averages.
  2. Check recent changes: Correlate the start of the regression with deploys, configuration changes, traffic shifts, or dependency incidents. If there’s a strong correlation and rollback is safe, mitigate first while continuing the investigation.
  3. Find the bottleneck: Inspect CPU, memory, garbage collection, thread or connection pools, disk and network I/O, queue depth, and database query latency. Distributed traces help identify which span is consuming time; profiles can explain CPU or allocation hotspots.
  4. Test a hypothesis: For example, if database time is high, inspect slow-query logs, query plans, lock waits, and pool saturation. Change one factor at a time in a representative environment, and compare measurements before and after.
  5. Mitigate and verify: Depending on the cause, reduce load, scale a constrained tier, disable an expensive feature, or roll back. Confirm the user-facing metric improves and that the change hasn’t shifted the bottleneck elsewhere.
  6. Prevent recurrence: Add or improve alerts, capacity limits, regression tests, and runbook guidance. Record the cause and the evidence so the next incident is faster to diagnose.
flowchart TD
    A[Confirm user impact] --> B[Scope by endpoint and cohort]
    B --> C[Compare metrics with baseline]
    C --> D{Recent change correlated?}
    D -->|Yes| E[Mitigate or roll back safely]
    D -->|No| F[Trace request across services]
    E --> F
    F --> G[Identify saturated resource or slow dependency]
    G --> H[Test one hypothesis]
    H --> I[Verify latency and error recovery]
    I --> J[Add prevention and document findings]
Diagram

I’d keep the investigation evidence-led: avoid guessing from a single metric, and distinguish immediate mitigation from the deeper fix.

TechnicalMediumSenior Software Engineer

18. What features of Scala make it compelling to you?

Model answer

Scala appeals to me because it combines the reliability of a strong type system with the practicality of the JVM.

  1. Types that make invalid states harder to represent. Algebraic data types, pattern matching, and expressive generics let me model domain rules directly. For example, a publishing workflow can distinguish Draft, Scheduled, and Published states rather than passing around loosely defined strings. That makes code easier to reason about and refactor safely.
  2. Functional programming where it helps. Immutability and functions with explicit inputs and outputs make business logic easier to test and understand. I value being able to use those ideas without giving up object-oriented techniques when they make a design clearer.
  3. A good balance of concision and structure. Scala can reduce repetitive code while keeping abstractions explicit. Features such as case classes and pattern matching are useful for building clear APIs and transformations, especially in data-heavy backend services.
  4. JVM ecosystem and interoperability. Scala runs on the JVM, so teams can use mature libraries, observability tools, and existing Java components. That matters in a large platform: adopting Scala does not mean isolating a service from the rest of the system.
  5. Concurrency options. Depending on the workload, Scala offers libraries and patterns for asynchronous work and concurrency. I like being able to choose an approach that makes failure handling and resource use explicit, rather than treating concurrency as an afterthought.

The trade-off is that Scala’s flexibility can lead to overly abstract code, steep onboarding, or slow compilation if a team does not agree on conventions. I find it most compelling when a team uses the language deliberately: clear domain types, restrained abstractions, consistent style, and straightforward interfaces between services. In a platform such as Wix, that combination can help teams evolve complex backend domains without sacrificing maintainability or JVM compatibility.

TechnicalMediumSenior Software EngineerJavaScript Platform & DSA

19. Where should asynchronous code be used in Node.js, and why?

Model answer

  1. Use asynchronous I/O for operations that wait. Node.js runs JavaScript on an event-loop thread, so asynchronous file, network, database, and timer APIs let that thread serve other requests while the operation is pending. This is especially important for API servers and control-plane services handling many concurrent connections.
  2. Prefer non-blocking APIs in request paths. Use promise-based APIs or async/await for operations such as RPCs, storage access, and reading files. await makes the code easier to follow; it does not block the event loop while the promise is pending. Avoid synchronous APIs such as readFileSync in a server request handler because they prevent all other JavaScript callbacks from running until they finish.
  3. Do not assume async makes CPU work non-blocking. A long loop, compression task, or expensive JSON transformation still occupies the event-loop thread, even inside an async function. Break suitable work into bounded chunks, or move CPU-heavy work to worker_threads or a separate service. Native APIs may use the libuv thread pool, but its capacity is finite and should be considered when tuning workloads.
  4. Handle concurrency and failures deliberately. Await dependent operations in order; use Promise.all only for independent work that can safely run concurrently. Bound fan-out, apply timeouts and cancellation where supported, and handle promise rejections so failures do not become unhandled or leave requests hanging.
flowchart TD
    A[Request handler] --> B{Operation type}
    B -->|Network or storage wait| C[Start async I/O]
    C --> D[Event loop serves other work]
    C --> E[Completion callback or promise]
    E --> F[Resume handler]
    B -->|CPU intensive| G[Worker thread or separate service]
Diagram
TechnicalMediumSenior Software Engineer

20. How is disk I/O performed?

Model answer

  1. An application requests a file read or write through an operating-system API. The OS filesystem resolves the path and permissions, then uses its page cache when possible. A cache hit may avoid physical device I/O.
  2. On a cache miss, or when dirty data must be written, the filesystem issues block I/O through the kernel’s storage layer and device driver. The device transfers data—often using DMA—and signals completion. The OS then makes read data available to the process or completes the write request.
flowchart LR
    A[Application] -->|read or write request| B[System call]
    B --> C[Filesystem]
    C -->|cache hit| D[Page cache]
    C -->|cache miss or flush| E[Block layer and driver]
    E --> F[Storage device]
    F -->|data transfer and completion| E
    E --> D
    D -->|data or completion| A
Diagram
  1. Writes are often buffered, so a successful write call may only mean data reached the OS cache—not durable storage. Applications that require durability use APIs such as fsync/fdatasync (or the corresponding language APIs), with the exact guarantees depending on the filesystem and device.
  2. In Java, common options include InputStream/OutputStream, FileChannel, and AsynchronousFileChannel. Whether I/O is blocking or asynchronous depends on the API and operating-system implementation; “asynchronous” does not necessarily mean the device itself is doing work without kernel involvement.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions