Backend Engineer interview questions & answers

20 Backend Engineer interview questions with complete model answers, spanning System design, Behavioral, Coding, Technical, Product & growth. The bank holds 73 Backend Engineer questions in total, tagged by round and difficulty.

BehavioralEasyBackend EngineerJob interview

1. What did you see for yourself in terms of your career and future?

Model answer

  1. Situation — As I’ve grown as a backend engineer, I’ve become most motivated by work where reliable systems directly improve a customer’s experience. In a marketplace, that connection is especially clear: a delay, failed payment, or inaccurate listing can undermine trust for both buyers and sellers.
  2. Task — I’ve been thinking about how to build a career that combines strong technical depth with broader ownership—not just delivering services, but helping teams make good decisions about reliability, scale, and customer impact.
  3. Action
  • I’ve focused on building a strong foundation in distributed systems, API design, data modeling, and operational practices, because those skills let me contribute to both new features and the health of existing services.
  • On projects, I try to understand the user problem and the relevant business metric before settling on an implementation. For example, when improving a latency-sensitive marketplace flow, I would look beyond average latency to tail latency, failure rates, and the effect on successful transactions.
  • I’ve also made observability and safe operations part of how I approach backend work: clear service-level indicators, actionable alerts, gradual rollouts, and a rollback plan. I want to prevent problems where possible and respond calmly when they happen.
  • Over time, I want to take on larger technical ownership—leading design discussions, mentoring engineers, and aligning teams around trade-offs—while staying close enough to the code and production systems to keep learning.
  • Mercari’s recommerce mission appeals to me because backend quality can help make secondhand commerce feel dependable and easy at scale. I’d want to contribute to that through systems that support a trustworthy experience for buyers and sellers.
  1. Result — The direction I see for myself is becoming a senior backend engineer and, over time, a technical leader who raises the quality of both systems and team decisions. I’m not aiming to move away from engineering; I want to expand my impact while continuing to deepen my technical judgment. I’d measure progress by whether I can help teams deliver customer value more safely, reliably, and consistently.
BehavioralMediumBackend EngineerTechnical Round

2. How would you approach giving code reviews?

Model answer

  1. Situation — On a backend team supporting user-facing marketplace flows, code reviews were sometimes either delayed or reduced to style comments. That created two risks: important issues in data handling or failure behavior could be missed, and authors could spend time waiting for feedback that did not improve the change. I wanted reviews to protect production quality while helping the team ship steadily.
  2. Task — My goal was to give feedback that was timely, technically useful, and respectful. The central judgment was how to focus limited review time on correctness, security, reliability, and maintainability without turning personal preferences into blockers.
  3. Action
  • I first read the change in context: the issue it addressed, the affected API or service, and the expected behavior. For a marketplace backend change, I pay particular attention to authorization, money or inventory state transitions, idempotency, privacy, and how downstream failures are handled.
  • I look for concrete risks before commenting on style: incorrect edge cases, unsafe retries, missing validation, concurrency problems, migrations that cannot be rolled back, and tests that do not exercise the intended behavior.
  • I make comments specific and explain the consequence. Instead of writing “this is wrong,” I might say, “If this request is retried after a timeout, could it create a second reservation? Can we use the operation ID as an idempotency key?” That gives the author a problem to solve and a reason it matters.
  • I distinguish blocking issues from suggestions. I’ll mark a correctness or security concern as blocking, but phrase naming or readability preferences as optional unless they make the code materially harder to maintain.
  • I try to respond promptly, split large reviews into manageable passes, and ask questions when I am unsure rather than assuming the author missed something. If a discussion becomes nuanced, I’ll move it to a short conversation and summarize the decision in the review.
  • When the same concern appears repeatedly, I look for a team-level fix—such as a checklist, shared helper, or test pattern—instead of repeating the same comment on every pull request.
  1. Result — This approach makes reviews more actionable and keeps attention on risks that can affect users or operations. It also builds shared understanding: the author can see why a change matters, and the reviewer remains accountable for reaching a decision rather than leaving a pull request stalled. I see a good review as both a quality gate and a collaboration tool.
BehavioralMediumBackend EngineerOnsite

3. Describe a time when you had to coordinate between two teams that were in conflict or seriously misaligned.

The full question

Describe a time when you had to coordinate between two teams that were in conflict or seriously misaligned. What caused the disagreement, how did you align stakeholders, what actions did you personally take, and what was the outcome?

Model answer

Situation

In my previous role as a project manager at a mid-sized tech company, I was tasked with overseeing a critical product launch. The engineering team and the marketing team were in conflict over the product's feature set and launch timeline. The engineering team was concerned about the feasibility and quality of the features within the given timeline, while the marketing team was pushing for a launch date that aligned with a major industry event. This misalignment threatened the success of the product launch and could have resulted in missed market opportunities and potential revenue loss.

Task

My goal was to align both teams to ensure a successful product launch that met both the technical feasibility and market timing. The key constraint was balancing the engineering team's need for quality assurance with the marketing team's deadline for the industry event.

Action

  • I initiated a series of joint meetings between the two teams to openly discuss their concerns and objectives. This helped create a platform for transparent communication and mutual understanding.
  • To address the engineering team's concerns, I worked with them to identify the critical features that could be realistically developed and tested within the timeline. I facilitated a prioritization exercise to focus on high-impact features.
  • For the marketing team, I proposed a phased launch strategy. This allowed us to meet the initial deadline with a core set of features, while planning subsequent updates to incorporate additional features post-launch.
  • I mediated discussions to ensure both teams understood the trade-offs involved and the importance of each other's objectives. I emphasized the shared goal of a successful product launch and how collaboration was essential to achieve it.
  • I also set up a regular progress tracking system to keep both teams informed and aligned on the project status, which helped in maintaining momentum and accountability.

Result

The coordinated effort led to a successful product launch that met the industry event deadline with a robust set of core features. The phased approach allowed us to continue enhancing the product post-launch, which was well-received by customers and stakeholders. This experience reinforced the importance of cross-functional collaboration and transparent communication. I learned that facilitating open dialogue and focusing on shared goals can effectively resolve conflicts and align teams towards a common objective.

BehavioralMediumBackend EngineerOnsite

4. You may be asked behavioral questions such as: Tell me about a time you had a conflict with a teammate or partner team.

