Urban Company interview questions & answers

15 real Urban Company interview questions with full model answers — System design, Technical, Coding. Drawn from the same verified bank ChannelPulse drills from (15 Urban Company questions in total).

CodingEasyUrban CompanySoftware EngineerTechnical/Managerial Round

1. Write a SQL query using a standard join.

Model answer

A standard inner join keeps rows whose keys appear in both collections. This JavaScript example joins bookings to customers by customerId:

const bookings = [
  { id: 101, customerId: 1, service: "cleaning" },
  { id: 102, customerId: 2, service: "plumbing" },
  { id: 103, customerId: 9, service: "beauty" },
];

const customers = [
  { id: 1, name: "Asha" },
  { id: 2, name: "Ravi" },
];

function innerJoin(bookings, customers) {
  // Index the right-hand collection for efficient key lookups.
  const customersById = new Map(
    customers.map((customer) => [customer.id, customer])
  );

  return bookings.flatMap((booking) => {
    const customer = customersById.get(booking.customerId);

    // An inner join excludes rows without a matching customer.
    return customer ? [{ ...booking, customerName: customer.name }] : [];
  });
}

console.log(innerJoin(bookings, customers));
// [
//   { id: 101, customerId: 1, service: "cleaning", customerName: "Asha" },
//   { id: 102, customerId: 2, service: "plumbing", customerName: "Ravi" }
// ]
  • Build a map of customers keyed by ID, then look up each booking’s customer.
  • Bookings without a matching customer are omitted, as in an inner join.

Complexity: Time O(bookings + customers); space O(customers + result).

CodingMediumUrban CompanySoftware Engineer

2. Evaluate Division (LeetCode)

Model answer

The task

Given equations that define ratios between variables, answer queries asking for a ratio between two variables. Return -1.0 when the ratio cannot be determined.

Key idea

Represent each equation as two directed graph edges: from a to b with weight a / b, and from b to a with the reciprocal weight. A path’s edge weights multiply to give the ratio between its endpoints.

Approach

  1. Build a weighted adjacency list from the equations.
  2. For each query, return -1.0 if either variable is unknown.
  3. Otherwise, use DFS to find a path between the variables, multiplying edge weights along the way.
  4. Track visited variables so cycles do not cause repeated exploration.
  5. If the variables are the same and known, the ratio is 1.0.
from collections import defaultdict
from typing import List

class Solution:
    def calcEquation(
        self,
        equations: List[List[str]],
        values: List[float],
        queries: List[List[str]]
    ) -> List[float]:
        graph = defaultdict(list)

        for (numerator, denominator), value in zip(equations, values):
            graph[numerator].append((denominator, value))
            graph[denominator].append((numerator, 1.0 / value))

        def find_ratio(start: str, target: str) -> float:
            if start not in graph or target not in graph:
                return -1.0
            if start == target:
                return 1.0

            stack = [(start, 1.0)]
            visited = {start}

            while stack:
                variable, product = stack.pop()

                for neighbor, edge_value in graph[variable]:
                    if neighbor in visited:
                        continue

                    next_product = product * edge_value
                    if neighbor == target:
                        return next_product

                    visited.add(neighbor)
                    stack.append((neighbor, next_product))

            return -1.0

        return [find_ratio(a, b) for a, b in queries]

Complexity:

  • Time: O(Q(V + E)), where each query may traverse the full graph.
  • Space: O(V + E) for the graph and the DFS state.

Common follow-ups

  • How can repeated queries be sped up? Use weighted union-find to answer each query in near-constant time after preprocessing.
  • How would you handle inconsistent equations? Detect conflicting ratios when connecting variables or revisiting an already-connected pair.
  • What if the graph is very large but queries are few? Keep DFS/BFS per query to avoid more elaborate preprocessing.
CodingMediumUrban CompanySoftware Engineer

3. Pacific Atlantic Water Flow (LeetCode)

Model answer

The task

Given a grid of elevations, find every cell from which water can flow to both the Pacific and Atlantic oceans. Water can flow between adjacent cells only downhill or across cells of equal height; the Pacific borders the top and left edges, and the Atlantic borders the bottom and right edges.

Key idea

Instead of tracing water downhill from every cell, search backward from each ocean. From a cell already reachable by an ocean, the reverse search can move to an adjacent cell of equal or greater height.

