Data Engineer interview questions & answers

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

BehavioralEasyData EngineerTechnical Screen

1. You are in the behavioral portion of an Amazon final-round interview (Software Development Engineer internship).

The full question

You are in the behavioral portion of an Amazon final-round interview (Software Development Engineer internship). Prepare strong, structured responses to the following questions using the STAR framework and Amazon's Leadership Principles where relevant. Your answers should demonstrate ownership, problem solving, collaboration, resilience under ambiguity, and clear, measurable impact.

  1. Tell me about a time you faced a significant challenge or difficult problem — at work, during an internship, in a research assignment, or on a project. How did you respond, what actions did you take, and what was the outcome?
  2. Tell me about a time your team was struggling or blocked on execution. How did you motivate the team, align people on a plan, and help drive a solution?
  3. Why do you want to join Amazon, and why is this role a good fit for your background and career goals?

Use concrete examples, explain your decisions and trade-offs, and quantify impact wherever possible.

Model answer

1. Tell me about a time you faced a significant challenge or difficult problem — at work, during an internship, in a research assignment, or on a project. How did you respond, what actions did you take, and what was the outcome?

Situation During my internship at a tech startup, I was tasked with optimizing the performance of a critical feature in our mobile app. The app was experiencing significant latency issues, which led to a poor user experience and negative feedback from our customers. As a junior developer, this was a daunting challenge, as the feature was complex and deeply integrated into the app.

Task My goal was to identify the root cause of the latency and implement a solution that would improve the app's performance by at least 30%, all within a tight two-week deadline. The key constraint was maintaining the app's existing functionality while making these improvements.

Action

  • I began by conducting a thorough analysis of the app's performance metrics to pinpoint the specific areas causing delays. I used profiling tools to gather data on memory usage and processing time.
  • After identifying that the main issue was inefficient data retrieval from the backend, I proposed a solution to implement data caching on the client side to reduce redundant network calls.
  • I collaborated with the backend team to ensure that the data caching strategy would not compromise data consistency. We agreed on a cache invalidation policy that balanced performance with up-to-date information.
  • I then implemented the caching mechanism and conducted extensive testing to ensure it worked seamlessly with the existing app features.
  • Throughout the process, I communicated regularly with my manager and the team, providing updates and seeking feedback to ensure alignment with the project goals.

Result The optimization efforts resulted in a 40% reduction in app latency, exceeding the original target. This improvement led to a significant increase in user satisfaction, as reflected in positive customer reviews and a 15% increase in user retention over the following month. This experience taught me the importance of data-driven decision-making and cross-team collaboration in solving complex technical challenges.

2. Tell me about a time your team was struggling or blocked on execution. How did you motivate the team, align people on a plan, and help drive a solution?

Situation While working on a group project during my final year at university, our team faced a major roadblock. We were developing a web application for a class assignment, but we encountered a critical bug that prevented the app from functioning correctly. The deadline was approaching, and team morale was low due to the lack of progress.

Task As the team lead, my responsibility was to motivate the team, identify a clear path forward, and ensure we delivered a working solution by the deadline. The challenge was to keep everyone focused and aligned despite the frustration and time pressure.

Action

  • I organized an emergency team meeting to openly discuss the issues and gather input from each member on potential solutions. This fostered a sense of ownership and collaboration.
  • We decided to divide the tasks based on individual strengths, with some members focusing on debugging while others worked on documentation and testing.
  • I took the lead on the debugging effort, systematically isolating the bug through a process of elimination and leveraging online resources and forums for additional insights.
  • To keep the team motivated, I set up daily check-ins to track progress and celebrate small wins, which helped maintain momentum and morale.
  • I also ensured that we communicated regularly with our professor to manage expectations and seek guidance when necessary.

Result We successfully identified and resolved the bug two days before the deadline, allowing us to complete the project on time. The final presentation was well-received, and we achieved a top grade for our work. This experience reinforced the value of clear communication, strategic task allocation, and maintaining a positive team environment under pressure.

3. Why do you want to join Amazon, and why is this role a good fit for your background and career goals?

Situation I have always admired Amazon's commitment to innovation and customer obsession, which aligns closely with my personal values and career aspirations. As a software development engineer intern, I am eager to contribute to projects that have a real-world impact and to learn from some of the best minds in the industry.

Task My goal is to leverage my technical skills and problem-solving abilities to contribute to Amazon's mission of being Earth's most customer-centric company. I am particularly drawn to the opportunity to work on scalable, high-impact projects that challenge me to grow and learn continuously.

Action

  • I have prepared for this role by gaining experience in software development through internships and academic projects, where I honed my skills in coding, debugging, and collaborating with cross-functional teams.
  • I have also familiarized myself with Amazon's Leadership Principles, which I believe are crucial for driving innovation and delivering results. I am committed to embodying these principles in my work.
  • I am particularly excited about the prospect of working on projects that involve cutting-edge technologies and require innovative solutions, as I have a strong passion for learning and being curious about new advancements.

Result Joining Amazon would be a significant step in my career, providing me with the platform to apply my skills in a dynamic environment and to contribute to projects that make a difference. I am confident that this role will not only allow me to grow professionally but also enable me to add value to Amazon's teams and customers.

BehavioralMediumData EngineerOnsite

2. For a product or feature of your choice: 1) Define 4–6 success metrics you would use to evaluate it.

The full question

For a product or feature of your choice: 1) Define 4–6 success metrics you would use to evaluate it. 2) If the primary metric suddenly drops, outline a step-by-step root-cause investigation plan. 3) Identify one leading metric you would monitor and justify why it predicts the primary outcome. 4) List the key business questions stakeholders will ask and how you would answer them analytically. 5) Propose meaningful user segments to slice the metrics and explain what each segment could reveal.

Model answer

Situation

In my role as a product manager at a tech company, I was responsible for launching a new social media feature aimed at increasing user engagement. The feature allowed users to create and share short video clips, similar to Instagram Reels. Given the competitive landscape, it was crucial to ensure the feature's success by closely monitoring its performance and impact on user engagement.

Task

My goal was to define success metrics for the feature, investigate any sudden drops in these metrics, and ensure that we could predict and address potential issues proactively. The challenge was to balance between immediate user engagement and long-term user retention.

Action

  • Defined Success Metrics: I identified six key metrics: Daily Active Users (DAU), Average Session Duration, User Retention Rate, Number of Videos Created, Share Rate (how often videos were shared), and Feature Adoption Rate (percentage of users using the feature).
  • Root-Cause Investigation Plan: If the primary metric, DAU, dropped, I planned to: 1. Analyze user feedback and reviews to identify any common complaints or issues. 2. Check for any recent changes or updates that might have affected user experience. 3. Review system logs for any technical issues or outages. 4. Conduct A/B testing to isolate potential causes. 5. Engage with customer support to gather insights from user interactions.
  • Leading Metric: I chose the Number of Videos Created as a leading metric. A decline in this metric could predict a drop in DAU, as it directly reflects user engagement and content creation, which are critical for retaining users.
  • Stakeholder Questions: Stakeholders might ask about the reasons for the metric drop, user satisfaction, and competitive positioning. I would answer by presenting data-driven insights, user feedback analysis, and competitive benchmarking to provide a comprehensive view.
  • User Segments: I proposed segmenting users by demographics (age, location), engagement level (high, medium, low), and content creators vs. consumers. Each segment could reveal different user behaviors and preferences, helping tailor strategies to enhance engagement and retention.

Result

By implementing these strategies, we were able to maintain a steady increase in user engagement and quickly address any issues that arose. The feature's adoption rate exceeded initial projections by 20%, and user retention improved by 15% over six months. This experience reinforced the importance of proactive metric monitoring and a structured approach to problem-solving.

BehavioralMediumData EngineerTechnical Screen

3. The reported pair-programming round included several SQL exercises and explicitly evaluated both collaboration and the candidate's use of AI.

The full question

The reported pair-programming round included several SQL exercises and explicitly evaluated both collaboration and the candidate's use of AI. The exact SQL prompts and tool policy were not preserved, so this question focuses only on the reported working style rather than inventing a schema.