The full question

You may be asked behavioral questions such as:

  • Tell me about a time you had a conflict with a teammate or partner team. What happened, how did you handle it, and what was the outcome?
  • What project are you most proud of, and why? What impact did it have?

Model answer

Situation

In my role as a software engineer at a previous company, I was part of a cross-functional team working on a high-stakes project to develop a new feature for our flagship product. The project had a tight deadline, and tensions were high. A conflict arose between our team and the design team regarding the user interface. The designers wanted to implement a visually complex design that would require significant development time, while our team was concerned about meeting the deadline without compromising the feature's functionality.

Task

As the lead developer on the project, my goal was to mediate the conflict and find a solution that balanced both the design team's vision and our technical constraints. The key challenge was to ensure that the project stayed on schedule while maintaining a high-quality user experience.

Action

  • I initiated a meeting with both teams to openly discuss the concerns and priorities. I emphasized the importance of collaboration and understanding each other's perspectives to ensure the project's success.
  • During the meeting, I actively listened to the design team's rationale for the complex interface and shared our technical limitations and timeline constraints. I encouraged both teams to express their views candidly.
  • I proposed a compromise by suggesting a phased approach: implementing a simplified version of the design for the initial release, followed by iterative enhancements in subsequent updates. This would allow us to meet the deadline while gradually incorporating the designers' vision.
  • To facilitate this, I worked closely with the design lead to identify the core elements of the interface that could be implemented within the current timeline without sacrificing quality.
  • I also coordinated with the project manager to adjust the timeline for future updates, ensuring that the design enhancements were prioritized in the development roadmap.

Result

The compromise was well-received by both teams, and we successfully launched the feature on time with a simplified yet effective user interface. The phased approach allowed us to gather user feedback, which informed the subsequent design iterations. This experience taught me the value of empathy and open communication in resolving conflicts and reinforced the importance of balancing creativity with practicality. The project not only met its deadline but also received positive feedback from users, enhancing our product's reputation in the market.

BehavioralMediumBackend EngineerTechnical Round

5. How would you approach a production bug introduced by someone else?

Model answer

  1. Situation — In one example, a production release caused a subset of users to receive errors when completing a high-value action. The change had been made by another engineer, and the issue affected a dependency used by more than one service. My priority was to reduce user impact quickly while keeping the response blameless and focused on evidence.
  2. Task — I needed to help establish the scope, restore reliable behavior, and coordinate the investigation without making an unverified change that could worsen the incident. The key tension was speed versus safety: users needed a fix, but we also had to preserve data integrity.
  3. Action
  • I started by checking the incident channel, dashboards, and recent deploys. I compared error rates and affected request paths against the previous hour to distinguish a release-related regression from a broader dependency problem.
  • I helped define impact precisely: which regions, client versions, and operations were failing, and whether requests were failing before or after a state change. I asked someone to check for partial writes so we would not treat a data-integrity issue as only an availability issue.
  • I worked with the service owner to identify the smallest reversible mitigation. In this case, we rolled back the release after confirming that doing so would not invalidate in-flight operations, then watched the relevant error and success metrics.
  • Once service recovered, I joined the code-level investigation. We reproduced the failure with the affected request shape and traced it to an assumption about a downstream response that was not guaranteed by the API contract.
  • I kept communication factual: what was known, what we were testing, and who owned each next step. I avoided framing the incident around who wrote the change; that would not help us restore service or learn from it.
  • Afterward, I contributed a regression test for the missing response case and a follow-up to clarify the dependency contract and alert on this failure mode.
  1. Result — The rollback restored the affected path, and monitoring confirmed recovery before we prepared a corrected change. The follow-up test prevented the same assumption from being reintroduced in that flow. I took away that a fast, blameless response still needs disciplined impact assessment—especially checking for partial writes—and that prevention should address the system conditions, not just the individual change.
CodingEasyBackend EngineerEighth Round

6. Implement strcpy to copy a string.

Model answer

// Copy a null-terminated byte string, including its '\0' terminator.
// Preconditions: src contains a terminator and dest has sufficient capacity.
function strcpyBytes(dest, src) {
  let length = 0;
  while (length < src.length && src[length] !== 0) {
    length++;
  }

  if (length === src.length) {
    throw new Error('Source is not null-terminated');
  }
  if (dest.length < length + 1) {
    throw new Error('Destination buffer is too small');
  }

  // Copy the characters and the terminating zero.
  for (let i = 0; i <= length; i++) {
    dest[i] = src[i];
  }
  return dest;
}

// Example: encode UTF-8 text and add the C-style null terminator.
const text = new TextEncoder().encode('Tencent');
const src = new Uint8Array(text.length + 1);
src.set(text);
const dest = new Uint8Array(src.length);

strcpyBytes(dest, src);
console.log(new TextDecoder().decode(dest.subarray(0, dest.length - 1)));
  • This models strcpy on byte buffers because JavaScript strings are immutable and are not null-terminated.
  • Like C strcpy, overlapping source and destination buffers are not supported; use a temporary buffer or a memmove-style implementation if overlap must be handled.

Complexity: O(n) time and O(1) extra space, where n is the source length.

CodingEasyBackend EngineerFirst Round

7. Find the depth of a binary tree.

Model answer

function maxDepth(root) {
  if (root === null) return 0;

  // Each queue entry stores a node and its depth.
  const queue = [[root, 1]];
  let head = 0;
  let depth = 0;

  while (head < queue.length) {
    const [node, nodeDepth] = queue[head++];
    depth = Math.max(depth, nodeDepth);

    if (node.left !== null) queue.push([node.left, nodeDepth + 1]);
    if (node.right !== null) queue.push([node.right, nodeDepth + 1]);
  }

  return depth;
}
  • Use breadth-first traversal and track each node’s depth; the greatest depth is the tree’s maximum depth.
  • Return 0 for an empty tree. This assumes nodes have left and right properties.

Complexity: Time O(n); space O(w), where w is the maximum tree width (worst case O(n)).

CodingEasyBackend EngineerVideo technical interview

8. Given an array or list of numbers, how would you remove any duplicates?

Model answer

function removeDuplicates(numbers) {
  // Set preserves the first occurrence of each value and its input order.
  return [...new Set(numbers)];
}