Approach

  1. Return an empty list if the grid has no rows or columns.
  2. Initialize one search from the Pacific-border cells and another from the Atlantic-border cells.
  3. In each search, visit a neighbor only if it is in bounds, unvisited, and at least as high as the current cell.
  4. Return the coordinates visited by both searches.
from collections import deque
from typing import List

class Solution:
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
        if not heights or not heights[0]:
            return []

        rows, cols = len(heights), len(heights[0])

        def reachable(starts):
            visited = set(starts)
            queue = deque(starts)

            while queue:
                r, c = queue.popleft()

                for nr, nc in ((r - 1, c), (r + 1, c),
                               (r, c - 1), (r, c + 1)):
                    if (0 <= nr < rows and 0 <= nc < cols
                            and (nr, nc) not in visited
                            and heights[nr][nc] >= heights[r][c]):
                        visited.add((nr, nc))
                        queue.append((nr, nc))

            return visited

        pacific_starts = (
            [(0, c) for c in range(cols)]
            + [(r, 0) for r in range(rows)]
        )
        atlantic_starts = (
            [(rows - 1, c) for c in range(cols)]
            + [(r, cols - 1) for r in range(rows)]
        )

        pacific = reachable(pacific_starts)
        atlantic = reachable(atlantic_starts)

        return [[r, c] for r, c in pacific & atlantic]

Complexity:

  • Time: O(rows × cols), since each cell is visited at most once per search.
  • Space: O(rows × cols) for the visited sets and queues.

Common follow-ups

  • Can DFS replace BFS? Yes; either traversal finds the same reachable cells.
  • How would you handle diagonal flow? Include diagonal neighbors in the traversal.
  • What if the grid is updated repeatedly? Recompute reachability, or use a specialized dynamic-connectivity strategy if updates are frequent.
CodingMediumUrban CompanySoftware Engineer

4. Frequency of the Most Frequent Element (LeetCode)

Model answer

The task

Given an integer array and a budget of unit increments, find the largest number of elements that can be made equal using at most that budget. Each operation increments one element by one.

Key idea

After sorting, consider a window whose elements will all be raised to its largest value. The cost is the largest value times the window size minus the sum of the window. Expand the window while affordable; otherwise, move its left edge forward.

Approach

  1. Sort the array.
  2. Keep a sliding window and its running sum.
  3. For each right edge, add its value to the sum.
  4. While raising the window to the rightmost value costs more than k, remove the leftmost value and advance the left edge.
  5. Track the largest affordable window.
class Solution:
    def maxFrequency(self, nums: list[int], k: int) -> int:
        nums.sort()

        left = 0
        window_sum = 0
        best = 0

        for right, value in enumerate(nums):
            window_sum += value

            # Cost to raise every value in the window to nums[right].
            while value * (right - left + 1) - window_sum > k:
                window_sum -= nums[left]
                left += 1

            best = max(best, right - left + 1)

        return best

Complexity:

  • Time: O(n log n), dominated by sorting; the window scan is O(n).
  • Space: O(n) for Python's in-place sort in the worst case; the scan itself uses O(1) extra space.

Common follow-ups

  • What if the array is already sorted? The scan takes O(n), so the total time is O(n).
  • Can you return the value to which the elements are raised? Record nums[right] whenever the best window size increases.
  • What if decrements are also allowed? The target need not be the window maximum; use a median-based cost instead of this one-sided cost.
  • What if updates arrive online? Sorting and this sliding window assume the full array is available; dynamic updates need a different data structure and strategy.
CodingMediumUrban CompanySoftware Engineer

5. Find Peak Element (LeetCode)

Model answer

The task

Given an array whose neighboring values are distinct, return the index of any element that is greater than its neighbors. Treat positions outside the array as having value negative infinity.

Key idea

Compare the middle element with the one immediately to its right. If the middle is larger, a peak exists at or to its left; otherwise, a peak exists to its right. This lets binary search discard half the search range each iteration.

Approach

  1. Set left and right to the array’s endpoints.
  2. While the range has more than one element, inspect its midpoint and the next element.
  3. If the midpoint is larger, keep the left half, including the midpoint.
  4. Otherwise, keep the right half, starting after the midpoint.
  5. Return the remaining index.
class Solution:
    def findPeakElement(self, nums: list[int]) -> int:
        left, right = 0, len(nums) - 1

        while left < right:
            mid = (left + right) // 2

            # A descending step means a peak is at mid or somewhere to its left.
            if nums[mid] > nums[mid + 1]:
                right = mid
            else:
                # An ascending step means a peak exists to the right of mid.
                left = mid + 1

        return left