Assume an interviewer gives you a SQL task in a shared editor and permits a coding assistant. Explain how you would collaborate with the interviewer and, if useful, use the assistant without outsourcing your reasoning. Your process should cover requirements discovery, query construction, verification, and recovery when either you or the assistant proposes something wrong.

Model answer

Situation

During a pair-programming interview at a tech company, I was tasked with solving several SQL exercises in a shared editor. The interviewer emphasized collaboration and the use of a coding assistant. My role was to demonstrate effective teamwork and problem-solving skills while leveraging AI tools appropriately. This was crucial because it tested not only my technical abilities but also my capacity to work collaboratively and adaptively in a dynamic environment.

Task

My goal was to collaboratively construct accurate SQL queries to solve the given problems while maintaining open communication with the interviewer. I needed to balance the use of AI assistance without relying on it to do the thinking for me, ensuring that my reasoning and understanding were clear and correct.

Action

  • I began by discussing the requirements with the interviewer to ensure a clear understanding of the problem. I asked clarifying questions to confirm the data structure and the expected output.
  • As we started constructing the SQL query, I proposed an initial approach based on my understanding. I explained my thought process to the interviewer, highlighting the logic behind my choices.
  • I used the coding assistant to check syntax and suggest optimizations, ensuring that I understood each suggestion before implementing it. This allowed me to leverage AI for efficiency while maintaining control over the query logic.
  • When the assistant suggested a solution that seemed incorrect, I communicated my concerns to the interviewer. We reviewed the suggestion together, discussing why it might not fit the problem requirements.
  • After agreeing on a correct approach, I ran the query and verified the results. I explained the verification process to the interviewer, detailing how I checked for accuracy against the expected outcomes.
  • When errors occurred, I took the initiative to debug by systematically reviewing each part of the query, discussing potential issues with the interviewer, and iterating on the solution.

Result

By the end of the session, we successfully completed the SQL exercises with accurate queries. The interviewer appreciated my collaborative approach and ability to use AI tools effectively without outsourcing my reasoning. This experience reinforced the importance of clear communication and critical thinking when working with both human and AI collaborators. It taught me how to balance technology use with personal expertise, ensuring that I remain an active participant in problem-solving processes.

BehavioralMediumData EngineerTechnical Screen

4. Describe a past project where you built a dashboard for business or product stakeholders.

The full question

Describe a past project where you built a dashboard for business or product stakeholders.

Explain the business goal, audience, metrics, data-quality work, how the dashboard or analysis helped identify an important problem, how you investigated root cause, what actions you took, and how stakeholder feedback improved the final outcome.

Model answer

Situation

In my role as a data analyst at a mid-sized e-commerce company, I was tasked with creating a dashboard for our product management team. The company was experiencing a plateau in sales growth, and the stakeholders needed a comprehensive view of product performance to identify potential issues. The dashboard was crucial because it would provide insights into sales trends, customer behavior, and inventory levels, enabling data-driven decision-making.

Task

My primary goal was to design and implement a dashboard that would accurately reflect key performance metrics such as sales volume, conversion rates, and inventory turnover. A critical constraint was ensuring the data's accuracy and timeliness, as stakeholders needed real-time insights to make informed decisions.

Action

  • I began by conducting interviews with product managers to understand their specific needs and the metrics that would be most valuable for them. This helped me tailor the dashboard to their requirements.
  • I collaborated with the data engineering team to ensure data pipelines were optimized for real-time data ingestion. This involved setting up ETL processes that minimized latency and ensured data accuracy.
  • To address data quality, I implemented validation checks that flagged anomalies and discrepancies in the data. This proactive approach helped maintain the integrity of the dashboard's insights.
  • I used a BI tool to design the dashboard, focusing on user-friendly visualizations that highlighted key metrics. I iterated on the design based on feedback from initial user testing sessions with stakeholders.
  • Once the dashboard was live, I conducted training sessions with the product team to ensure they could effectively interpret the data and leverage it for strategic decisions.

Result

The dashboard successfully highlighted a significant issue: certain products had high view rates but low conversion rates. This insight led us to investigate further, revealing that the product descriptions were not aligned with customer expectations. By updating the descriptions, we saw a 15% increase in conversion rates within two months.

Reflecting on the project, I learned the importance of continuous stakeholder engagement and iterative design. The feedback loop with stakeholders was invaluable in refining the dashboard to meet their evolving needs, ultimately enhancing its impact on the business.

BehavioralMediumData EngineerOnsite

5. Prepare for a hiring manager interview and a cross-functional partner conversation.

The full question

Prepare for a hiring manager interview and a cross-functional partner conversation. Be ready to answer questions such as:

  • Why do you want to join this company?
  • Why are you considering leaving your current role?
  • Describe a project you are especially proud of. Start from the problem framing, explain how you designed the solution, what your specific role was, and how you measured success.
  • Describe a project where you worked closely with a data scientist or another cross-functional partner. How did you collaborate, divide responsibilities, and handle disagreements?
  • If you were doing that project again today, what would you improve?
  • What constructive feedback has your manager given you, and how did you respond?

Answer with specific examples, clear ownership, and thoughtful reflection.

Model answer

Situation

In my previous role as a software engineer at a mid-sized tech company, I was part of a team tasked with developing a new feature for our flagship product. This feature aimed to enhance user engagement by providing personalized content recommendations. The project was high-stakes because it directly impacted user retention and satisfaction, which were key performance indicators for our business.

Task

My specific responsibility was to lead the integration of machine learning algorithms into our existing system to enable personalized recommendations. The main challenge was to ensure that the integration was seamless and did not disrupt the current user experience.

Action

  • I began by collaborating closely with our data scientist to understand the algorithms and the data requirements. We held several brainstorming sessions to align on the project goals and technical constraints.
  • I took the initiative to design a modular architecture that allowed for easy integration of the machine learning models. This involved creating APIs that could fetch user data, process it, and return recommendations in real-time.
  • To ensure smooth collaboration, we divided responsibilities based on our expertise. The data scientist focused on refining the algorithms, while I concentrated on the system integration and performance optimization.
  • We encountered disagreements on the data processing pipeline's complexity. I proposed a compromise by implementing a phased approach, starting with a simpler model to validate the concept before scaling up.
  • Throughout the project, I maintained open communication with the product manager and other stakeholders to keep them informed of our progress and any potential risks.

Result

The project was successfully completed within the deadline, and the new feature led to a 15% increase in user engagement within the first quarter of its launch. This success was a testament to our effective cross-functional collaboration and strategic planning. Reflecting on this experience, I learned the importance of flexibility and open communication in resolving technical disagreements and driving project success. If I were to do this project again, I would invest more time in user testing to gather early feedback and iterate on the solution more rapidly.

CodingEasyData EngineerTechnical Screen

6. You are asked to solve the following two coding problems.

The full question

You are asked to solve the following two coding problems.

  1. Count unique Morse code translations

You are given an array of lowercase English words, words.

Each letter maps to standard Morse code as follows:

  • a -> .-
  • b -> -...
  • c -> -.-.
  • d -> -..
  • e -> .
  • f -> ..-.
  • g -> --.
  • h -> ....
  • i -> ..
  • j -> .---
  • k -> -.-
  • l -> .-..
  • m -> --
  • n -> -.
  • o -> ---
  • p -> .--.
  • q -> --.-
  • r -> .-.
  • s -> ...
  • t -> -
  • u -> ..-
  • v -> ...-
  • w -> .--
  • x -> -..-
  • y -> -.--
  • z -> --..

The translation of a word is the concatenation of the Morse codes of its letters. For example, "cab" becomes "-.-..--..." because c -> -.-., a -> .-, and b -> -....

Return the number of distinct word translations among all words in the input array.

  1. Return all valid word-break sentences

You are given a string s and a dictionary of words wordDict.

Insert spaces into s to form all possible sentences such that every token is a word in wordDict. The same dictionary word may be reused multiple times.

Return all valid sentences in any order.