console.log(removeDuplicates([4, 2, 4, 1, 2])); // [4, 2, 1]
  • I use a Set to track values already seen; spreading it back into an array preserves first-occurrence order.
  • This uses JavaScript's Set equality semantics, including treating NaN values as duplicates.

Complexity: O(n) time and O(n) additional space.

CodingMediumBackend EngineerSeventh Round

9. Given n buildings in a row with heights w_i, where 1 ≤ n ≤ 100000 and 1 ≤ w_i ≤ 100000, determine for every building how many buildings Xiao Q can…

The full question

Given n buildings in a row with heights w_i, where 1 ≤ n ≤ 100000 and 1 ≤ w_i ≤ 100000, determine for every building how many buildings Xiao Q can see from that position, including the current building. Xiao Q walks from the first building to the last. A building in front that is at least as tall as a building behind it blocks that building. Read n followed by the n building heights, and output n space-separated visibility counts. For input 6 and heights 5 3 8 3 2 5, the output is 3 3 5 4 4 4.

Model answer

For a building at position i, scan outward independently in each direction. A building is visible if every building between it and i is shorter than it. Thus, in either direction, visible buildings are exactly the strict record highs encountered while scanning outward.

const fs = require("fs");
const tokens = fs.readFileSync(0, "utf8").trim().split(/\s+/).map(Number);
const n = tokens[0];
const heights = tokens.slice(1, n + 1);

if (!Number.isInteger(n) || n <= 0 || heights.length !== n) {
  throw new Error("Expected n followed by n building heights");
}

const nextGreaterRight = Array(n).fill(-1);
const nextGreaterLeft = Array(n).fill(-1);
let stack = [];

// For each building, find the next strictly taller building to its right.
for (let i = n - 1; i >= 0; i--) {
  while (stack.length > 0 && heights[stack[stack.length - 1]] <= heights[i]) {
    stack.pop();
  }
  if (stack.length > 0) nextGreaterRight[i] = stack[stack.length - 1];
  stack.push(i);
}

stack = [];
// For each building, find the next strictly taller building to its left.
for (let i = 0; i < n; i++) {
  while (stack.length > 0 && heights[stack[stack.length - 1]] <= heights[i]) {
    stack.pop();
  }
  if (stack.length > 0) nextGreaterLeft[i] = stack[stack.length - 1];
  stack.push(i);
}

// Count record highs when scanning rightward starting at each index.
const visibleFromStartRight = Array(n).fill(0);
for (let i = n - 1; i >= 0; i--) {
  visibleFromStartRight[i] = 1;
  const next = nextGreaterRight[i];
  if (next !== -1) visibleFromStartRight[i] += visibleFromStartRight[next];
}

// Count record highs when scanning leftward starting at each index.
const visibleFromStartLeft = Array(n).fill(0);
for (let i = 0; i < n; i++) {
  visibleFromStartLeft[i] = 1;
  const next = nextGreaterLeft[i];
  if (next !== -1) visibleFromStartLeft[i] += visibleFromStartLeft[next];
}

const answer = heights.map((_, i) => {
  let count = 1; // Include the current building.
  if (i + 1 < n) count += visibleFromStartRight[i + 1];
  if (i - 1 >= 0) count += visibleFromStartLeft[i - 1];
  return count;
});

console.log(answer.join(" "));
  • The next-strictly-greater links skip buildings blocked by a closer building at least as tall as them. Following those links counts all visible record highs without scanning each position repeatedly.
  • The two directional counts are independent; the current building is included once.
  • Complexity: O(n) time and O(n) space. For the sample, the output is 3 3 5 4 4 4.
CodingMediumBackend EngineerFirst Round

10. How would you implement a hash table?

Model answer

Here is a simple hash table for string keys, using separate chaining to handle collisions and resizing to keep the load factor bounded.

class HashTable {
  constructor(initialCapacity = 8) {
    this.capacity = Math.max(1, initialCapacity);
    this.buckets = Array.from({ length: this.capacity }, () => []);
    this.size = 0;
    this.maxLoadFactor = 0.75;
  }

  // Hash a string into a non-negative 32-bit integer.
  hash(key) {
    if (typeof key !== "string") {
      throw new TypeError("HashTable keys must be strings");
    }

    let hash = 0;
    for (let i = 0; i < key.length; i++) {
      hash = (Math.imul(hash, 31) + key.charCodeAt(i)) >>> 0;
    }
    return hash % this.capacity;
  }

  set(key, value) {
    const index = this.hash(key);
    const bucket = this.buckets[index];

    // Update an existing key rather than adding a duplicate.
    for (const entry of bucket) {
      if (entry[0] === key) {
        entry[1] = value;
        return this;
      }
    }

    bucket.push([key, value]);
    this.size++;

    if (this.size / this.capacity > this.maxLoadFactor) {
      this.resize(this.capacity * 2);
    }
    return this;
  }

  get(key) {
    const bucket = this.buckets[this.hash(key)];
    for (const [storedKey, value] of bucket) {
      if (storedKey === key) return value;
    }
    return undefined;
  }

  has(key) {
    const bucket = this.buckets[this.hash(key)];
    return bucket.some(([storedKey]) => storedKey === key);
  }

  delete(key) {
    const bucket = this.buckets[this.hash(key)];
    const index = bucket.findIndex(([storedKey]) => storedKey === key);
    if (index === -1) return false;

    bucket.splice(index, 1);
    this.size--;
    return true;
  }

  resize(newCapacity) {
    const oldBuckets = this.buckets;
    this.capacity = newCapacity;
    this.buckets = Array.from({ length: newCapacity }, () => []);

    // Re-hash entries because their bucket indexes depend on capacity.
    for (const bucket of oldBuckets) {
      for (const [key, value] of bucket) {
        this.buckets[this.hash(key)].push([key, value]);
      }
    }
  }
}
  • Separate chaining makes collisions explicit; resizing rehashes all entries.
  • get returns undefined when absent, so use has to distinguish that from a stored undefined value.
  • Complexity: Average O(1) for lookup, insertion, and deletion with a well-distributed hash; worst case O(n). Space is O(n + capacity).
Product & growthMediumBackend EngineerTechnical Round

11. What would you consider when developing a login feature?

Model answer

Clarify & scope