Complexity:

  • Time: O(log n), since the search range is halved each iteration.
  • Space: O(1), since only a fixed number of variables are used.

Common follow-ups

  • How would you return all peak indices? Scan the array and compare each value with its neighbors, using negative infinity at the boundaries.
  • What if adjacent values may be equal? The binary-search reasoning may no longer identify a peak in logarithmic time; handle plateaus explicitly or scan in O(n).
  • How would you find a peak in a two-dimensional grid? Use binary search across columns, finding a column maximum each step and comparing it with its horizontal neighbors.
CodingMediumUrban CompanySoftware Engineer

6. Minimum Deletions to Make String Balanced (LeetCode)

Model answer

The task

Given a string containing only a and b, find the fewest characters to delete so that no b appears before an a. The remaining string must have all its as before its bs.

Key idea

Scan from left to right while tracking how many bs have appeared and the minimum deletions needed so far. When an a follows earlier bs, either delete this a or delete those earlier bs.

Approach

  1. Initialize the count of seen bs and the deletion count to zero.
  2. For each character, increment the b count if it is b.
  3. If it is a, update the deletion count to the cheaper of deleting this a or deleting the preceding bs.
  4. Return the deletion count.
class Solution:
    def minimumDeletions(self, s: str) -> int:
        seen_b = 0
        deletions = 0

        for char in s:
            if char == "b":
                seen_b += 1
            else:
                # Either remove this "a", or remove earlier "b"s.
                deletions = min(deletions + 1, seen_b)

        return deletions

Complexity:

  • Time: O(n), where n is the string length.
  • Space: O(1), using only two counters.

Common follow-ups

  • How would you reconstruct which characters to delete? Track the choices and use backtracking or store DP decisions.
  • What if the string has more than two character types with a required order? Use dynamic programming over the allowed phases or character groups.
  • Can this be solved with a stack? Yes; a stack-based approach can remove an earlier b whenever an a appears, though the counter-based DP uses less space.
CodingHardUrban CompanySoftware Engineer

7. Trapping Rain Water (LeetCode)

Model answer

The task

Given an array of nonnegative bar heights, compute how much water remains trapped between the bars after rainfall. Each bar has unit width.

Key idea

Water above a position is limited by the shorter of the tallest bars to its left and right. With two pointers, process the side whose current height is lower: its boundary already determines the maximum water that position can hold, so no arrays of prefix and suffix maxima are needed.

Approach

  1. Start pointers at both ends and track the greatest height seen from each side.
  2. While the pointers have not crossed, compare their current heights.
  3. If the left height is lower, update the left maximum and add any water above the left bar, then advance the left pointer.
  4. Otherwise, do the symmetric operation on the right.
  5. Return the accumulated water.
from typing import List

