ZomatoData EngineerData Structures & Algorithms

A zomato data engineer needs to process high-velocity, real-time order event streams to calculate unique active users and popular menu items within dynamic time windows. How would you choose and implement appropriate data structures to efficiently handle these requirements?

ZomatoData Engineer5–8 YearsData Structures & Algorithms

9 min readUpdated

Processing high-velocity, real-time order event streams for metrics like unique active users and popular menu items within dynamic time windows requires careful selection of data structures that balance accuracy, memory efficiency, and update/query performance. For unique active users, approximate counting algorithms like HyperLogLog are ideal due to their constant memory footprint irrespective of cardinality. For popular menu items, Count-Min Sketch or a combination of hash maps with sliding window logic and min-heaps can provide efficient frequency estimation or top-k tracking.

Choosing Data Structures for Streaming Analytics

For unique active users, the most suitable data structure is a HyperLogLog (HLL) sketch. It provides a probabilistic approximation of the number of unique elements in a multiset with a very small, fixed memory footprint, typically a few kilobytes, regardless of the number of unique items. This is crucial for high-velocity streams where storing all unique user IDs would quickly exhaust memory. HLL works by hashing elements and observing the position of the first set bit (or trailing zeros) in the hash, using statistical properties to estimate cardinality. For popular menu items, a Count-Min Sketch is an excellent choice. It is another probabilistic data structure that approximates the frequency of elements in a stream, making it suitable for identifying top-k items. It uses multiple hash functions and an array of counters to estimate frequencies. Alternatively, for exact counts within a sliding window, a Hash Map to store item counts, paired with a Doubly Linked List or Queue to manage the window’s elements for timely expiration, can be used. A Min-Heap can then efficiently extract the top-k items from the hash map.

Best Practice: Windowing and Combination

For dynamic time windows (e.g., last 5 minutes, last hour), these data structures need to be applied within a windowing framework. For HyperLogLog and Count-Min Sketch, you can maintain separate sketches for different window types or use a hopping window approach where sketches are merged and rolled over. For exact counts of popular items in a sliding window, implement a data structure that tracks counts and their entry times. When an item enters the window, its count is incremented. When it expires (moves out of the window), its count is decremented. A min-heap helps in maintaining the top-k items efficiently by pushing new items and popping the smallest when capacity is reached. For more complex historical queries or dynamic aggregation, consider a Segment Tree or Fenwick Tree that can operate over time-based indices, though these are typically for more structured or batch-oriented updates within a window context.

Edge Case Interviewers Probe For

Interviewers often probe the trade-offs between accuracy and space. While probabilistic data structures are memory-efficient, they offer approximate results. Discuss how to tune their parameters (e.g., number of registers for HLL, depth/width for Count-Min Sketch) to achieve desired accuracy bounds. Another edge case is handling cold starts for windows or sudden shifts in data distribution, where initial estimates might be skewed or take time to stabilize. Consider mechanisms to warm up these data structures or fall back to more precise, albeit resource-intensive, methods for critical initial periods. The interviewer might also ask about handling data skew, where a few items dominate the stream, which can affect the accuracy of Count-Min Sketch or the efficiency of exact counting methods.

Common Mistake

A common mistake is attempting to store every unique identifier or every single order item for exact counts in memory, especially for large-scale, high-velocity streams. This leads to prohibitive memory consumption and poor performance. Another error is not understanding the implications of “at-least-once” processing in streaming systems, which can lead to overcounting without proper deduplication or idempotent processing logic at the application layer. Failing to implement robust windowing logic or not correctly handling element expiration and aggregation for dynamic windows also frequently causes issues. Additionally, overlooking the operational complexity and monitoring aspects of these real-time systems is a critical oversight.

What the interviewer is checking

The interviewer is assessing your deep understanding of data structures tailored for streaming and big data problems. They want to see your ability to analyze requirements (approximate vs. exact, memory vs. speed), propose suitable solutions, articulate the trade-offs involved, and consider practical implementation details like windowing, memory management, and error handling. This demonstrates your capacity for designing scalable and efficient real-time analytics systems in a data-intensive environment like Zomato’s.

Imagine you’re at a huge food festival, and you need to quickly figure out two things for the organizers: 1) Roughly how many different people have shown up today, and 2) What are the most popular food items based on quick tallies. You can’t possibly count every single person or meticulously track every order for every food item, because there are too many, and you need answers fast.

For the “different people” (unique active users), you don’t count every person one by one. Instead, you use a special, clever trick. It’s like having a magic notepad that, no matter how many people tell you their name, can give you a very good estimate of how many unique names it has heard, without actually remembering every single name. This saves a lot of space and brainpower. For the “most popular food items,” you have a different, smart way to tally votes. Instead of having a dedicated counter for every single food item (which would be thousands), you use a clever system of several smaller tally boards that lets you get a good estimate for the most popular ones, even if it’s not perfectly precise. This allows you to react quickly to what’s trending and what’s not, ensuring the festival runs smoothly.