I’d first clarify whether we’re building login for a new experience or improving an existing one, which clients need it, and whether the account system is shared across Mercari surfaces. I’d treat authentication as a trust-critical backend feature: users need reliable access, while the platform must protect listings, personal information, and transactions. I’d scope the first release to email-and-password login, with a clear path to social login or passkeys if user research supports them.

User segments & pain points

I’d focus first on returning buyers and sellers using a new device. They need to get back into their account quickly, but may have forgotten a password or be signing in from a suspicious location. Recovery must be understandable without making it easy for an attacker to take over an account.

Goals & success metrics

My North Star would be the percentage of legitimate login attempts that reach an authenticated session successfully. I’d pair it with login latency, abandonment, and recovery completion. Guardrails would include account-takeover reports, credential-stuffing rates, false-positive blocks, and support contacts. I’d segment these metrics by device, region, login method, and risk level so a healthy overall rate doesn’t hide problems for a particular group.

Solutions

I’d consider three approaches: password-only login, password login with risk-based additional verification, and passwordless login. Password-only is simple but weak against reused credentials; requiring a second factor every time adds friction; passwordless changes user behavior and recovery requirements.

Recommendation: Start with established, secure password authentication and risk-based step-up verification. Store passwords using a modern password-hashing algorithm with per-user salts and suitable work factors; never log credentials or return whether an email exists. Rate-limit attempts, use generic errors, protect session tokens, and provide an abuse-resistant recovery flow. Issue short-lived access credentials and rotate revocable refresh tokens. Make the design accessible and support secure logout across devices.

Prioritization & trade-offs

I’d prioritize safe, dependable login and recovery over adding multiple sign-in providers. Risk-based checks balance protection and convenience, but depend on reliable signals and need monitoring for bias and false positives.

MVP, measurement & rollout

I’d launch behind a feature flag, test recovery and session revocation, and ramp traffic gradually. I’d compare success, latency, and abuse guardrails by cohort, with rollback criteria agreed in advance. I’d also verify that login integrates cleanly with checkout and listing flows so authentication protects the account without unexpectedly interrupting a transaction.

System designEasyBackend EngineerOnsite

12. Design an object-oriented elevator control system for a building with multiple floors and multiple elevators.

The full question

Design an object-oriented elevator control system for a building with multiple floors and multiple elevators.

The system should support:

  • Hall requests from each floor, where a user can request to go up or down
  • Cabin requests from inside an elevator, where a user selects a destination floor
  • Tracking each elevator's current floor, direction, door state, and pending stops
  • Assigning hall requests to an appropriate elevator
  • Moving elevators efficiently while avoiding obviously poor scheduling decisions

Focus on clean object-oriented design and the core scheduling logic. You do not need to model low-level motor hardware, networking, or a graphical UI.

Discuss the main classes, responsibilities, state transitions, and how requests are processed. If useful, also describe a simple dispatch algorithm and how you would extend the design later.

Model answer

1. Requirements & scale

Functional Requirements:

  • Handle hall requests from each floor for up and down directions.
  • Handle cabin requests from inside an elevator to select destination floors.
  • Track each elevator's current floor, direction, door state, and pending stops.
  • Assign hall requests to the most appropriate elevator.
  • Move elevators efficiently to minimize wait and travel times.

Non-Functional Requirements:

  • System should be reliable and handle requests in real-time.
  • Scalable to accommodate buildings with varying numbers of floors and elevators.
  • Maintainable and extendable for future enhancements.

Scale Estimates:

  • Assume a building with 10 floors and 4 elevators.
  • Each elevator can handle up to 10 requests per minute.
  • Total requests per minute = 4 elevators * 10 requests = 40 requests.
  • System should handle peak loads efficiently, with potential scaling for larger buildings.

2. High-level architecture

flowchart TD
    subgraph Client
        A[User Interface]
    end

    subgraph API / Services
        B[Request Processor]
        C[Scheduler]
        D[Elevator Controller]
    end

    subgraph Datastores
        E[State Database]
    end

    A -- "Hall/Cabin Request" --> B
    B -- "Process Request" --> C
    C -- "Schedule Elevator" --> D
    D -- "Update State" --> E
    E -- "Current State" --> C
Diagram

3. API design

  • POST /request/hall: Submit a hall request from a specific floor with direction.
  • POST /request/cabin: Submit a cabin request from inside an elevator for a destination floor.
  • GET /elevator/status: Retrieve the current status of all elevators (floor, direction, door state).

4. Data model & storage

Datastore Choice:

  • Use a relational database (SQL) for structured data and ACID transactions to ensure consistency.

Key Tables:

  • Elevators: Tracks each elevator's current floor, direction, door state, and pending stops.
  • elevator_id (Primary Key)
  • current_floor
  • direction (enum: UP, DOWN, IDLE)
  • door_state (enum: OPEN, CLOSED)
  • pending_stops (list of floor numbers)
  • Requests: Stores hall and cabin requests.
  • request_id (Primary Key)
  • floor_number
  • direction (optional for cabin requests)
  • elevator_id (foreign key)

5. Deep dive

The core of this system is the scheduling logic that assigns hall requests to the most appropriate elevator. The scheduling algorithm should consider factors such as the current direction of the elevator, the proximity to the requested floor, and the current load of pending requests.

sequenceDiagram
    participant User
    participant RequestProcessor
    participant Scheduler
    participant ElevatorController
    participant StateDatabase

    User->>RequestProcessor: Submit Hall/Cabin Request
    RequestProcessor->>Scheduler: Process Request
    Scheduler->>StateDatabase: Fetch Current Elevator States
    StateDatabase-->>Scheduler: Return Elevator States
    Scheduler->>ElevatorController: Assign Request to Elevator
    ElevatorController->>StateDatabase: Update Elevator State
    StateDatabase-->>ElevatorController: Confirm Update
Diagram

6. Scale, bottlenecks & trade-offs

Scalability:

  • The system can scale horizontally by adding more elevators and processing nodes.
  • The scheduler can be distributed to handle more requests concurrently.

Bottlenecks:

  • The scheduler could become a bottleneck if not properly optimized, as it needs to make real-time decisions.
  • Database performance could degrade with a high number of concurrent requests; indexing and query optimization are crucial.