Example:

  • s = "catsanddog"
  • wordDict = ["cat", "cats", "and", "sand", "dog"]
  • Output: ["cats and dog", "cat sand dog"]

Design correct and efficient algorithms for both problems, and be prepared to discuss time and space complexity.

Model answer

// Problem 1: Count unique Morse code translations

function uniqueMorseRepresentations(words) {
    const morseCodeMap = [
        ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
        "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."
    ];
    
    const seen = new Set();
    
    for (let word of words) {
        let morseTranslation = '';
        for (let char of word) {
            morseTranslation += morseCodeMap[char.charCodeAt(0) - 'a'.charCodeAt(0)];
        }
        seen.add(morseTranslation);
    }
    
    return seen.size;
}

// Problem 2: Return all valid word-break sentences

function wordBreak(s, wordDict) {
    const wordSet = new Set(wordDict);
    const memo = new Map();
    
    function backtrack(start) {
        if (memo.has(start)) return memo.get(start);
        if (start === s.length) return [''];
        
        const sentences = [];
        
        for (let end = start + 1; end <= s.length; end++) {
            const word = s.substring(start, end);
            if (wordSet.has(word)) {
                const restOfSentences = backtrack(end);
                for (let sentence of restOfSentences) {
                    sentences.push(word + (sentence ? ' ' + sentence : ''));
                }
            }
        }
        
        memo.set(start, sentences);
        return sentences;
    }
    
    return backtrack(0);
}

// Approach for Problem 1:
// - Create a map of Morse code for each letter.
// - Use a set to store unique Morse translations of words.
// - For each word, translate it to Morse code and add to the set.
// - Return the size of the set as the count of unique translations.

// Approach for Problem 2:
// - Use a backtracking approach with memoization to explore all possible sentences.
// - For each starting index, check all substrings if they are in the word dictionary.
// - Recursively find valid sentences for the remaining string.
// - Memoize results to avoid redundant calculations.

// Complexity:
// - Problem 1: Time O(n * m), Space O(n), where n is the number of words and m is the average length of a word.
// - Problem 2: Time O(n^3), Space O(n^3), where n is the length of the string `s`.
CodingMediumData EngineerOnsite

7. In a 15-minute coding round, implement a small Python function or class to solve a well-scoped problem within about 5 minutes of coding.

The full question

In a 15-minute coding round, implement a small Python function or class to solve a well-scoped problem within about 5 minutes of coding. 1) State 1–2 clarifying questions you would ask before coding. 2) Enumerate important edge cases and how your solution handles them. 3) Provide clean, readable code and explain your formatting choices. 4) Briefly describe time and space complexity and outline a minimal test plan.

Model answer

Clarifying Questions

  1. What are the constraints on the input size? This helps determine if a more efficient algorithm is necessary.
  2. Can we assume that the input data is always valid, or do we need to handle invalid inputs?

Edge Cases

  • Empty Input: Ensure the function handles cases where input is empty or null.
  • Single Element: Consider how the function behaves with the smallest non-empty input.
  • Large Numbers: Check if the function can handle very large numbers without overflow.
  • Negative Numbers: If applicable, ensure the function correctly processes negative numbers.

Code Implementation

def find_maximum_subarray_sum(arr):
    # Initialize variables to store the maximum sum and current sum
    max_sum = float('-inf')
    current_sum = 0
    
    for num in arr:
        # Update the current sum by adding the current number
        current_sum += num
        
        # Update max_sum if current_sum is greater
        if current_sum > max_sum:
            max_sum = current_sum
        
        # Reset current_sum to zero if it becomes negative
        if current_sum < 0:
            current_sum = 0
    
    return max_sum

# Example usage:
# print(find_maximum_subarray_sum([1, -2, 3, 4, -1, 2, 1, -5, 4]))  # Output: 10
  • Formatting Choices: The code is structured with clear variable names (max_sum, current_sum) and comments to enhance readability. The loop iterates through each element, maintaining a running sum and updating the maximum found so far.

Complexity

  • Time Complexity: O(n), where n is the number of elements in the array. The algorithm iterates through the array once.
  • Space Complexity: O(1), as it uses a constant amount of additional space regardless of input size.

Test Plan

  1. Empty Array: find_maximum_subarray_sum([]) should return 0 or handle gracefully.
  2. Single Element: find_maximum_subarray_sum([5]) should return 5.
  3. All Negative Numbers: find_maximum_subarray_sum([-1, -2, -3]) should return -1.
  4. Mixed Positive and Negative: find_maximum_subarray_sum([1, -2, 3, 4, -1, 2, 1, -5, 4]) should return 10.
  5. Large Input: Test with a large array to ensure performance constraints are met.

This solution uses Kadane's algorithm to efficiently find the maximum subarray sum, balancing between functional and imperative programming for optimal performance.

CodingMediumData EngineerSecond technical round

8. Write SQL queries involving ranking and top-N results.

Model answer

// Rank employees by salary within each department.
// rank: ties share a rank, with gaps; denseRank: ties share a rank, no gaps.
// rowNumber: every row receives a unique position.
const employees = [
  { id: 1, name: "Asha", department: "Ops", salary: 90000 },
  { id: 2, name: "Ben", department: "Ops", salary: 80000 },
  { id: 3, name: "Chen", department: "Ops", salary: 80000 },
  { id: 4, name: "Diya", department: "Ops", salary: 70000 },
  { id: 5, name: "Eli", department: "Data", salary: 95000 },
  { id: 6, name: "Fatima", department: "Data", salary: 85000 },
  { id: 7, name: "Gus", department: "Data", salary: 85000 },
];

function rankByGroup(rows, groupKey, scoreKey) {
  const groups = new Map();
  for (const row of rows) {
    const key = row[groupKey];
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(row);
  }

  const result = [];
  for (const [group, items] of groups) {
    // Use id as a stable tie-breaker for rowNumber ordering.
    items.sort((a, b) => b[scoreKey] - a[scoreKey] || a.id - b.id);
    let rank = 0;
    let denseRank = 0;
    let previousScore;

    items.forEach((item, index) => {
      if (index === 0 || item[scoreKey] !== previousScore) {
        rank = index + 1;
        denseRank += 1;
      }
      previousScore = item[scoreKey];
      result.push({ ...item, rank, denseRank, rowNumber: index + 1 });
    });
  }
  return result;
}

const ranked = rankByGroup(employees, "department", "salary");

// Top 2 ranks per department, including all ties at rank 2.
const topTwoRanks = ranked.filter((employee) => employee.rank <= 2);

// Exactly 2 rows per department, using the stable tie-breaker.
const topTwoRows = ranked.filter((employee) => employee.rowNumber <= 2);

console.log("Top two ranks, including ties:", topTwoRanks);
console.log("Exactly two rows:", topTwoRows);
  • rank matches SQL RANK() semantics; denseRank matches DENSE_RANK(); rowNumber matches ROW_NUMBER().
  • Filtering by rank includes ties, while filtering by row number returns a fixed number of rows. A stable tie-breaker makes the latter deterministic.
  • Complexity: Time O(n log n) for sorting; space O(n) for grouped and ranked results.
CodingMediumData EngineerTechnical Screen

9. You are given a small library system with the following relational schema and several Python data-processing tasks.

The full question

You are given a small library system with the following relational schema and several Python data-processing tasks. Answer the SQL questions and implement the described Python functions.

---

Part 1: SQL Questions

Assume the following tables:

Table: Books

  • book_id INT, primary key
  • title VARCHAR
  • condition ENUM('good', 'damaged', 'lost') — current physical condition of the book copy
  • copies INT — number of physical copies the library owns for this title
  • lifetime_value DECIMAL — total revenue (e.g., rental fees) generated by this title over its lifetime

Table: Loans

  • loan_id INT, primary key
  • book_id INT, foreign key to Books(book_id)
  • member_id INT, foreign key to Members(member_id)
  • loaned_at DATETIME
  • returned_at DATETIME NULL — NULL means the book has not yet been returned