Why interviewers ask this

Interviewers ask this to gauge your expertise in designing efficient data processing solutions for high-volume, real-time data streams. It assesses your knowledge of advanced data structures, understanding of probabilistic algorithms, and ability to make trade-offs between accuracy, memory, and performance in a big data context.

What a strong answer signals

A strong answer demonstrates practical experience with streaming analytics, the ability to articulate the strengths and weaknesses of different data structures, and a clear understanding of how to apply them to solve real-world problems. It signals your capacity for designing scalable, production-ready data pipelines that handle massive scale efficiently.

Common follow-ups

  • How would you handle data skew when calculating popular items, and what impact could it have?
  • What if exact counts for unique active users were a strict requirement, and how would that change your data structure and system design approach?
  • How would you integrate these data structures into a larger stream processing framework like Apache Flink or Spark Streaming for distributed computation?

Advanced variation

Design a system to detect unusual spikes or drops in unique active users or menu item popularity in real-time. This requires integrating these data structures with anomaly detection algorithms that consider historical trends and seasonality, adding another layer of complexity to the real-time analysis.

Consider Zomato wanting to offer dynamic, hyper-localized promotions based on trending menu items in a specific city over the last hour, and simultaneously display the count of unique users who have viewed menus in that same window. Storing every order or user view event for exact counts for millions of interactions per hour across thousands of menu items would be prohibitively memory-intensive and slow for real-time decision-making. Instead, for unique active users, a HyperLogLog sketch is maintained per city per hour. For popular menu items, a Count-Min Sketch or a sliding window hash map combined with a min-heap tracks item frequencies, allowing the system to quickly identify the top-selling dishes. This approach provides real-time, actionable insights with manageable resource usage, enabling agile business responses like adjusting promotions dynamically.

count_min_sketch.py
# Basic implementation of a Count-Min Sketch for frequency estimation
import hashlib
import sys

class CountMinSketch:
    def __init__(self, width, depth):
        self.width = width  # Number of columns (counters per hash function)
        self.depth = depth  # Number of hash functions (rows)
        self.table = [[0] * width for _ in range(depth)]
        self.seeds = [i for i in range(depth)] # Unique seeds for hash functions

    def _hash(self, item, seed):
        # Simple hash function using SHA-256 and modulo
        h = hashlib.sha256((item + str(seed)).encode()).hexdigest()
        return int(h, 16) % self.width

    def add(self, item, count=1):
        for i in range(self.depth):
            idx = self._hash(item, self.seeds[i])
            self.table[i][idx] += count

    def query(self, item):
        min_count = sys.maxsize
        for i in range(self.depth):
            idx = self._hash(item, self.seeds[i])
            min_count = min(min_count, self.table[i][idx])
        return min_count

# Example Usage for popular menu items
if __name__ == "__main__":
    cms = CountMinSketch(width=1000, depth=5)
    
    orders = ["pizza", "burger", "pizza", "sushi", "burger", "pizza", "fries", "burger"]
    for item in orders:
        cms.add(item)
    
    print(f"Estimated count for 'pizza': {cms.query('pizza')}")
    print(f"Estimated count for 'burger': {cms.query('burger')}")
    print(f"Estimated count for 'sushi': {cms.query('sushi')}")
    print(f"Estimated count for 'salad' (not in stream): {cms.query('salad')}")

    # Expected output (approximate, may vary slightly due to hash collisions):
    # Estimated count for 'pizza': 3
    # Estimated count for 'burger': 3
    # Estimated count for 'sushi': 1
    # Estimated count for 'salad' (not in stream): 0 (or a small positive value due to false positives)
Order Event Stream Data Structure Logic (Streaming Window) HyperLogLog (Unique Users) Count-Min Sketch (Popular Items) Sliding Window Hash/Heap (Exact Top-K Items) Real-time Analytics Dashboard
  1. 1Probabilistic data structures like HyperLogLog are essential for efficiently estimating unique counts in high-velocity data streams with minimal memory footprint.
  2. 2Count-Min Sketch provides approximate frequency counts, suitable for identifying popular items in real-time streaming contexts by balancing accuracy and resource usage.
  3. 3Dynamic time window analysis often involves combining these structures with windowing techniques or using specialized sliding window aggregates for continuous updates.
  4. 4Choosing the right data structure for streaming data requires balancing accuracy requirements with memory constraints and computational overhead.
  5. 5Effective data engineering for streaming analytics prioritizes scalable, real-time insights over perfect, resource-intensive precision, especially for high-volume scenarios.