Trade-offs:

  • Consistency vs. Availability: Prioritize consistency to ensure accurate elevator states and request handling.
  • Push vs. Pull: Use a push model for real-time updates to elevators, ensuring timely response to requests.
  • Modular Design: Following modular design principles allows for easier maintenance and future extensions, such as adding predictive maintenance features or integrating with building management systems.

This design provides a robust framework for an elevator control system, focusing on efficient scheduling and real-time processing while maintaining a clean and modular architecture.

System designEasyBackend EngineerOnsite

13. Design the backend of an internal analytics system for a conversational AI product similar to ChatGPT.

The full question

Design the backend of an internal analytics system for a conversational AI product similar to ChatGPT. The goal is to power an analytical metrics dashboard used by product managers and backend engineers.

The dashboard itself and the LLM serving stack are out of scope. Focus on the data platform and backend services that collect data from existing production databases and service logs, compute product and reliability metrics, and serve those metrics to the dashboard.

Your design should address:

  • How to ingest data from existing services without overloading primary databases
  • What event and metric schemas you would use
  • How to support both near-real-time metrics and historical analysis
  • How to compute common metrics such as daily active users, number of conversations, request volume, latency percentiles, token usage, error rates, and feature adoption
  • How to slice metrics by dimensions such as time, model version, region, platform, and user segment
  • Data freshness, correctness, deduplication, and backfills
  • Privacy, access control, and operational monitoring
  • The APIs or query layer that a dashboard backend would call

Assume the system must support large-scale traffic and multi-month historical retention.

Model answer

1. Requirements & scale

Functional Requirements:

  • Ingest data from existing production databases and service logs.
  • Compute and serve metrics like daily active users, number of conversations, request volume, latency percentiles, token usage, error rates, and feature adoption.
  • Support slicing metrics by dimensions such as time, model version, region, platform, and user segment.
  • Provide APIs for the dashboard to query metrics.

Non-Functional Requirements:

  • Near-real-time metrics computation.
  • Support historical analysis with multi-month retention.
  • Ensure data freshness, correctness, deduplication, and support for backfills.
  • Implement privacy, access control, and operational monitoring.

Scale Estimates:

  • Assume 1 million DAUs generating 10 events per day: 10 million events/day.
  • Each event is approximately 1 KB, resulting in 10 GB/day of raw event data.
  • For a 6-month retention, storage needs are approximately 1.8 TB.
  • Assume a peak QPS of 100 for dashboard queries.

2. High-level architecture

flowchart TD
    subgraph Client
        A[Dashboard]
    end

    subgraph Edge/CDN
        B[API Gateway]
    end

    subgraph Load Balancer
        C[Load Balancer]
    end

    subgraph API / Services
        D[Metrics API]
        E[Ingestion Service]
    end

    subgraph Cache
        F[Redis Cache]
    end

    subgraph Datastores
        G[Event Storage (S3)]
        H[Data Warehouse (Redshift)]
        I[Metadata DB (PostgreSQL)]
    end

    subgraph Message Queue
        J[Kafka]
    end

    subgraph Workers
        K[Metrics Computation Workers]
    end

    A --> B
    B --> C
    C --> D
    C --> E
    E --> J
    J --> K
    K --> G
    K --> H
    D --> F
    F --> H
    H --> D
Diagram

3. API design

  • GET /metrics: Retrieve computed metrics for specified dimensions and time range.
  • POST /ingest: Ingest raw event data from production databases and service logs.
  • GET /status: Check the health and status of the metrics computation pipeline.

4. Data model & storage

Datastores:

  • Event Storage (S3): Used for raw event data storage. Chosen for its scalability and cost-effectiveness.
  • Data Warehouse (Redshift): Used for storing processed metrics. Chosen for its analytical capabilities and ability to handle large datasets.
  • Metadata DB (PostgreSQL): Stores metadata about data sources, schemas, and processing jobs.

Key Tables:

  • Events Table: event_id, timestamp, user_id, event_type, attributes.
  • Metrics Table: metric_id, metric_name, value, timestamp, dimensions.

Partitioning/Sharding:

  • Events and metrics tables are partitioned by time (e.g., daily) to optimize query performance.
  • Sharding by user ID or region to distribute load evenly.

5. Deep dive

The core of this system is the metrics computation pipeline. Events are ingested via the API and pushed to Kafka. Workers consume these events to compute metrics in near-real-time and store them in the data warehouse.

sequenceDiagram
    participant E as Ingestion Service
    participant J as Kafka
    participant K as Metrics Workers
    participant G as Event Storage
    participant H as Data Warehouse

    E->>J: Publish raw events
    J->>K: Consume events
    K->>G: Store raw events
    K->>H: Compute and store metrics
Diagram

6. Scale, bottlenecks & trade-offs

Scaling:

  • Horizontal Scaling: Use sharding for the data warehouse and Kafka to handle increased load.
  • Caching: Use Redis to cache frequently accessed metrics to reduce load on the data warehouse.

Bottlenecks:

  • Ingestion Pipeline: Kafka can become a bottleneck if not scaled properly. Ensure sufficient partitions.
  • Metrics Computation: Workers need to be scaled based on event volume to maintain near-real-time processing.

Trade-offs:

  • Consistency vs. Availability: Prioritize availability for the metrics API, allowing eventual consistency in metrics computation.
  • Push vs. Pull: Use a push-based model for event ingestion to reduce load on primary databases.
  • Privacy and Access Control: Implement role-based access control and data anonymization to ensure privacy.

By carefully designing the ingestion, processing, and storage layers, this system can efficiently compute and serve analytics metrics for a conversational AI product at scale.

System designMediumBackend EngineerTechnical Screen

14. Design a small scoring component for one tennis game between two players.

The full question

Design a small scoring component for one tennis game between two players. It must record which player won each point, report a human-readable score, and identify when the game has ended and who won.

Under standard scoring, the first points are displayed as Love, 15, 30, and 40. Once both players have at least three points, equal scores are Deuce, a one-point lead is Advantage, and a two-point lead wins the game. Extend the design so another scoring policy, such as no-ad scoring at Deuce, can be selected without putting rule-specific conditionals throughout the game object.

Candidate hint: Keep the facts that happened separate from the policy that interprets those facts.

Model answer

1. Requirements & scale