Table: Members

  • member_id INT, primary key
  • invited_by INT NULL, foreign key to Members(member_id) — the member who invited this member, if any
  • reserved_copies INT — number of book copies this member currently has reserved

Write SQL queries for the following:

  1. Count good, not-yet-returned books

Return a single integer: the number of book loans where the book is in condition = 'good' and the book has not yet been returned (i.e., the corresponding Loans.returned_at is NULL).

  1. Top 3 high-value books with many copies

Return the top 3 books (their book_id and title) that have:

  • more than 10 copies (copies > 10), and
  • the highest lifetime_value among such books.

Order results by lifetime_value descending, and if needed, break ties by book_id ascending. Limit the result to 3 rows.

  1. Largest absolute difference in reserved copies between inviter and invitee

For each member who was invited by another member (invited_by is not NULL), consider the pair:

  • the inviter: Members.member_id = invited_by
  • the invitee: Members.member_id (the one who was invited)

Each member has a reserved_copies value. For every inviter–invitee pair, compute the absolute difference:

\[ |\text{inviter.reserved_copies} - \text{invitee.reserved_copies}| \]

Write a query that returns a single row with a single column giving the maximum such absolute difference over all valid inviter–invitee pairs.

---

Part 2: Python Coding Questions

Implement the following functions in Python. Aim for efficient, readable solutions.

Python Q1: Maximum reading score without consecutive books

You are given a list of non-negative integers scores, where scores[i] is the number of points a student earns by reading the *i*-th book in a sequence. The student may choose to read any subset of books, but cannot read two adjacent books in the sequence (they need rest between adjacent books).

Write a function:

from typing import List

def max_reading_score(scores: List[int]) -> int:
"""Return the maximum total score achievable without reading adjacent books."""

Constraints:

  • 0 <= len(scores) <= 10**5
  • 0 <= scores[i] <= 10**4

The function should return the maximum possible total score.

---

Python Q2: Validate a sequence of open/close log entries

You are given a list of log entries representing operations on resources. Each entry is a tuple (action, resource_id) where:

  • action is a string: either 'OPEN' or 'CLOSE'
  • resource_id is a string identifying the resource

A log is considered valid if all of the following hold:

  • A resource cannot be closed before it has been opened.
  • A resource cannot be opened twice in a row without being closed in between.
  • At the end of the log, all opened resources must have been closed (no resource remains open).

Write a function:

from typing import List, Tuple

def is_log_valid(logs: List[Tuple[str, str]]) -> bool:
"""Return False if the log sequence is inconsistent; True otherwise."""

Return False if the log does not make sense according to the above rules; otherwise return True.

Constraints:

  • 0 <= len(logs) <= 10**5

---

Python Q3: Count employees at each open office

You are given a list of office objects and a set of office IDs that are closed.

Assume offices are represented as:

from typing import List, Dict, Set

Office = Dict[str, object] # keys: "id" (int), "employees" (List[Dict[str, object]])

Each Office dictionary has:

  • "id": int — office identifier
  • "employees": List[Dict[str, object]] — a list of employee objects assigned to that office (you do not need to inspect the employee fields; just count how many there are).

You are also given a set closed_office_ids: Set[int] containing the IDs of offices that are closed.

Write a function:

from typing import Dict

def count_employees_by_open_office(
offices: List[Office], closed_office_ids: Set[int]
) -> Dict[int, int]:
"""Return a mapping from office_id to employee count for offices that are open."""

The function should:

  • Ignore any office whose id is in closed_office_ids.
  • For every remaining (open) office, compute how many employees it has by taking len(office["employees"]).
  • Return a dictionary mapping office_id (int) to that employee count (int) for only the open offices.

You may assume:

  • Office IDs are unique within offices.
  • 0 <= len(offices) <= 10**4.

---

Python Q4: Merge two strings to create a new name

You are given two non-empty strings a and b. Create a new string by alternating characters from a and b, starting with a. When one string runs out of characters, append the remaining characters from the other string.

For example:

  • a = "abc", b = "XYZ" → result: "aXbYcZ"
  • a = "ab", b = "WXYZ" → result: "aWbXYZ"

Write a function:

def merge_names(a: str, b: str) -> str:
"""Return a new string formed by alternating characters from a and b."""

Assume:

  • 1 <= len(a), len(b) <= 10**5.

Model answer

-- Part 1: SQL Questions

-- 1. Count good, not-yet-returned books
SELECT COUNT(*) AS count
FROM Loans
JOIN Books ON Loans.book_id = Books.book_id
WHERE Books.condition = 'good' AND Loans.returned_at IS NULL;

-- 2. Top 3 high-value books with many copies
SELECT book_id, title
FROM Books
WHERE copies > 10
ORDER BY lifetime_value DESC, book_id ASC
LIMIT 3;

-- 3. Largest absolute difference in reserved copies between inviter and invitee
SELECT MAX(ABS(inviter.reserved_copies - invitee.reserved_copies)) AS max_difference
FROM Members AS inviter
JOIN Members AS invitee ON inviter.member_id = invitee.invited_by
WHERE invitee.invited_by IS NOT NULL;
from typing import List

def max_reading_score(scores: List[int]) -> int:
    """Return the maximum total score achievable without reading adjacent books."""
    if not scores:
        return 0

    n = len(scores)
    if n == 1:
        return scores[0]

    # Initialize dp array
    dp = [0] * n
    dp[0] = scores[0]
    dp[1] = max(scores[0], scores[1])

    for i in range(2, n):
        dp[i] = max(dp[i-1], dp[i-2] + scores[i])

    return dp[-1]

def is_log_valid(logs: List[Tuple[str, str]]) -> bool:
    """Return False if the log sequence is inconsistent; True otherwise."""
    opened = set()

    for action, resource_id in logs:
        if action == 'OPEN':
            if resource_id in opened:
                return False  # Cannot open twice without closing
            opened.add(resource_id)
        elif action == 'CLOSE':
            if resource_id not in opened:
                return False  # Cannot close without opening
            opened.remove(resource_id)

    return len(opened) == 0  # All opened resources must be closed

def count_employees_by_open_office(
    offices: List[Dict[str, object]], closed_office_ids: Set[int]
) -> Dict[int, int]:
    """Return a mapping from office_id to employee count for offices that are open."""
    employee_count = {}

    for office in offices:
        if office["id"] not in closed_office_ids:
            employee_count[office["id"]] = len(office["employees"])

    return employee_count

def merge_names(a: str, b: str) -> str:
    """Return a new string formed by alternating characters from a and b."""
    result = []
    length_a, length_b = len(a), len(b)
    min_length = min(length_a, length_b)

    for i in range(min_length):
        result.append(a[i])
        result.append(b[i])

    # Append remaining characters
    result.append(a[min_length:])
    result.append(b[min_length:])

    return ''.join(result)
  • Approach:
  • SQL queries utilize JOINs and aggregate functions to derive insights from the library schema.
  • Python functions leverage dynamic programming for score calculation, set operations for log validation, and straightforward iterations for counting employees and merging strings.

Complexity:

  • SQL: O(n) for each query where n is the number of rows in the relevant tables.
  • Python:
  • max_reading_score: O(n)
  • is_log_valid: O(n)
  • count_employees_by_open_office: O(m) where m is the number of offices.
  • merge_names: O(max(len(a), len(b)))
CodingMediumData EngineerTechnical Screen

10. The technical interview included two coding-style tasks: a SQL analytics query and merging two sorted linked lists.

Model answer

// Definition for singly-linked list.
function ListNode(val, next = null) {
  this.val = val;
  this.next = next;
}