class Solution:
    def trap(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1
        left_max = right_max = 0
        water = 0

        while left < right:
            if height[left] < height[right]:
                # The right side is tall enough that the left maximum
                # determines the water level at this position.
                left_max = max(left_max, height[left])
                water += left_max - height[left]
                left += 1
            else:
                # Symmetrically, the right maximum determines this level.
                right_max = max(right_max, height[right])
                water += right_max - height[right]
                right -= 1

        return water

Complexity:

  • Time: O(n), because each pointer moves across the array at most once.
  • Space: O(1), because the algorithm uses only a fixed number of variables.

Common follow-ups

  • How can this be solved with dynamic programming? Precompute the maximum height to each position from the left and right, then sum the trapped water at each position.
  • How can a monotonic stack solve it? Keep indices of decreasing bar heights; when a taller bar arrives, pop a basin bottom and calculate the bounded layer.
  • What if bars have different widths? Track each bar’s width and use area rather than unit-width contributions; the boundary logic must account for the resulting horizontal spans.
System designHardUrban CompanySoftware EngineerRound 2

8. Design a Query Management System with resource-utilization monitoring, notifications, and analytics.

Model answer

1. Requirements & scale

Assumption: I’ll design an internal query-management platform for Urban Company support teams, handling customer and service-professional issues from booking, payment, cancellation, and service workflows. “Resource utilization” means both agent workload/capacity and the system’s operational health.

  • Functional: Create and track queries; categorize and prioritize them; assign or reassign agents; enforce SLAs; notify customers and agents; expose dashboards for volume, resolution, SLA, and capacity.
  • Non-functional: No lost queries; authorization by role; auditable changes; p95 read latency under 300 ms; durable notifications; dashboards within five minutes of events.
  • Scale assumptions: 5 million monthly users, 50,000 queries/day, and 500 support agents. At 10× peak, intake is about 6 queries/s; allow 100 API requests/s for reads and updates. At 10 KB/query, one year of query records is about 183 GB before indexes and replicas. At 10 events/query and 1 KB/event, event volume is about 183 GB/year. A 1 KB notification per query averages under 1 KB/s, with burst capacity designed for 100/s.

2. High-level architecture

flowchart TD
  subgraph Client
    U["Customer and Partner Apps"]
    A["Agent Console"]
  end
  subgraph EdgeCDN["Edge / CDN"]
    E["WAF and CDN"]
  end
  subgraph LoadBalancer["Load Balancer"]
    LB["API Gateway"]
  end
  subgraph Services["API / Services"]
    QS["Query Service"]
    AS["Assignment Service"]
    NS["Notification Service"]
    MS["Metrics Ingest Service"]
  end
  subgraph Cache["Cache"]
    R["Redis: SLA and agent capacity"]
  end
  subgraph Datastores["Datastores"]
    DB["PostgreSQL: queries and audit"]
    TS["Time-series store: resource metrics"]
    WH["Analytics warehouse"]
  end
  subgraph MessageQueue["Message Queue"]
    Q["Kafka: query and capacity events"]
  end
  subgraph Workers["Workers"]
    W["Routing and SLA workers"]
    N["Notification workers"]
    D["Analytics and alert workers"]
  end
  U --> E
  A --> E
  E --> LB
  LB --> QS
  QS --> DB
  QS --> R
  QS -->|"query events"| Q
  AS --> R
  AS -->|"assignment events"| Q
  Q --> W
  Q --> N
  Q --> D
  W -->|"assignment update"| DB
  N --> NS
  D --> WH
  D --> TS
  MS --> TS
  MS -->|"capacity events"| Q
Diagram

The API path is synchronous for query creation and reads; routing, notifications, and analytics are asynchronous. The transactional outbox prevents a committed query from losing its event if Kafka is temporarily unavailable.

3. API design

  • POST /v1/queries — create a query with booking ID, category, description, and idempotency key.
  • GET /v1/queries/{queryId} — retrieve status, owner, and SLA.
  • GET /v1/queries?status=&category=&cursor= — agent queue with cursor pagination.
  • PATCH /v1/queries/{queryId} — update status, priority, or category; record the actor and reason.
  • POST /v1/queries/{queryId}/assignments — manually assign or reassign with an audit reason.
  • POST /v1/agents/{agentId}/capacity — publish availability and active workload.
  • GET /v1/analytics/queries?from=&to=&groupBy= — role-authorized aggregate metrics.

4. Data model & storage

  • PostgreSQL: queries(id, customer_id, booking_id, category, priority, status, assignee_id, created_at, sla_due_at, version); query_events(query_id, event_id, type, actor_id, payload, created_at); and outbox(event_id, payload, published_at). Partition large event tables by month; shard queries by id only when a single primary becomes a measured bottleneck.
  • Redis: Agent capacity, routing counters, and short-lived SLA timers. Treat it as a rebuildable cache, not the source of truth.
  • Kafka: Partition query events by query_id to preserve per-query order. Consumers must be idempotent because delivery is at least once.
  • Time-series store: Agent availability, queue depth, and service health samples. Warehouse: Aggregated analytics; do not run dashboard scans against the transactional database.

5. Deep dive

The core challenge is assigning work fairly while meeting SLAs. Route within category, language, and region eligibility; among eligible agents, choose the lowest normalized load, with aging priority for queries approaching their SLA.

Define agent load as active_weight / effective_capacity, where active work is weighted by query priority and expected handling time. Effective capacity accounts for availability and skill coverage. Recompute capacity from agent updates and query assignment/resolution events; periodically reconcile it against PostgreSQL so missed events cannot cause permanent drift. A Redis sorted set can rank eligible agents by load, but assignment must be confirmed using an atomic capacity reservation with a short lease. If the reservation fails, try the next candidate. Persist the assignment and audit event transactionally, then publish the event through the outbox.

sequenceDiagram
  participant C as Client
  participant Q as Query API
  participant DB as PostgreSQL
  participant K as Kafka
  participant W as Routing worker
  participant R as Redis
  participant N as Notification worker
  C->>Q: Create query with idempotency key
  Q->>DB: Insert query and outbox event
  Q-->>C: Query ID and accepted status
  W->>K: Consume query-created event
  W->>R: Find eligible agent and reserve capacity
  W->>DB: Persist assignment and audit event
  W->>K: Publish assignment event via outbox
  N->>K: Consume assignment event
  N-->>C: Send customer and agent notification
Diagram

SLA workers schedule reminders and escalation events; they re-check current status before acting, avoiding stale timers. Notifications use provider adapters, retries with exponential backoff, and a dead-letter queue. Analytics workers aggregate events into hourly and daily metrics. Alerts fire on SLA breach rate, queue age, agent saturation, notification failure rate, and infrastructure CPU/memory thresholds.

6. Scale, bottlenecks & trade-offs

  • Use stateless API replicas across availability zones; PostgreSQL has synchronous failover within a region and asynchronous read replicas for read-heavy queues. Keep writes strongly consistent for ownership and status transitions.
  • Cache read-only category and SLA configuration. Avoid caching query state as authoritative; stale assignments can expose incorrect ownership.
  • Kafka absorbs bursts and isolates notification or warehouse outages from query intake. Monitor consumer lag; scale workers by partition count and lag.
  • Analytics may be eventually consistent by up to five minutes. Operational alerts use near-real-time stream aggregates, not delayed warehouse queries.
  • If a region fails, fail over the API and database with a defined recovery-point objective; retry clients using idempotency keys. If Redis fails, pause automated assignment or use a conservative database-backed fallback rather than over-assigning agents.
  • The primary trade-off is consistency versus availability: accept and persist a query even if routing or notifications are down, then recover asynchronously. This protects customer issues from being lost while keeping assignment and audit history correct. Regular reconciliation and dashboards for event lag, capacity drift, and failed deliveries make that design observable.
TechnicalMediumUrban CompanySoftware EngineerTechnical/Managerial Round

9. Explain runtime polymorphism and give a real-world example in code.

Model answer

Runtime polymorphism means the method that runs is chosen at runtime based on an object's actual type, rather than the type of the variable holding it. It is commonly implemented through method overriding: subclasses provide their own implementation of a method defined by a parent class or interface.

For example, Urban Company might support multiple service types that each calculate a different booking duration:

class Service {
  estimateMinutes() {
    throw new Error("Subclasses must implement estimateMinutes()");
  }
}

class SalonService extends Service {
  estimateMinutes() {
    return 60;
  }
}

class CleaningService extends Service {
  estimateMinutes() {
    return 120;
  }
}

function printEstimate(service) {
  // The implementation is selected from the object's actual class.
  console.log(`${service.constructor.name}: ${service.estimateMinutes()} minutes`);
}

const bookings = [new SalonService(), new CleaningService()];
bookings.forEach(printEstimate);

printEstimate uses the same interface for both objects, but JavaScript dispatches estimateMinutes() to the implementation on each object's actual class. This lets callers depend on a common contract while implementations vary.

TechnicalMediumUrban CompanySoftware EngineerTechnical/Managerial Round

10. What is database indexing, and how is it stored on disk?

Model answer

A database index is an auxiliary data structure that helps the database find rows without scanning the entire table. It stores indexed column values along with a way to locate the corresponding row or table page.

  • On disk: Indexes are usually stored as files made up of fixed-size pages or blocks, much like table data. A common structure is a B+ tree: internal pages contain separator keys and child-page pointers, while leaf pages contain keys and row identifiers (or, for a clustered index, the row data itself).
  • In memory: The database caches frequently used index pages in its buffer pool. A lookup follows page pointers from the root toward a leaf, reading pages from disk only when they are not cached.
  • Trade-off: An index speeds up reads such as filtering and sorting, but consumes storage and adds work to inserts, updates, and deletes because the index must also be maintained.

For example, an index on bookings.customer_id can help find a customer's bookings without examining every booking row. An index is not necessarily stored in RAM; its durable representation is on disk, with hot pages cached as needed.

TechnicalMediumUrban CompanySoftware EngineerTechnical/Managerial Round

11. What are the drawbacks of sharding?

Model answer

Sharding can improve scale, but it adds operational and application complexity:

  • Cross-shard queries: Joins, aggregations, and searches may need results from every shard, increasing latency and coordination costs.
  • Uneven load: A skewed shard key can create a hot shard. For example, routing by city may overload a few high-volume cities.
  • Resharding is difficult: Changing shard count or key can require moving large amounts of data while keeping the service available.
  • Transactions are harder: A transaction spanning shards needs distributed coordination, which adds latency and failure cases.
  • Operational overhead: Backups, migrations, monitoring, and incident response must account for multiple database instances.
  • Application coupling: The application or routing layer must know how to locate data and handle shard failures.

I would generally try indexing, query optimization, read replicas, and vertical scaling first. Sharding is most appropriate when a single database is a measured storage or throughput bottleneck and the data has a stable, high-cardinality shard key.

TechnicalMediumUrban CompanySoftware EngineerTechnical/Managerial Round

12. What are B+ trees, and how are they used in indexing?

Model answer

A B+ tree is a balanced search tree designed for storage systems. It keeps keys sorted and remains shallow by allowing each node to contain many keys and child pointers.

  • Internal nodes contain separator keys and pointers to child pages; they guide the search but generally do not store the full row.
  • Leaf nodes contain sorted keys and row identifiers, or the actual rows for a clustered index. Leaves are linked in key order, making range scans efficient.
  • Search and updates: A lookup follows a root-to-leaf path. Inserts go to the appropriate leaf; when a page overflows, it splits and may propagate a separator key upward. Deletions may redistribute keys or merge underfull pages. These operations keep the tree balanced.

Because each disk page can hold many keys, a B+ tree has a small height and needs relatively few page reads. Its linked leaves are especially useful for queries such as “find bookings between these two dates,” where the database locates the first key and then scans adjacent leaves. This is why B+ trees are a common choice for database indexes.

TechnicalMediumUrban CompanySoftware EngineerTechnical/Managerial Round

13. What is the consistent hashing algorithm?

Model answer

Consistent hashing maps both data keys and database nodes onto the same circular hash space, or ring. A key is assigned to the first node encountered clockwise from its hash.

  1. Hash each node to a position on the ring.
  2. Hash each data key to a position.
  3. Starting at the key’s position, move clockwise to find the responsible node.
  4. When adding or removing a node, only keys in the affected ring interval need to move—not the whole dataset.
flowchart LR
    A[Hash data key] --> B[Find key position on ring]
    B --> C[Move clockwise]
    C --> D[Select first node]
    E[Add or remove node] --> F[Remap affected interval]
Diagram

In practice, systems use virtual nodes: each physical server gets multiple positions on the ring. This improves load balance and makes it easier to distribute a failed or removed server’s data among the remaining nodes. Replication can store each key on the next N distinct physical nodes around the ring.

TechnicalMediumUrban CompanySoftware EngineerTechnical/Managerial Round

14. What are AVL trees, and what is their self-adjusting property?

Model answer

An AVL tree is a self-balancing binary search tree. For every node, it maintains a balance factor:

height(left subtree) - height(right subtree)

The tree's invariant is that this factor is always -1, 0, or 1. After an insertion or deletion, the affected path is checked; if a node becomes unbalanced, the tree restores the invariant with rotations: left, right, left-right, or right-left.

This keeps the tree height at O(log n), so search, insertion, and deletion are all O(log n) in the worst case. For example, inserting sorted keys into an ordinary binary search tree can create a chain with O(n) operations; AVL rotations prevent that degeneration.

“Self-adjusting” here means the tree automatically rebalances after updates. It does not mean it restructures itself based on which keys are accessed most often; that behavior is associated with structures such as splay trees.

TechnicalMediumUrban CompanySoftware EngineerTechnical/Managerial Round

15. What is database sharding?

Model answer

Database sharding splits a dataset horizontally across multiple database servers, called shards. Each shard stores a subset of rows, selected by a shard key such as customer_id or city_id.

For example, an Urban Company bookings database might route bookings by customer_id so each customer’s bookings are stored together:

flowchart LR
    A[Booking request] --> B[Shard router]
    B -->|customer_id in range 1| C[Shard 1]
    B -->|customer_id in range 2| D[Shard 2]
    B -->|customer_id in range 3| E[Shard 3]
Diagram

Sharding increases storage capacity and can distribute read/write load. The shard key matters: a poor choice can create hot shards or make common queries require reading from many shards.

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