Functional Requirements:

  • Record which player won each point.
  • Report the current score in a human-readable format.
  • Identify when the game has ended and who won.
  • Support multiple scoring policies (e.g., standard, no-ad scoring).

Non-Functional Requirements:

  • The system should be extensible to accommodate new scoring policies.
  • Ensure high reliability and accuracy in score reporting.
  • Maintain separation between game events and scoring policies.

Estimates:

Given that this is a component for a single tennis game, the scale is minimal. No significant storage or bandwidth concerns are anticipated. The system primarily requires efficient in-memory operations.

2. High-level architecture

flowchart TD
    subgraph Client
        A[Player Input]
    end
    
    subgraph API / Services
        B[Game Service]
        C[Scoring Policy]
    end
    
    subgraph Datastores
        D["Event Store"]
    end
    
    A -->|Point Won| B
    B -->|Store Event| D
    B -->|Fetch Events| C
    C -->|Calculate Score| B
    B -->|Report Score| A
Diagram

3. API design

  • POST /game/{gameId}/point: Record a point won by a player.
  • GET /game/{gameId}/score: Retrieve the current score of the game.
  • GET /game/{gameId}/status: Check if the game has ended and who won.

4. Data model & storage

Datastore Choice:

  • Event Store: Use an event sourcing approach to store each point as an event. This allows the system to reconstruct the game state by replaying events, supporting different scoring policies without altering the underlying data.

Key Tables/Structures:

  • Events Table:
  • gameId: Unique identifier for the game.
  • playerId: Identifier for the player who won the point.
  • timestamp: Time when the point was recorded.

5. Deep dive

The core of this design is the separation of game events from scoring policies using event sourcing. Each point won is stored as an event, and the current score is derived by applying a scoring policy to these events.

sequenceDiagram
    participant Player
    participant GameService
    participant EventStore
    participant ScoringPolicy

    Player->>GameService: Record Point (playerId)
    GameService->>EventStore: Store Event (gameId, playerId)
    Player->>GameService: Request Score
    GameService->>EventStore: Fetch Events (gameId)
    EventStore-->>GameService: List of Events
    GameService->>ScoringPolicy: Calculate Score (events)
    ScoringPolicy-->>GameService: Current Score
    GameService-->>Player: Return Score
Diagram

6. Scale, bottlenecks & trade-offs

Scalability:

  • The system is designed to handle a single game, so scalability concerns are minimal. However, the architecture supports scaling by handling multiple games concurrently if needed.

Bottlenecks:

  • The main bottleneck could be the event store if it becomes large, but given the small scale of a single game, this is unlikely to be an issue.

Trade-offs:

  • Event Sourcing: Provides a complete audit trail and flexibility to apply different scoring policies. However, it requires replaying events to compute the current state, which can be inefficient if the event list grows large. This can be mitigated by creating periodic snapshots.
  • CAP Theorem: As this is not a distributed system, CAP considerations are minimal. However, if extended to a distributed system, one might prioritize consistency and availability.
  • Policy Extensibility: By decoupling the scoring policy from the game events, the system adheres to the DRY principle, allowing easy addition of new policies without modifying existing code. This promotes maintainability and flexibility.
System designMediumBackend EngineerTake-home Project

15. Extend a library-management system with two notification workflows: A patron receives a notification 24 hours before a borrowed item is due and ano…

The full question

Extend a library-management system with two notification workflows:

  1. A patron receives a notification 24 hours before a borrowed item is due and another when it becomes due.
  2. Patrons may place holds on an item. When N copies become available, notify the first N eligible patrons in FIFO hold order.

Design the backend and the related frontend states. The workflows must be idempotent, tolerate retries and worker crashes, and have meaningful unit and integration coverage.

Model answer

1. Requirements & scale

Functional Requirements:

  • Notify patrons 24 hours before a borrowed item is due.
  • Notify patrons when a borrowed item becomes due.
  • Allow patrons to place holds on items.
  • Notify the first N eligible patrons when N copies of a held item become available.
  • Ensure notifications are idempotent and tolerate retries and worker crashes.

Non-Functional Requirements:

  • High availability and reliability.
  • Scalability to handle a growing number of patrons and items.
  • Consistent and timely notifications.

Estimates:

  • Assume 1 million patrons, each borrowing an average of 5 items.
  • Daily notifications: 2 million (1 million for 24-hour notice, 1 million for due notice).
  • Holds: Assume 10% of items have holds, leading to 500,000 hold notifications daily.
  • Total notifications per day: 2.5 million.
  • QPS (Queries per second): ~30 (2.5 million / 86,400 seconds).
  • Storage: Assume 1KB per notification, leading to 2.5GB/day.

2. High-level architecture

flowchart TD
    subgraph Client
        A[Patron App]
    end

    subgraph Edge/CDN
        B[API Gateway]
    end

    subgraph Load Balancer
        C[Load Balancer]
    end

    subgraph API / Services
        D[Notification Service]
        E[Hold Service]
    end

    subgraph Cache
        F[Redis Cache]
    end

    subgraph Datastores
        G[MySQL DB]
        H["Object Storage (S3)"]
    end

    subgraph Message Queue
        I[Kafka Queue]
    end

    subgraph Workers
        J[Notification Worker]
        K[Hold Worker]
    end

    A --> B
    B --> C
    C --> D
    C --> E
    D --> I
    E --> I
    I --> J
    I --> K
    J --> F
    K --> F
    F --> G
    G --> H
Diagram

3. API design

  • POST /notifications/due: Schedule a notification for when an item is due.
  • POST /notifications/hold: Schedule a notification for when a hold becomes available.
  • GET /holds: Retrieve the list of holds for a patron.
  • POST /holds: Place a hold on an item.
  • DELETE /holds/{holdId}: Cancel a hold.

4. Data model & storage

Datastores:

  • MySQL for relational data such as patrons, items, and holds due to its ACID properties.
  • Redis for caching notification states to ensure idempotency.
  • Kafka for message queuing to handle retries and worker crashes.

Key Tables:

  • Patron: (id, email, notification_preference)
  • Item: (id, title, due_date)
  • Hold: (id, item_id, patron_id, status, created_at)

Partition Key:

  • For the Hold table, use item_id to distribute load evenly across shards.

5. Deep dive

The core of this design is the notification workflow, which involves scheduling and sending notifications reliably.