function mergeTwoLists(l1, l2) {
  // Create a dummy node to act as the start of the merged list
  let dummy = new ListNode(-1);
  // This will be our current node in the new list
  let current = dummy;

  // Traverse both lists
  while (l1 !== null && l2 !== null) {
    // Compare the values in the current nodes of both lists
    if (l1.val < l2.val) {
      // If l1's value is smaller, attach it to the merged list
      current.next = l1;
      l1 = l1.next; // Move to the next node in l1
    } else {
      // If l2's value is smaller or equal, attach it to the merged list
      current.next = l2;
      l2 = l2.next; // Move to the next node in l2
    }
    // Move to the next node in the merged list
    current = current.next;
  }

  // If one of the lists is not empty, attach it to the end of the merged list
  if (l1 !== null) {
    current.next = l1;
  } else if (l2 !== null) {
    current.next = l2;
  }

  // Return the merged list, which starts at dummy.next
  return dummy.next;
}
  • Approach:
  • Use a dummy node to simplify edge cases and maintain a reference to the head of the merged list.
  • Traverse both linked lists simultaneously, comparing the current nodes.
  • Append the smaller node to the merged list and move the pointer of that list forward.
  • Once one list is exhausted, append the remaining nodes of the other list.
  • Complexity:
  • Time: O(n + m), where n and m are the lengths of the two lists. Each node is processed exactly once.
  • Space: O(1), as we are only using a few extra pointers and not creating new nodes except for the dummy node.
System designEasyData EngineerTechnical Screen

11. Design a highly scalable URL shortening service (like bit.ly / TinyURL) that converts long URLs into short links and supports redirection.

The full question

Design a highly scalable URL shortening service (like bit.ly / TinyURL) that converts long URLs into short links and supports redirection. Cover the architecture, data model, short-code generation, uniqueness, caching, scaling, and operational concerns below.

  1. Functional requirements
  • Provide an API to create a short URL for a given long URL.
  • Provide an API to redirect (resolve) a short code back to the original long URL.
  • The mapping must be globally unique (no unintended collisions) and reversible (given a short code, you can always retrieve the original URL via lookup).
  1. Non-functional requirements & assumptions
  • High availability and high QPS, with reads/redirects typically far outnumbering writes.
  • Support horizontal scaling across multiple instances/regions.
  • Short codes should be as short as possible (e.g., 6–10 characters) and URL-safe.
  • Low redirect latency (e.g., p95 < 50 ms); the service must tolerate partial failures.
  • State any other assumptions you need.
  1. APIs
  • Define example endpoints for creating short links and performing redirects (request/response shapes, status codes).
  1. Data model & storage
  • What you store per short link (e.g., short_code, long_url, created_at, expiry, owner_id).
  • Choice of datastore(s): KV store vs relational DB vs both, and why.
  1. Short-code generation strategy
  • Option A: hash the long URL.
  • Option B: generate globally unique IDs (e.g., Snowflake / auto-increment) and Base62-encode them.
  • How you ensure uniqueness and performance under concurrency.
  1. Guaranteeing global uniqueness across multiple instances/regions.
  2. Caching & performance
  • Use of in-memory cache (e.g., Redis) and/or CDN for hot links.
  • Cache key design, TTL, and cache-miss behavior.
  1. Scalability & reliability
  • Partitioning/sharding strategy.
  • Replication, failover, and consistency trade-offs.
  1. Operational concerns
  • Abuse prevention (rate limits), observability/metrics, link expiration, and analytics logging (optional).
  1. Follow-up: If you use a hash of the long URL to generate the short code, how do you detect and handle hash collisions? Provide at least two approaches and their trade-offs.

Model answer

1. Requirements & scale

Functional Requirements:

  • API to create a short URL for a given long URL.
  • API to redirect a short code back to the original long URL.
  • Mapping must be globally unique and reversible.

Non-Functional Requirements:

  • High availability and high QPS, with reads/redirects far outnumbering writes.
  • Support horizontal scaling across multiple instances/regions.
  • Short codes should be 6–10 characters, URL-safe.
  • Low redirect latency (p95 < 50 ms) and tolerance for partial failures.

Estimates:

  • Assume 1 million users, each generating 10 links/month.
  • QPS: 1 million links / 30 days / 24 hours / 60 minutes / 60 seconds ≈ 1.16 QPS.
  • Storage: Each URL mapping takes ~200 bytes. For 1 million links, ~200 MB storage required.

2. High-level architecture

flowchart TD
    subgraph Client
        A["User Interface"]
    end

    subgraph Edge/CDN
        B["CDN"]
    end

    subgraph Load_Balancer
        C["Load Balancer"]
    end

    subgraph API_Services
        D["API Gateway"]
        E["Short URL Service"]
        F["Redirect Service"]
    end

    subgraph Cache
        G["In-Memory Cache (Redis)"]
    end

    subgraph Datastores
        H["NoSQL Database (DynamoDB)"]
    end

    subgraph Message_Queue
        I["Message Queue (Kafka)"]
    end

    A -->|Create Short URL| C
    A -->|Redirect| C
    C -->|API Requests| D
    D -->|Create Short URL| E
    D -->|Redirect| F
    E -->|Store Mapping| H
    F -->|Lookup Mapping| H
    F -->|Cache Lookup| G
    G -->|Cache Miss| I
Diagram

3. API design

Endpoints:

  1. Create Short URL - Method: POST - Path: /api/shorten - Request Body: { "long_url": "http://example.com" } - Response: { "short_code": "abc123", "long_url": "http://example.com" } - Status Codes: 201 Created, 400 Bad Request
  2. Redirect to Long URL - Method: GET - Path: /api/redirect/{short_code} - Response: { "long_url": "http://example.com" } - Status Codes: 302 Found, 404 Not Found

4. Data model & storage

Data Model:

  • short_code: Unique identifier for the short URL.
  • long_url: Original long URL.
  • created_at: Timestamp of creation.
  • expiry: Optional expiration date.
  • owner_id: Optional user identifier.

Datastore Choice:

  • NoSQL Database (DynamoDB): For scalability and flexibility with schema.
  • In-Memory Cache (Redis): For fast access to frequently used short URLs.

5. Short-code generation strategy

Option B: Generate Globally Unique IDs

  • Use a unique ID generator (e.g., Snowflake) and Base62 encode it.
  • Ensures uniqueness across distributed instances.

Concurrency Handling:

  • Use atomic operations in the database to ensure no collisions occur during writes.

6. Guaranteeing global uniqueness

  • Use a centralized service for ID generation (e.g., Snowflake) to ensure unique IDs across instances.
  • Implement a distributed lock mechanism or database transactions to prevent race conditions.

7. Caching & performance

In-Memory Cache:

  • Use Redis to cache frequently accessed short URL mappings.
  • Cache Key Design: short_code as the key.
  • TTL: Set to 1 hour for hot links.
  • Cache Miss Behavior: On a cache miss, fetch from the database and update the cache.

8. Scalability & reliability

Partitioning/Sharding Strategy:

  • Use hash-based sharding on short_code to distribute load across multiple database instances.

Replication & Failover:

  • Implement multi-region replication for the database.
  • Use a failover mechanism to switch to a backup instance in case of failure.

Consistency Trade-offs:

  • Prioritize availability over consistency (eventual consistency model).

9. Operational concerns

  • Abuse Prevention: Implement rate limiting on API endpoints.
  • Observability/Metrics: Monitor API usage and response times using tools like Prometheus.
  • Link Expiration: Allow users to set expiration dates for short links.
  • Analytics Logging: Track click-through rates and user engagement.

10. Handling hash collisions

Approach 1: Linear Probing

  • If a collision occurs, incrementally check the next available slot until an empty one is found.
  • Trade-off: Simple but may lead to performance degradation under high load.

Approach 2: Hashing with a Salt

  • Append a random salt to the long URL before hashing to reduce collision probability.
  • Trade-off: Increases complexity and requires storage for the salt but significantly reduces collision chances.
System designMediumData EngineerTechnical Screen

12. You are interviewing for a Data Solutions Architect role.

The full question

You are interviewing for a Data Solutions Architect role. A customer is using a cloud data platform (e.g., Databricks on AWS/Azure/GCP) and reports:

  • Data quality issues (incorrect/missing/duplicated records, inconsistent definitions)
  • Performance issues (slow ETL/ELT pipelines, long query times, high compute cost)

They ask: “We’re struggling with data quality and performance—how would you approach this?”