sequenceDiagram
    participant Patron
    participant API
    participant Queue
    participant Worker
    participant Cache
    participant DB

    Patron->>API: Request to place hold
    API->>DB: Store hold
    API->>Queue: Publish hold event
    Worker->>Queue: Consume hold event
    Worker->>DB: Check available copies
    alt Copies available
        Worker->>Cache: Check notification state
        alt Not notified
            Worker->>Patron: Send notification
            Worker->>Cache: Update notification state
        end
    end
Diagram

6. Scale, bottlenecks & trade-offs

Replication & Sharding:

  • Use MySQL replication for read scalability and high availability.
  • Shard the Hold table by item_id to distribute load.

Caching:

  • Use Redis to cache notification states, reducing database load and ensuring idempotency.

Single Points of Failure:

  • Ensure redundancy in the message queue (Kafka) and workers to avoid single points of failure.

Trade-offs:

  • Consistency vs. Availability: Opt for eventual consistency in notifications to ensure high availability.
  • Push vs. Pull: Use push notifications for timely alerts but ensure retries in case of failures.
  • SQL vs. NoSQL: Use SQL for structured data and relationships, ensuring data integrity.

This design ensures that notifications are sent reliably and efficiently, even in the face of system failures or retries, while maintaining scalability and high availability.

System designMediumBackend EngineerTechnical Screen

16. Design an online chess service that supports real-time, two-player games.

The full question

Design an online chess service that supports real-time, two-player games.

Users should be able to create or join a game, make legal moves, and see their opponent's moves with low latency. Games end by checkmate, timeout (flag fall), resignation, draw (agreement, stalemate, threefold repetition, fifty-move rule, or insufficient material), or abandonment. The server is the authority on rules, move ordering, and the clock — clients are never trusted.

Your design should address, in particular:

  1. State representation & persistence — how you model and store a game's position and history.
  2. Move validation & ordering — how the server rejects illegal/out-of-turn moves and keeps the two players' views totally consistent.
  3. Clock accuracy — how each player's remaining time is tracked authoritatively, including a timeout that occurs while a player is simply thinking.
  4. Failure recovery — what happens when a client disconnects, crashes, or reconnects from a different device, and when a server-side game owner fails.
  5. Scaling — how the service handles millions of concurrent games while preserving per-game correctness.

The system must feel real-time: a move should typically reach the opponent in well under a few hundred milliseconds. State any additional assumptions you make.

Model answer

1. Requirements & scale

Functional Requirements:

  • Users can create or join a real-time, two-player chess game.
  • The server validates moves and enforces chess rules.
  • Games can end by checkmate, timeout, resignation, draw, or abandonment.
  • Players should see opponent moves with low latency.

Non-Functional Requirements:

  • Low latency communication (under 200ms per move).
  • High availability and fault tolerance.
  • Scalable to handle millions of concurrent games.

Estimates:

  • Assume 1 million concurrent games with an average move every 10 seconds: 100,000 moves per second (QPS).
  • Each game state (board position, move history) is approximately 1KB, leading to 1GB of storage for active games.
  • Bandwidth: 100,000 moves/sec * 1KB = 100MB/sec.

2. High-level architecture

flowchart TD
    subgraph Client
        A[Player 1]
        B[Player 2]
    end
    
    subgraph Edge/CDN
        C[WebSocket Server]
    end
    
    subgraph Load Balancer
        D[Load Balancer]
    end
    
    subgraph API / Services
        E[Game Service]
        F[Move Validation Service]
        G[Clock Service]
    end
    
    subgraph Cache
        H[Redis Cache]
    end
    
    subgraph Datastores
        I["SQL DB (Game State)"]
        J["NoSQL DB (Move History)"]
    end
    
    subgraph Message Queue
        K[Message Queue]
    end
    
    subgraph Workers
        L[Game State Worker]
    end
    
    A -- "Move" --> C
    B -- "Move" --> C
    C -- "WebSocket" --> D
    D -- "HTTP" --> E
    E -- "Validate Move" --> F
    F -- "Legal/Illegal" --> E
    E -- "Update Clock" --> G
    G -- "Clock Update" --> E
    E -- "Game State" --> H
    H -- "Cached State" --> E
    E -- "Persist State" --> I
    E -- "Persist Move" --> J
    E -- "Notify Players" --> K
    K -- "Game Update" --> L
    L -- "Broadcast Move" --> C
Diagram

3. API design

  • POST /games: Create a new game.
  • POST /games/{gameId}/join: Join an existing game.
  • POST /games/{gameId}/move: Submit a move.
  • GET /games/{gameId}/state: Retrieve current game state.
  • POST /games/{gameId}/end: End a game (resignation, draw).

4. Data model & storage

Datastores:

  • SQL Database for game state: Ensures ACID properties for critical game state updates.
  • NoSQL Database for move history: Efficiently stores and retrieves sequential move data.

Key Tables:

  • Games: game_id (PK), player1_id, player2_id, current_state, status, start_time, end_time.
  • Moves: move_id (PK), game_id (FK), player_id, move, timestamp.

Partition Key:

  • game_id for both Games and Moves tables to distribute load evenly.

5. Deep dive

The core challenge is ensuring real-time, consistent game state updates and move validation.

sequenceDiagram
    participant A as Player 1
    participant B as WebSocket Server
    participant C as Game Service
    participant D as Move Validation Service
    participant E as Clock Service
    participant F as Player 2

    A->>B: Send Move
    B->>C: Forward Move
    C->>D: Validate Move
    D-->>C: Move Valid/Invalid
    alt Move Valid
        C->>E: Update Clock
        E-->>C: Clock Updated
        C->>F: Notify Move
    else Move Invalid
        C->>A: Notify Invalid Move
    end
Diagram

6. Scale, bottlenecks & trade-offs

Scaling Techniques:

  • Load Balancing: Distributes incoming WebSocket connections and HTTP requests across multiple servers.
  • Sharding: Game data is sharded by game_id to ensure even distribution and parallel processing.
  • Caching: Redis is used to cache game states, reducing database load and improving response times.

Bottlenecks & Trade-offs:

  • Consistency vs. Availability: Prioritize strong consistency for game state to prevent illegal moves and ensure fair play.
  • Failure Recovery: Use a gossip protocol for decentralized failure detection and recovery, ensuring players can reconnect seamlessly.
  • Latency: WebSockets provide low-latency communication, essential for real-time updates.