Tasks

  1. Discovery & scoping: What questions do you ask to clarify the problem and constraints?
  2. Define success: What metrics would you use for (a) data quality and (b) performance/cost? Include primary metrics and guardrails.
  3. Diagnosis plan: Describe a step-by-step approach to identify root causes (data sources, pipeline stages, storage layer, compute, governance).
  4. Solution proposal: Propose concrete technical and process changes to:
  • Improve data quality (validation, monitoring, ownership, SLAs)
  • Improve performance (storage layout, compute configuration, pipeline design)
  1. Concept check: Explain the differences between a data lake and a data warehouse, and where a lakehouse fits.
  2. Cloud considerations: What cloud concepts commonly matter in these engagements (e.g., security/IAM, networking, storage, encryption, cost)?

Deliverable

Provide a structured plan you could present to the customer (bullets are fine), including short-term mitigations and longer-term architecture/process recommendations.

Model answer

1. Requirements & scale

Functional Requirements:

  • Ensure data quality by addressing incorrect, missing, and duplicated records.
  • Optimize performance for ETL/ELT pipelines and query execution.
  • Reduce compute costs while maintaining or improving performance.

Non-Functional Requirements:

  • High availability and reliability of data processing.
  • Scalability to handle increasing data volumes and user queries.
  • Security and compliance with data governance standards.

Back-of-the-Envelope Estimates:

  • Data Volume: Assume 1 TB of data ingested daily.
  • Query Load: Assume 1000 queries per second (QPS) at peak.
  • Storage: Assuming data retention for 1 year, total storage required is approximately 365 TB.
  • Bandwidth: If each query processes 10 MB of data, bandwidth required is 10 GB/s.

2. High-level architecture

flowchart TD
    subgraph Client
        A[User]
    end

    subgraph Edge/CDN
        B[CDN]
    end

    subgraph Load Balancer
        C[Load Balancer]
    end

    subgraph API / Services
        D[API Gateway]
        E[Data Quality Service]
        F[Performance Monitoring Service]
    end

    subgraph Cache
        G[Redis Cache]
    end

    subgraph Datastores
        H["Data Lake (S3)"]
        I["Data Warehouse (Redshift)"]
    end

    subgraph Message Queue
        J[Kafka]
    end

    subgraph Workers
        K[ETL Workers]
        L[Data Validation Workers]
    end

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

3. API design

  • POST /data/ingest: Ingest new data into the system.
  • GET /data/query: Execute queries against the data warehouse.
  • POST /data/validate: Trigger data validation processes.
  • GET /performance/metrics: Retrieve performance metrics for monitoring.

4. Data model & storage

Datastores:

  • Data Lake (S3): For raw data storage, allowing schema-on-read flexibility.
  • Data Warehouse (Redshift): For structured data storage and fast query execution.

Key Tables:

  • Raw Data Table: Stores ingested data with minimal transformation.
  • Validated Data Table: Stores data post-validation, ensuring quality.
  • Metrics Table: Stores performance metrics for monitoring and analysis.

Partitioning Strategy:

  • Partition data by date and source to optimize query performance and manageability.

5. Deep dive

To address data quality issues, implement a robust data validation pipeline. This involves:

  1. Data Ingestion: Use Kafka to handle high-throughput data ingestion, ensuring durability and backpressure management.
  2. Data Validation: Employ Data Validation Workers to check for duplicates, missing values, and consistency against predefined schemas.
  3. Storage: Store validated data in the Data Warehouse for efficient querying.
sequenceDiagram
    participant User
    participant API Gateway
    participant Data Quality Service
    participant Kafka
    participant Data Validation Workers
    participant Data Warehouse

    User->>API Gateway: POST /data/ingest
    API Gateway->>Data Quality Service: Validate Data
    Data Quality Service->>Kafka: Publish Validated Data
    Kafka->>Data Validation Workers: Consume Data
    Data Validation Workers->>Data Warehouse: Store Validated Data
Diagram

6. Scale, bottlenecks & trade-offs

Replication and Sharding:

  • Replication: Use database replicas to ensure high availability and load distribution.
  • Sharding: Implement sharding in the Data Warehouse to handle large data volumes efficiently.

Caching:

  • Use Redis to cache frequently accessed query results, reducing load on the Data Warehouse and improving response times.

Single Points of Failure:

  • Ensure redundancy in the Load Balancer and API Gateway to prevent single points of failure.

Trade-offs:

  • Consistency vs. Availability: Opt for eventual consistency in the Data Lake to improve availability and performance.
  • Push vs. Pull: Use a pull-based approach for data validation to allow for batch processing and reduced latency.
  • SQL vs. NoSQL: Use SQL for structured data and complex queries, while leveraging NoSQL for flexible schema requirements in the Data Lake.

By addressing these aspects, we can enhance data quality and performance, ensuring the system is robust, scalable, and cost-effective.

System designMediumData EngineerTechnical Screen

13. Design a platform that collects GPU telemetry from a large compute environment and exposes both high-level trend analytics and low-level drilldowns.

The full question

Design a platform that collects GPU telemetry from a large compute environment and exposes both high-level trend analytics and low-level drilldowns.

The interviewer gives these requirements:

  • A collector process must ingest telemetry at both 30-second resolution and 1-second resolution.
  • Operators need a dashboard showing three-month trends.
  • Operators must also drill down to per-GPU, per-second details when investigating incidents.
  • The same analytics environment may later expose a natural-language SQL assistant. The assistant must only query data the user is allowed to access and must avoid dangerous or extremely expensive generated queries.

Model answer

1. Requirements & scale

Functional Requirements:

  • Collect GPU telemetry data at two resolutions: 30-second and 1-second intervals.
  • Provide a dashboard for operators to view three-month trends.
  • Allow operators to drill down into per-GPU, per-second telemetry data.
  • Support a natural-language SQL assistant that queries data securely and efficiently.

Non-Functional Requirements:

  • High throughput and low-latency data ingestion.
  • Scalable storage to handle large volumes of time-series data.
  • Secure access control for data queries.
  • Reliable and fault-tolerant system design.

Scale Estimates:

  • Assume 10,000 GPUs, each generating telemetry data every second.
  • Data size per telemetry record: 1 KB.
  • Ingestion rate: 10,000 records/second = 10 MB/second.
  • Monthly data storage: 10 MB/second 86,400 seconds/day 30 days ≈ 25.9 TB/month.
  • Three-month storage requirement: 77.7 TB.

2. High-level architecture

flowchart TD
    subgraph Client
        A[Dashboard]
        B[Natural Language SQL Assistant]
    end

    subgraph Edge/CDN
        C[CDN]
    end

    subgraph Load Balancer
        D[Load Balancer]
    end

    subgraph API / Services
        E[Telemetry Ingestion API]
        F[Analytics Service]
        G[Auth Service]
    end

    subgraph Cache
        H[In-memory Cache]
    end

    subgraph Datastores
        I[Time-series DB]
        J[SQL DB]
    end

    subgraph Message Queue
        K[Message Queue]
    end

    subgraph Workers
        L[Stream Processor]
    end

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

3. API design

  • POST /telemetry: Ingest telemetry data from GPUs.
  • GET /analytics/trends: Retrieve high-level trend analytics for the dashboard.
  • GET /analytics/drilldown: Fetch detailed per-GPU telemetry data.
  • POST /auth: Authenticate users for secure access.
  • POST /query: Execute natural-language SQL queries with access control.

4. Data model & storage

Datastores:

  • Time-series Database (e.g., InfluxDB, TimescaleDB): Chosen for efficient storage and querying of time-series data. Supports high write throughput and time-based queries.
  • SQL Database (e.g., PostgreSQL): Used for metadata and access control data, supporting complex queries and transactions.

Key Tables:

  • TelemetryData: (timestamp, gpu_id, metrics)
  • UserAccess: (user_id, permissions)

Partitioning Strategy:

  • TelemetryData: Partitioned by time (e.g., daily) and GPU ID for efficient querying and storage management.

5. Deep dive

The core of this design is the telemetry ingestion and processing pipeline. The system must handle high-throughput data ingestion while ensuring data reliability and low latency for real-time analytics.