This design ensures that the chess service can handle high concurrency while maintaining low latency and strong consistency, crucial for a real-time gaming experience.

TechnicalEasyBackend EngineerSecond Round

17. How do TCP and UDP differ?

Model answer

TCP and UDP are transport-layer protocols, but they make different trade-offs.

AspectTCPUDP
ConnectionConnection-oriented; establishes a connection before sending dataConnectionless; sends independent datagrams
DeliveryRetransmits lost data and delivers bytes in orderNo built-in delivery, ordering, or duplicate guarantees
ControlFlow control and congestion controlNo built-in flow or congestion control
Data modelOrdered byte stream; message boundaries are not preservedDatagram-oriented; each packet is a separate message
Overhead and latencyMore protocol state and coordinationLower overhead; can avoid connection setup
Typical usesHTTP/HTTPS, databases, file transferDNS, real-time media, games, custom protocols

A TCP connection typically performs a handshake, then exchanges sequenced data and acknowledgments. UDP sends a datagram without that connection setup; an application can add its own reliability or congestion-control logic if needed.

flowchart LR
    A[Application] --> B[TCP or UDP]
    B --> C[IP network]
    C --> D[Remote transport]
    D --> E[Remote application]
    B -. "TCP: ordered, reliable byte stream" .-> D
    B -. "UDP: independent datagrams" .-> D
Diagram

Neither choice is universally faster: TCP is often the right default for correctness, while UDP is useful when the application needs message-oriented delivery or tighter control over latency and recovery.

TechnicalEasyBackend EngineerVideo technical interview

18. What is the difference between UDP and TCP?

Model answer

  1. TCP is connection-oriented: peers establish a connection before sending application data. It provides reliable, ordered delivery, retransmitting lost data and controlling flow and congestion. This makes it a good fit when the application needs a complete, ordered byte stream, such as an API request.
  2. UDP sends independent datagrams without establishing a connection. It does not guarantee delivery, ordering, or retransmission, so applications can avoid some transport-level delay and implement only the reliability they need. It suits latency-sensitive traffic such as live audio, where a late packet may be less useful than a lost one.
  3. Trade-off: TCP's reliability and ordering are convenient, but retransmission and head-of-line blocking can add latency. UDP has less built-in overhead, but the application must handle any needed reliability, ordering, or congestion behavior responsibly.
  4. Modern nuance: HTTP/3 runs over QUIC, which uses UDP as its underlying transport. QUIC adds features such as encryption and reliable streams at the transport layer, without relying on TCP.

For example, a music streaming client might use a reliable HTTP-based connection to fetch a track segment, while real-time voice features may favor a transport that can prioritize fresh audio over retransmitting stale packets.

TechnicalEasyBackend Engineer

19. Explain polymorphism, including whether constructors and destructors can be virtual.

Model answer

Polymorphism lets code use one interface for objects of different concrete types. In C++, the key distinction is static polymorphism (chosen at compile time, such as overloads and templates) versus dynamic polymorphism (chosen at runtime through virtual functions).

struct Handler {
    virtual void handle() { /* default behavior */ }
    virtual ~Handler() = default;
};

struct LoginHandler : Handler {
    void handle() override { /* login behavior */ }
};

Handler* h = new LoginHandler;
h->handle();  // Calls LoginHandler::handle()
delete h;      // Safely calls derived, then base destructor
  • A constructor cannot be virtual: the object’s dynamic type is not established until construction completes. A base constructor can call a virtual function, but dispatch is limited to the class currently being constructed; it will not call an override in a not-yet-constructed derived class. Use a factory function when runtime-dependent construction is needed.
  • A destructor can and often should be virtual. If an object may be deleted through a base-class pointer, the base destructor must be virtual; otherwise, behavior is undefined and the derived destructor may not run. A base class not intended for polymorphic deletion can instead use a protected non-virtual destructor.
TechnicalMediumBackend Engineer

20. How would you diagnose and optimise a slow SQL query in production?

Model answer

  1. Confirm the impact and capture evidence. I’d identify the affected endpoint, query shape, time window, and whether the slowdown is broad or isolated. I’d compare p50, p95, and p99 latency, throughput, timeout and error rates, and database CPU, I/O, connections, and lock waits against a known-good baseline. I’d use query statistics and traces to find the actual expensive query rather than guessing from application latency alone.
  2. Inspect the query and its plan. I’d check the exact SQL, bind values, row counts, and execution plan. The plan can reveal a full table scan, an inefficient join order, repeated lookups, a sort or hash spilling to disk, or a large mismatch between estimated and actual rows. On production, I’d prefer a safe plan-inspection method; EXPLAIN ANALYZE executes the query and can add load, so I would only use it with appropriate safeguards.
  3. Check data and concurrency conditions. I’d look for stale statistics, skewed data, lock contention, connection-pool saturation, N+1 queries, and recent schema or traffic changes. A query can be fast in isolation but slow under contention or when it returns far more data than the caller needs.
  4. Make the smallest evidence-backed change. Depending on the plan, I might add a composite or covering index whose column order matches the filters and sort, rewrite a non-sargable predicate, reduce selected columns, change an inefficient join, or paginate results. For a Bolt trips query, for example, an index on (rider_id, created_at) may help if the request filters by rider and orders recent trips. I’d verify the read improvement against the write and storage cost of the index.
  5. Roll out and verify safely. I’d test correctness and performance with representative data, apply schema changes using an online method where possible, then canary or gradually roll out. I’d compare latency, resource use, and errors, and keep a rollback path. If one query cannot meet the latency target, I’d consider caching or asynchronous processing only after checking freshness and consistency requirements.
flowchart TD
    A[Slow endpoint report] --> B[Measure latency and database health]
    B --> C[Find query from traces and query stats]
    C --> D[Inspect SQL and execution plan]
    D --> E[Check locks data and statistics]
    E --> F[Choose targeted change]
    F --> G[Test and canary]
    G --> H{Metrics improve safely}
    H -->|Yes| I[Roll out and monitor]
    H -->|No| D
Diagram

I’d avoid adding indexes or rewriting SQL without measuring: each change should be tied to a plan-level cause and validated against production-like traffic.

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