sequenceDiagram
    participant GPU as GPU Device
    participant E as Telemetry Ingestion API
    participant K as Message Queue
    participant L as Stream Processor
    participant I as Time-series DB

    GPU->>E: Send telemetry data
    E->>K: Publish to message queue
    K->>L: Stream data for processing
    L->>I: Write processed data to time-series DB
Diagram

Key Considerations:

  • Backpressure Handling: The message queue decouples ingestion from processing, allowing the system to handle spikes in data volume.
  • Stream Processing: The stream processor aggregates and enriches telemetry data, ensuring it is ready for both real-time and historical analysis.

6. Scale, bottlenecks & trade-offs

Replication and Sharding:

  • Time-series DB: Use replication for high availability and sharding to distribute load across multiple nodes.
  • Message Queue: Scale horizontally to handle increased data ingestion rates.

Caching:

  • In-memory Cache: Store frequently accessed trend data to reduce query latency and load on the database.

Single Points of Failure:

  • Load Balancer and Message Queue: Ensure redundancy and failover mechanisms to prevent service disruption.

Trade-offs:

  • Consistency vs. Availability: Prioritize availability using eventual consistency for telemetry data, as real-time insights are more critical than immediate consistency.
  • Push vs. Pull: Use a push-based model for telemetry ingestion to reduce latency and ensure timely data processing.

This design balances the need for real-time analytics with the scalability and reliability required to handle large volumes of telemetry data.

System designMediumData EngineerTechnical Screen

14. The interview report mentioned detailed questions about the candidate's batch- and stream-processing experience, but it did not preserve an exact s…

The full question

The interview report mentioned detailed questions about the candidate's batch- and stream-processing experience, but it did not preserve an exact scenario. The following is a self-contained practice reconstruction of that topic.

You are designing a data platform for an online marketplace. Order lifecycle events arrive continuously and may be duplicated, delayed, or delivered out of order. Product teams need operational metrics within five minutes, while the finance team needs a reproducible daily table by the following morning. Historical corrections and event-schema changes are expected.

Explain whether you would use batch processing, stream processing, or a hybrid design. Describe the end-to-end architecture and how it would produce both low-latency metrics and an auditable daily result.

Model answer

1. Requirements & scale

Functional Requirements:

  • Continuously ingest order lifecycle events.
  • Provide operational metrics within five minutes.
  • Generate a reproducible daily table for the finance team.
  • Handle duplicated, delayed, and out-of-order events.
  • Support historical corrections and event-schema changes.

Non-Functional Requirements:

  • Low-latency processing for near real-time metrics.
  • High reliability and fault tolerance.
  • Scalability to handle increasing event volumes.
  • Data consistency for financial reporting.

Estimates:

  • Assume 10,000 orders per second (QPS) at peak.
  • Each event is approximately 1 KB, leading to 10 MB/s of incoming data.
  • Daily data storage: 10 MB/s * 86,400 seconds/day ≈ 864 GB/day.

2. High-level architecture

flowchart TD
    subgraph Client
        A[Order Event Producers]
    end

    subgraph Edge/CDN
        B[Event Gateway]
    end

    subgraph Load Balancer
        C[Load Balancer]
    end

    subgraph API / Services
        D[Stream Processor]
        E[Batch Processor]
    end

    subgraph Cache
        F[In-memory Cache]
    end

    subgraph Datastores
        G[Real-time Metrics DB]
        H[Data Lake]
    end

    subgraph Message Queue
        I[Event Queue]
    end

    subgraph Workers
        J[Data Transformation Workers]
    end

    A --> B["Order Events"]
    B --> C["Order Events"]
    C --> I["Order Events"]
    I --> D["Stream Processing"]
    D --> F["Processed Metrics"]
    F --> G["Real-time Metrics"]
    I --> E["Batch Processing"]
    E --> J["Data Transformation"]
    J --> H["Daily Table"]
Diagram

3. API design

  • POST /events: Ingest order lifecycle events into the system.
  • GET /metrics: Retrieve real-time operational metrics.
  • GET /daily-report: Access the daily financial report.

4. Data model & storage

Datastores:

  • Real-time Metrics DB: A NoSQL database like Apache Cassandra for fast writes and reads, supporting real-time metrics.
  • Data Lake: A distributed file system like Amazon S3 or Hadoop HDFS for storing raw and processed data, supporting batch processing.

Key Tables:

  • OrderEvents: Partitioned by event timestamp for efficient querying.
  • Metrics: Sharded by metric type and timestamp for real-time access.
  • DailyReports: Stored as Parquet files for efficient batch processing and querying.

5. Deep dive

The core of this design is the hybrid processing approach that combines stream and batch processing to meet both low-latency and high-reliability requirements.

sequenceDiagram
    participant A as Event Gateway
    participant B as Event Queue
    participant C as Stream Processor
    participant D as Batch Processor
    participant E as Real-time Metrics DB
    participant F as Data Lake

    A->>B: Ingest Order Events
    B->>C: Stream Processing
    C->>E: Update Real-time Metrics
    B->>D: Batch Processing
    D->>F: Store Daily Table
Diagram

Stream Processing:

  • Utilizes a stream processing framework like Apache Kafka Streams or Apache Flink.
  • Processes events in real-time to update operational metrics.
  • Handles event deduplication and ordering using event timestamps and unique identifiers.

Batch Processing:

  • Uses a batch processing framework like Apache Spark.
  • Processes accumulated events overnight to generate the daily financial table.
  • Supports schema evolution and historical data corrections.

6. Scale, bottlenecks & trade-offs

Scalability:

  • Stream processing scales horizontally by adding more processing nodes.
  • Batch processing can be scaled by increasing the cluster size or using more powerful instances.

Bottlenecks:

  • The event queue could become a bottleneck if not properly scaled; use partitioning to distribute load.
  • Real-time metrics DB must handle high write throughput; consider using a distributed NoSQL database.

Trade-offs:

  • Consistency vs. Availability: Prioritize availability in stream processing for real-time metrics, while ensuring eventual consistency for daily reports.
  • Latency vs. Accuracy: Real-time metrics may sacrifice some accuracy for speed, while daily reports focus on accuracy.
  • Push vs. Pull: Stream processing uses a push model for low latency, whereas batch processing uses a pull model for comprehensive data analysis.

By leveraging both stream and batch processing, this architecture effectively balances the need for low-latency metrics and reliable, auditable daily reports, accommodating the dynamic nature of order events in an online marketplace.

System designMediumData EngineerTechnical Screen

15. You are building analytics for a chat platform similar to Discord.

The full question

You are building analytics for a chat platform similar to Discord. The raw event sources are:

  • server(server_id, creator_id, created_at)
  • server_view(server_id, user_id, viewed_at)
  • server_join(server_id, user_id, joined_at)
  • message(message_id, server_id, channel_id, user_id, sent_at)

Tasks:

  1. Design a fact-dimension data model that can support analytics on servers, views, joins, and messages.
  2. Write SQL to compute the average weekly number of server_view events during calendar year 2020.
  3. Write SQL to compute the week-over-week change in server_view events over the most recent 12 months.
  4. Explain how you would handle missing weeks in the time series.
  5. Write SQL to return, for every server, the all-time count of server views, server joins, and messages.

Model answer

1. Requirements & scale

Functional Requirements:

  • Track and analyze server creation, views, joins, and messages.
  • Compute average weekly server views for a given year.
  • Calculate week-over-week change in server views over the past 12 months.
  • Handle missing weeks in time series data.
  • Provide all-time counts of server views, joins, and messages per server.

Non-Functional Requirements:

  • High throughput for event ingestion.
  • Durability and reliability of stored data.
  • Scalable architecture to handle growth in data volume.
  • Efficient querying for analytics.

Scale Estimates:

  • Assume 1 million servers, each with 1000 views, 500 joins, and 10,000 messages per month.
  • Total events per month: \(1M \times (1000 + 500 + 10,000) = 11.5 \text{ billion events}\).
  • Average event size: 100 bytes.
  • Monthly storage: \(11.5 \text{ billion} \times 100 \text{ bytes} = 1.15 \text{ TB}\).
  • Queries per second (QPS): Assuming 1000 concurrent analytics queries, each taking 1 second, QPS = 1000.

2. High-level architecture

flowchart TD
    subgraph Client
        A[User Interface]
    end

    subgraph Edge/CDN
        B[CDN]
    end

    subgraph Load Balancer
        C[Load Balancer]
    end

    subgraph API / Services
        D[Analytics Service]
    end

    subgraph Cache
        E[Redis Cache]
    end

    subgraph Datastores
        F[Fact Table (SQL)]
        G[Dimension Tables (SQL)]
        H[Time-series DB]
    end

    subgraph Message Queue
        I[Kafka]
    end

    subgraph Workers
        J[Stream Processing]
    end

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

3. API design

  • GET /analytics/average-weekly-views: Compute average weekly server views for a given year.
  • GET /analytics/week-over-week-views: Calculate week-over-week change in server views over the past 12 months.
  • GET /analytics/all-time-counts: Return all-time counts of server views, joins, and messages per server.

4. Data model & storage

Datastores:

  • Fact Table (SQL): Stores events with high write throughput.
  • Dimension Tables (SQL): For metadata about servers, users, etc.
  • Time-series DB: Efficient storage and querying of time-series data.

Data Model:

  • Fact Table: events(event_id, server_id, user_id, event_type, timestamp)
  • Dimension Tables:
  • servers(server_id, creator_id, created_at)
  • users(user_id, joined_at)

Partitioning Strategy:

  • Fact table partitioned by timestamp for efficient time-based queries.

5. Deep dive

To compute the average weekly number of server_view events during 2020, we can use SQL aggregation functions:

SELECT 
    AVG(weekly_views) AS average_weekly_views
FROM (
    SELECT 
        DATE_TRUNC('week', viewed_at) AS week_start,
        COUNT(*) AS weekly_views
    FROM server_view
    WHERE viewed_at BETWEEN '2020-01-01' AND '2020-12-31'
    GROUP BY week_start
) AS weekly_data;

For week-over-week change:

WITH weekly_views AS (
    SELECT 
        DATE_TRUNC('week', viewed_at) AS week_start,
        COUNT(*) AS weekly_views
    FROM server_view
    WHERE viewed_at >= NOW() - INTERVAL '12 months'
    GROUP BY week_start
),
week_over_week AS (
    SELECT 
        week_start,
        weekly_views,
        LAG(weekly_views) OVER (ORDER BY week_start) AS previous_week_views
    FROM weekly_views
)
SELECT 
    week_start,
    (weekly_views - previous_week_views) / previous_week_views::float * 100 AS week_over_week_change
FROM week_over_week
WHERE previous_week_views IS NOT NULL;

Handling missing weeks involves generating a complete series of weeks and left joining it with the actual data.

6. Scale, bottlenecks & trade-offs

Replication and Sharding:

  • Use sharding for the fact table based on timestamp to distribute load.
  • Replicate dimension tables across nodes for read availability.

Caching:

  • Use Redis for caching frequently accessed analytics results.

Bottlenecks:

  • High write throughput to the fact table can be a bottleneck; use stream processing to batch writes.
  • Query performance can degrade with large datasets; optimize with indexing and partitioning.

Trade-offs:

  • Consistency vs. Availability: Prioritize availability for analytics queries; eventual consistency is acceptable.
  • SQL vs. NoSQL: SQL chosen for its strong querying capabilities and support for complex joins and aggregations.
  • Push vs. Pull: Use a pull model for analytics queries to allow flexible querying by users.
TechnicalEasyData Engineer

16. Define OLTP and OLAP.

The full question

Define OLTP and OLAP. What is the difference? What are their purposes?

Model answer

OLTP

  • Online Transaction Processing supports the application's day-to-day operations: short, frequent transactions that read or change individual records.
  • It prioritizes correctness, concurrency, and low latency, typically using normalized relational tables and ACID transactions.
  • Example: recording a hotel booking or updating a review.

OLAP

  • Online Analytical Processing supports analysis across large volumes of historical data, such as dashboards, trends, and business reporting.
  • It prioritizes efficient scans and aggregations, often using denormalized or columnar storage in a data warehouse or lakehouse.
  • Example: comparing booking or review trends across destinations and time periods.

Key differences

  • Workload: OLTP handles many small transactions; OLAP handles fewer, larger analytical queries.
  • Data model: OLTP commonly uses normalized schemas; OLAP commonly uses dimensional models, such as facts and dimensions.
  • Performance goal: OLTP optimizes transaction latency and consistency; OLAP optimizes scan and aggregation throughput.
  • Data freshness: OLTP is generally current; OLAP data may arrive through an ingestion pipeline and be slightly delayed.

They complement each other: operational systems capture events, and analytical systems make those events useful for reporting and decisions. Separating the workloads also prevents heavy reports from slowing down customer-facing transactions.

TechnicalEasyData Engineer

17. How do you define fact table granularity?

Model answer

Fact-table granularity is the precise definition of what one row represents. I define it before choosing measures or keys, and state it in business terms—for example: “one row per completed booking per booking line” or “one row per hotel, date, and device for daily page views.”

  • Identify the business event or observation being recorded and its point in the process.
  • Specify the dimensions that distinguish one observation from another, including time and any required line-item or entity identifiers.
  • Check that each proposed row corresponds to exactly one observation; avoid mixing detail levels in the same fact table.
  • Choose measures that are valid at that grain. Additive measures such as booking revenue can be summed across appropriate dimensions; ratios and distinct counts generally need to be recomputed from their components.
  • Document the grain and enforce it with keys or uniqueness checks so joins and aggregations do not silently duplicate facts.

For example, if a booking has multiple hotel nights, a booking-level fact and a booking-night-level fact have different grains. Joining them without accounting for that difference can multiply booking totals.

TechnicalEasyData Engineer

18. What is SQL execution order?

Model answer

The logical SQL query processing order is generally:

  1. FROM (including joins and table sources)
  2. ON (join condition)
  3. JOIN (combine matching rows)
  4. WHERE (filter rows before aggregation)
  5. GROUP BY (form groups)
  6. HAVING (filter groups after aggregation)
  7. SELECT (compute output expressions)
  8. DISTINCT (remove duplicate output rows, if requested)
  9. ORDER BY (sort results)
  10. LIMIT / OFFSET (restrict the returned rows; syntax varies by database)

This is a logical order, not necessarily the physical execution plan: the database optimizer may reorder operations while preserving the query's semantics. It also explains why a SELECT alias is usually unavailable in WHERE, which is evaluated earlier, though some databases permit aliases in ORDER BY.

TechnicalEasyData Engineer

19. What is a dimension?

Model answer

A dimension is a descriptive data model that provides context for analyzing measurable events. For example, in Tripadvisor booking analytics, dimensions might describe the traveler, hotel, destination, date, device, or channel; a fact table records measures such as bookings, revenue, or clicks.

  • Dimensions answer questions like who, what, where, when, and how.
  • They typically contain attributes used to filter, group, and label facts—for example, a destination’s city, country, and region.
  • In a star schema, dimensions join to fact tables through keys. A dimension often has a surrogate key, while retaining the source system’s natural key for identification.
  • Dimensions are generally less granular and change less frequently than the events recorded in fact tables.
TechnicalEasyData Engineer

20. What is a common table expression (CTE)?

Model answer

A common table expression (CTE) is a named, temporary result set defined with a WITH clause and used by the statement that follows it. It can make complex queries easier to read by separating logic into named steps.

WITH recent_reviews AS (
  SELECT review_id, restaurant_id, created_at
  FROM reviews
  WHERE created_at >= DATE '2025-01-01'
)
SELECT restaurant_id, COUNT(*) AS review_count
FROM recent_reviews
GROUP BY restaurant_id;

A CTE exists only for that statement; it does not create a persistent table. CTEs can also be recursive, which is useful for hierarchical or graph-like data. Whether a CTE is materialized or inlined for execution depends on the database and query.

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