Razorpay interview questions & answers

20 real Razorpay interview questions with full model answers — Product & growth, System design, Coding, Technical. Drawn from the same verified bank ChannelPulse drills from (29 Razorpay questions in total).

CodingEasyRazorpaySoftware Engineer

1. First Unique Character in a String (LeetCode)

Model answer

The task

Return the index of the first character in a string that occurs exactly once. If no character is unique, return -1.

Key idea

Count how often each character appears, then scan the string from left to right. The first character with a count of one has the smallest qualifying index.

Approach

  1. Build a frequency map by counting every character.
  2. Scan the string in its original order.
  3. Return the index of the first character whose count is one.
  4. If the scan finishes without finding one, return -1.
class Solution:
    def firstUniqChar(self, s: str) -> int:
        # Count the occurrences of each character.
        counts = {}
        for char in s:
            counts[char] = counts.get(char, 0) + 1

        # Return the earliest character that appears once.
        for index, char in enumerate(s):
            if counts[char] == 1:
                return index

        return -1

Complexity:

  • Time: O(n), for counting and scanning the string.
  • Space: O(k), where k is the number of distinct characters stored in the map.

Common follow-ups

  • What if the string is streamed and cannot be revisited? Keep character counts and a queue of candidates; discard candidates once their count exceeds one.
  • What if characters come from a fixed, small alphabet? Use an array of counters instead of a hash map.
  • How would you return the unique character rather than its index? Return char at the matching position, with an appropriate sentinel if none exists.
CodingMediumRazorpayFrontend EngineerMachine Coding Round

2. Create a UI component in a framework of your choice, implementing a must-have feature and a nice-to-have feature.

Model answer

I’ll use React and make a reusable password field. The must-have is a show/hide control; the nice-to-have is live password-strength feedback. The strength indicator is guidance, not a substitute for server-side password policy enforcement.

import React, { useId, useState } from "react";

export default function PasswordField({
  label = "Password",
  value,
  onChange,
  autoComplete = "new-password",
}) {
  const id = useId();
  const [visible, setVisible] = useState(false);

  // A lightweight client-side hint; the server remains authoritative.
  const checks = [
    value.length >= 8,
    /[a-z]/.test(value) && /[A-Z]/.test(value),
    /\d/.test(value),
    /[^A-Za-z0-9]/.test(value),
  ];
  const score = checks.filter(Boolean).length;
  const strength = ["None", "Weak", "Fair", "Good", "Strong"][score];

  return (
    <div style={{ maxWidth: 360, display: "grid", gap: 8 }}>
      <label htmlFor={id}>{label}</label>
      <div style={{ display: "flex", gap: 8 }}>
        <input
          id={id}
          type={visible ? "text" : "password"}
          value={value}
          onChange={onChange}
          autoComplete={autoComplete}
          aria-describedby={`${id}-strength`}
          style={{ flex: 1, minWidth: 0 }}
        />
        <button
          type="button"
          onClick={() => setVisible((current) => !current)}
          aria-pressed={visible}
          aria-label={visible ? "Hide password" : "Show password"}
        >
          {visible ? "Hide" : "Show"}
        </button>
      </div>
      <div
        id={`${id}-strength`}
        role="status"
        aria-live="polite"
        aria-label={`Password strength: ${strength}`}
      >
        <div
          role="progressbar"
          aria-label="Password strength"
          aria-valuemin={0}
          aria-valuemax={4}
          aria-valuenow={score}
          style={{ height: 4, background: "#ddd", marginTop: 4 }}
        >
          <div
            style={{
              width: `${score * 25}%`,
              height: "100%",
              background: score >= 3 ? "#16803c" : "#c77700",
              transition: "width 150ms ease",
            }}
          />
        </div>
        <small>Strength: {strength}</small>
      </div>
    </div>
  );
}
  • The parent owns the value and passes its change handler, so the component works in a form without hiding form state.
  • The button is explicitly type="button", and the field and feedback have accessible labels and status semantics.
  • Complexity: O(n) per keystroke to evaluate the password checks; O(1) extra space.
CodingMediumRazorpaySoftware Engineer

3. Shortest Subarray to be Removed to Make Array Sorted (LeetCode)

Model answer

The task

Find the shortest contiguous segment to delete so the remaining elements are in non-decreasing order. The remaining elements on either side of the deleted segment stay in their original order.

Key idea

A valid result can keep a sorted prefix and a sorted suffix, deleting everything between them. Scan the boundary between those parts, matching prefix values to suffix values while preserving sorted order.

Approach

  1. Find the end of the longest non-decreasing prefix.
  2. If it reaches the array’s end, no deletion is needed.
  3. Find the start of the longest non-decreasing suffix.
  4. Consider deleting only the prefix or only the suffix as initial candidates.
  5. For each prefix endpoint, advance through the suffix until its value can follow the prefix value; update the minimum deletion length.
class Solution:
    def findLengthOfShortestSubarray(self, arr: list[int]) -> int:
        n = len(arr)
        if n <= 1:
            return 0

        # Locate the longest non-decreasing prefix.
        left = 0
        while left + 1 < n and arr[left] <= arr[left + 1]:
            left += 1

        if left == n - 1:
            return 0

        # Locate the longest non-decreasing suffix.
        right = n - 1
        while right > 0 and arr[right - 1] <= arr[right]:
            right -= 1

        # Delete everything before the suffix or after the prefix.
        shortest = min(right, n - left - 1)

        # Try joining each prefix endpoint to a compatible suffix value.
        suffix = right
        for prefix in range(left + 1):
            while suffix < n and arr[suffix] < arr[prefix]:
                suffix += 1

            # Remove the elements strictly between these two kept values.
            shortest = min(shortest, suffix - prefix - 1)

        return shortest

Complexity:

  • Time: O(n), since each pointer moves only forward.
  • Space: O(1), using a fixed number of indices.

Common follow-ups

  • What if the remaining array must be strictly increasing? Use strict comparisons when identifying sorted runs and when matching the two parts.
  • Can this be done with binary search? Yes; for each prefix endpoint, binary-search the suffix for the first compatible value, giving O(n log n) time.
  • What if the array is already sorted? The prefix scan reaches the end, so the answer is zero.
CodingMediumRazorpaySoftware Engineer

4. LRU Cache (LeetCode)

Model answer

The task

Design a cache with a fixed capacity that supports retrieving and inserting key-value pairs. When an insertion exceeds capacity, evict the item that has gone unused for the longest time.

Key idea

Use a hash map for direct key lookup and a doubly linked list to track recency. Keep the most recently used item at the front; the least recently used item is at the back.

Approach

  1. Create a map from keys to their linked-list nodes.
  2. Use dummy head and tail nodes so items can be added or removed without special cases at the ends.
  3. On a successful get, move the node to the front and return its value; return -1 if the key is absent.
  4. On put, update and promote an existing node, or add a new node at the front.
  5. If the cache is over capacity, remove the node just before the tail and delete its key from the map.
class _Node:
    def __init__(self, key: int = 0, value: int = 0):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.nodes = {}

        # Items are stored between these sentinels.
        self.head = _Node()
        self.tail = _Node()
        self.head.next = self.tail
        self.tail.prev = self.head

    def _remove(self, node: _Node) -> None:
        node.prev.next = node.next
        node.next.prev = node.prev

    def _add_to_front(self, node: _Node) -> None:
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def _make_most_recent(self, node: _Node) -> None:
        self._remove(node)
        self._add_to_front(node)

    def get(self, key: int) -> int:
        node = self.nodes.get(key)
        if node is None:
            return -1

        self._make_most_recent(node)
        return node.value

    def put(self, key: int, value: int) -> None:
        node = self.nodes.get(key)

        if node is not None:
            node.value = value
            self._make_most_recent(node)
            return

        node = _Node(key, value)
        self.nodes[key] = node
        self._add_to_front(node)

        if len(self.nodes) > self.capacity:
            least_recent = self.tail.prev
            self._remove(least_recent)
            del self.nodes[least_recent.key]

Complexity:

  • Time: O(1) for get and put; map and list operations take constant time.
  • Space: O(capacity); the map and list store at most the cache’s capacity of entries.

Common follow-ups

  • How would you make the cache thread-safe? Protect operations with a lock.
  • What if entries expire after a time-to-live? Track expiration times and remove expired entries during access or with a cleanup mechanism.
  • How would you support eviction by frequency instead of recency? Track access counts and organize entries by frequency.
CodingMediumRazorpaySoftware Engineer

5. Two Best Non-Overlapping Events (LeetCode)

Model answer

The task

Given events with a start time, end time, and value, choose at most two events that do not overlap. Return the greatest total value; events that meet at an endpoint overlap.

Key idea

Sort events by start time and build a suffix maximum of event values. For each event, binary-search for the first event starting strictly after it ends, then pair it with the best event from that point onward.

Approach

  1. Sort the events by start time and collect their start times.
  2. Build a suffix array where each position stores the greatest value from that event onward.
  3. Consider each event as the first selected event.
  4. Use bisect_right to find the first compatible event.
  5. Update the answer with the first event alone or with the best compatible event.
from bisect import bisect_right
from typing import List

class Solution:
    def maxTwoEvents(self, events: List[List[int]]) -> int:
        events.sort(key=lambda event: event[0])
        starts = [event[0] for event in events]

        # suffix_best[i] is the maximum value among events[i:].
        n = len(events)
        suffix_best = [0] * n
        suffix_best[-1] = events[-1][2]

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

        best_total = 0

        for start, end, value in events:
            # Strictly after end, since events sharing an endpoint overlap.
            next_index = bisect_right(starts, end)

            total = value
            if next_index < n:
                total += suffix_best[next_index]

            best_total = max(best_total, total)

        return best_total

Complexity:

  • Time: O(n log n), for sorting and one binary search per event.
  • Space: O(n), for the start-time list and suffix maxima.

Common follow-ups

  • What if you can select up to k events? Use dynamic programming over the number selected, combined with binary search for compatible next events.
  • What if events may share an endpoint without overlapping? Search for the first start time greater than or equal to the current end instead.
  • Can the suffix array be avoided? A min-heap can process events by end time while tracking the best value seen so far.
CodingMediumRazorpaySoftware Engineer

6. Decode String (LeetCode)

Model answer

The task

Decode a string where a number before brackets indicates how many times to repeat the bracketed section. Sections may be nested.

Key idea

Parse the input into a compact tree of literal fragments and repeat nodes instead of expanding nested sections immediately. Then traverse that tree to produce the decoded string, avoiding repeated copying of large intermediate strings.

Approach

  1. Scan the input, accumulating each repetition count.
  2. On an opening bracket, save the current fragment list and count, then start a new list.
  3. On a closing bracket, wrap the current list in a repeat node and add it to its parent.
  4. Traverse the resulting structure with an explicit stack, yielding literal fragments as they are needed.
  5. Join the yielded fragments into the result.
class Solution:
    def decodeString(self, s: str) -> str:
        # Each repeat node is a (count, fragments) tuple.
        current = []
        stack = []
        count = 0

        for char in s:
            if "0" <= char <= "9":
                count = count * 10 + int(char)
            elif char == "[":
                stack.append((current, count))
                current = []
                count = 0
            elif char == "]":
                parent, repeat = stack.pop()
                # Omit zero repetitions so traversal skips empty sections.
                if repeat:
                    parent.append((repeat, current))
                current = parent
            else:
                current.append(char)

        def fragments():
            # Frames contain a fragment list, its next index, and
            # how many times to traverse that list.
            frames = [[current, 0, 1]]

            while frames:
                parts, index, remaining = frames[-1]

                if index == len(parts):
                    remaining -= 1
                    if remaining == 0:
                        frames.pop()
                    else:
                        frames[-1][1] = 0
                        frames[-1][2] = remaining
                    continue

                node = parts[index]
                frames[-1][1] += 1

                if isinstance(node, str):
                    yield node
                else:
                    repeat, nested = node
                    frames.append([nested, 0, repeat])

        return "".join(fragments())

Complexity:

  • Time: O(n + m), where n is the encoded length and m is the decoded length.
  • Space: O(n + m) for the parsed structure and returned string.

Common follow-ups

  • How would you handle malformed input? Validate bracket balance and ensure each opening bracket has a preceding count.
  • How could this support streaming output? Yield decoded fragments to a consumer instead of joining them into one string.
  • What if the grammar adds escaping or other operators? Extend the parser with explicit rules and represent each operation as a distinct node.
CodingMediumRazorpaySoftware Engineer

7. Most Beautiful Item for Each Query (LeetCode)

Model answer

The task

Each item has a price and a beauty score. For every query price, return the greatest beauty among items whose price is no higher than the query, or zero if no item qualifies.

Key idea

Sort items by price and build a prefix maximum of beauty. Then binary search for the last price that is within each query’s limit, and look up its prefix maximum.

Approach

  1. Sort the items by price.
  2. Build a list of sorted prices and a parallel list of prefix maximum beauties.
  3. For each query, use bisect_right to find how many item prices are at most the query.
  4. If that count is zero, return zero; otherwise use the prefix maximum immediately before that position.
from bisect import bisect_right
from typing import List

class Solution:
    def maximumBeauty(
        self, items: List[List[int]], queries: List[int]
    ) -> List[int]:
        items.sort(key=lambda item: item[0])

        prices = []
        prefix_best = []
        best = 0

        for price, beauty in items:
            best = max(best, beauty)
            prices.append(price)
            prefix_best.append(best)

        answers = []
        for query in queries:
            # The insertion point is just past all prices <= query.
            index = bisect_right(prices, query)
            answers.append(prefix_best[index - 1] if index else 0)

        return answers

Complexity:

  • Time: O(n log n + q log n), for sorting and binary-searching each of the q queries.
  • Space: O(n), for the sorted price and prefix-maximum lists.

Common follow-ups

  • What if queries arrive one at a time? Keep the preprocessed arrays and binary-search each new query in O(log n).
  • What if item prices are updated? The sorted prefix maxima may become stale; use an ordered structure or rebuild the preprocessing.
  • Can queries be processed offline? Sort queries by limit and scan the items once, maintaining the best beauty seen so far.
  • What if no qualifying item should return a different default? Replace the zero used for the no-match case with the required value.
CodingMediumRazorpaySoftware Engineer

8. Merge Intervals (LeetCode)

Model answer

The task

Given a collection of intervals, combine every pair that overlaps and return the resulting non-overlapping intervals. The result should be ordered by starting point.

Key idea

Sort intervals by their start. Then scan once, keeping the most recently merged interval; each next interval either extends it or starts a new one.

Approach

  1. Sort the intervals by their start value.
  2. Initialize the result with the first interval, if any.
  3. For each remaining interval, compare its start with the end of the last result interval.
  4. If they overlap, update that end to the larger of the two ends.
  5. Otherwise, append the interval as a new result.
from typing import List

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if not intervals:
            return []

        intervals.sort(key=lambda interval: interval[0])
        merged = [intervals[0]]

        for start, end in intervals[1:]:
            # The intervals overlap, so extend the last merged interval.
            if start <= merged[-1][1]:
                merged[-1][1] = max(merged[-1][1], end)
            else:
                # No overlap: this interval begins a new merged range.
                merged.append([start, end])

        return merged

Complexity: Time: O(n log n), dominated by sorting n intervals.

Complexity: Space: O(n) for the merged result; sorting may also use up to O(n) space.

Common follow-ups

  • What if intervals that only touch at an endpoint should remain separate? Use start < merged[-1][1] as the overlap test.
  • How would you merge intervals as they arrive in sorted order? Skip sorting and apply the same scan, processing each interval once.
  • What if intervals are inserted one at a time into an already merged collection? Use binary search to find the insertion point, then merge neighboring overlaps.
Product & growthMediumRazorpayProduct ManagerProblem solving round

9. Should a commerce app such as BigBasket have default signup after an app is downloaded from the Android Play Store?

Model answer

Clarify & scope

I’d distinguish automatically creating an account from making signup the default screen or requiring registration before browsing. I’ll assume the proposal is to create or initiate an account immediately after Play Store installation. An install does not, by itself, establish the user’s identity, intent, or informed consent, so I would not silently create a fully active account.

User segments & pain points

For a first-time grocery shopper, the immediate job is usually to check whether BigBasket serves their area, see relevant products, and understand delivery availability. A signup wall before those checks creates friction before the app has shown value. Returning users, by contrast, benefit from a fast sign-in and saved addresses, but can be recognized through an explicit login or account-recovery flow.

Goals & success metrics

The North Star would be incremental first completed orders per install. I’d track activation through serviceability check, product discovery, cart creation, and first order—not just accounts created. Guardrails would include uninstall rate, consent complaints, duplicate or abandoned accounts, OTP cost and failure, privacy incidents, and first-order cancellations.

Solutions

  • Automatically open directly into signup. This may increase account records, but risks poor consent, low-quality accounts, and immediate abandonment.
  • Let users browse first, then request signup when they need to save a cart, place an order, or use account-specific benefits.
  • Offer an optional, clearly explained one-tap or phone-based signup, with consent and terms presented before account creation.

Recommendation: I would not default users into an account just because they installed the app. I’d use guest browsing and progressive signup, asking for only the information required to fulfill an order at checkout. Make the value exchange explicit—such as order tracking or saved addresses—and provide an easy existing-customer sign-in.

Prioritization & trade-offs

I’d first remove the signup barrier to serviceability and product discovery, then test where the signup prompt performs best. Deferring signup can reduce early account capture and make personalization less immediate. However, an install-triggered account may inflate registrations without increasing orders and can create trust and compliance risks. I’d optimize for completed, retained customers rather than registration volume.

MVP, measurement & rollout

I’d test the current flow against guest browsing with signup at checkout, randomizing eligible new installs. Measure first-order conversion, time to first order, and repeat purchase, while monitoring uninstall, support, and privacy guardrails. Roll out incrementally, check results across acquisition channels and Android versions, and retain a rollback option if order quality or consent outcomes worsen.

Product & growthMediumRazorpayProduct ManagerTechnology grounding round

10. How would you define non-functional requirements for an at-scale product such as Flipkart’s PWA mobile site?

Model answer

Clarify & scope

I’d start by defining the PWA’s primary job: help mobile shoppers discover products, make confident purchase decisions, and complete checkout on a wide range of devices and networks. I’d identify the critical journeys—landing, search, product detail, cart, payment—and set requirements by journey rather than treating the site as one uniform experience.

User segments & pain points

I’d prioritize shoppers on low-end Android devices and unreliable or expensive mobile data. Slow page loads, large downloads, interrupted sessions, and checkout errors directly cost both customers and Flipkart sales. I’d also account for returning shoppers who expect cart and session continuity across visits.

Goals & success metrics

The North Star would be successful mobile orders per eligible shopper, interpreted alongside conversion and reliability. I’d define measurable targets, for example:

  • Performance: At the 75th percentile, LCP under 2.5 seconds, INP under 200 ms, and CLS under 0.1 on supported devices and networks.
  • Reliability: At least 99.9% monthly availability for critical shopping and checkout APIs; instrument error rates by endpoint and device class.
  • Checkout: Track checkout completion, payment initiation failures, duplicate orders, and recovery after network interruption.
  • Compatibility and accessibility: Support agreed Android browser versions and screen sizes; test keyboard, screen-reader, and contrast requirements.

I’d set final targets from baseline data, business impact, and engineering cost. Guardrails include data usage, security incidents, and checkout correctness.

Solutions

I’d define budgets for page weight, JavaScript execution, and API latency; use responsive images and lazy loading; and reserve service-worker caching for static assets and carefully selected non-sensitive content. I would not serve stale prices, inventory, or payment state as authoritative. APIs should support timeouts, bounded retries, and idempotency where operations can create an order or payment.

Prioritization & trade-offs

I’d prioritize performance and checkout resilience before offline features. Caching improves repeat visits and resilience, but adds invalidation and stale-data risk. Rich client-side features may improve interaction, but can slow low-end phones. I’d test on real devices and throttled networks, not just desktop emulation.

MVP, measurement & rollout

Instrument real-user monitoring by device, network, geography, and funnel step; complement it with synthetic tests and load tests. Release performance changes behind flags, compare treatment and control on conversion and Core Web Vitals, and monitor errors and payment outcomes. Define incident thresholds, rollback criteria, and an owner for each SLO. I’d review the requirements as traffic, device mix, and the product’s most valuable journeys change.

Product & growthMediumRazorpayProduct ManagerProblem solving round

11. Should Oyo’s mobile paid ad take users to an app download or to the mobile site?

Model answer

Clarify & scope

I’d clarify the campaign objective: immediate hotel booking, qualified leads, or app installs expected to drive future bookings. I’d also ask whether Oyo already has a mobile website capable of completing the same booking journey, whether the user has the app installed, and how the campaign is attributed. I would judge the choice by incremental profitable bookings, not clicks or installs alone.

User segments & pain points

For a user arriving from a paid ad with a specific destination and travel date, intent is already high. Sending that person to an app store adds steps and may lose the search context before they can check availability. A user who already has the app may benefit from a direct deep link into the relevant property or search results. Lower-intent audiences may value app features or repeat-booking convenience, but still need a clear reason to install.

Goals & success metrics

The North Star would be incremental completed bookings per advertising spend, with contribution margin or return on ad spend as the business measure. I’d track landing-to-search, search-to-property, checkout completion, cancellations, and app installs that later produce bookings. Guardrails include page latency, failed deep links, attribution loss, and booking quality.

Solutions

  • Send every paid click to the app store: this can support retention, but creates install friction and risks losing intent and campaign context.
  • Send every click to the mobile website: this offers immediate access, but may underuse app capabilities for existing users and returning customers.
  • Route users by install state and campaign intent: open a relevant in-app deep link for installed users; otherwise land on a fast mobile web page that preserves the destination and dates, with an optional app prompt.

Recommendation: I’d use the third approach. For a high-intent hotel ad, mobile web should be the reliable default for users without the app; for installed users, use a deep link. If the user later installs, deferred deep linking should restore the intended property or search where technically and privacy-wise supported.

Prioritization & trade-offs

I’d prioritize a fast, functional web booking path and correct deep links before promoting app downloads. App experiences may improve repeat use, but an install-first strategy adds acquisition friction and can over-credit installs that would not have become bookings. Web may have weaker retention or some platform limitations, so I’d compare the full booking lifecycle rather than assume either channel wins.

MVP, measurement & rollout

I’d run a randomized test within comparable campaign and audience cohorts: app-store-first versus mobile-web-first, with existing app users routed consistently. Measure incremental completed bookings and margin per ad spend, plus funnel and guardrail metrics. Roll out by campaign only after validating attribution, deep-link behavior, and cancellation rates; keep a holdout to estimate true incrementality.

Product & growthHardRazorpayProduct ManagerProblem solving round

12. Flipkart’s app conversion dropped by 10% yesterday.

The full question

Flipkart’s app conversion dropped by 10% yesterday. How would you diagnose the cause?

Model answer

Clarify & scope

First, I’d confirm what “conversion” means—such as app sessions that result in a completed order—and whether the 10% drop is relative or percentage-point. I’d compare yesterday with the same weekday and time window, then check whether the metric change is statistically meaningful or caused by delayed data, a tracking change, or an incomplete reporting window.

Define metric(s)

My primary metric would be session-to-order conversion, with the numerator and denominator defined consistently. I’d also monitor each funnel step: product view, add to cart, checkout start, payment attempt, and order confirmation. Guardrails would include revenue per session, cancellations, payment failure rate, latency, and crash rate.

Break down

I’d segment by app version, OS, device, geography, acquisition channel, new versus returning users, and payment method. Then I’d find the first funnel step where conversion diverges from its baseline.

flowchart LR
  A[App session] --> B[Product view]
  B --> C[Add to cart]
  C --> D[Checkout]
  D --> E[Payment attempt]
  E --> F[Order confirmed]
Diagram

Hypotheses

I’d rank causes by likely impact and how quickly we can test them:

  • Measurement or release issue: event definitions, app release, crash, or latency changed.
  • Traffic mix: a campaign, geography, or referral source brought lower-intent users.
  • Experience or availability: search, catalog, inventory, pricing, or checkout degraded.
  • Payment problem: a bank, payment method, or gateway has higher declines or timeouts.
  • External change: a competitor promotion, holiday effect, or supply disruption.

How to investigate

I’d compare the funnel by segment against the prior baseline, inspect release and incident timelines, and validate analytics events against backend order records. For a payment-step drop, I’d check authorization, timeout, and error rates by payment method and provider—for example, whether a gateway or issuer issue is concentrated in one cohort. I’d also compare app health and inventory data before attributing the change to user behavior.

Decision & guardrails

If a recent release is strongly implicated, I’d consider a staged rollback or feature-flag disable while monitoring recovery. For a provider-specific payment issue, I’d coordinate routing or fallback options with payments teams. I’d communicate the leading cause, confidence, affected segments, and next update time, then verify recovery without worsening fraud, cancellations, or payment costs.

Product & growthHardRazorpayProduct ManagerProduct thinking round

13. How would you design a mobile app for parents at an amusement park?

Model answer

Clarify & scope

I’d design for parents navigating a large amusement park with children, where the core job is to enjoy the visit while keeping the group safe and reducing time spent planning. I’d assume the park already has maps, schedules, and ride rules, and focus the app on coordinating a family’s day rather than replacing staff or safety procedures.

User segments & pain points

I’d prioritize parents with young children. They need to find age-appropriate attractions, understand height and accessibility requirements, avoid unexpectedly long waits, locate restrooms and quiet areas, and reunite if the group separates. Parents with teenagers have different needs, but I’d validate the primary segment before designing for everyone.

Goals & success metrics

The North Star would be families completing more of their intended activities with less avoidable friction. Supporting measures include itinerary completion, time to find an attraction, use of wait-time guidance, and post-visit satisfaction. Guardrails include safety incidents, accessibility complaints, inaccurate wait-time reports, notification overload, and battery consumption.

Solutions

I’d consider a personalized, flexible itinerary; a live map with attraction status, facilities, and step-free routes; and family coordination tools such as shared plans and a clear meeting point. The app could show ride suitability based on children’s heights and ages, but should let parents confirm details and avoid making safety judgments on their behalf.

Recommendation: Build a family day planner centered on a live map and a small set of high-value tasks: choose attractions, see requirements and estimated waits, find nearby essentials, and adjust the plan when conditions change. Make core information available in a low-connectivity mode and keep directions legible while walking.

Prioritization & trade-offs

I’d rank features by how much stress and wasted time they remove, then weigh development effort and operational dependencies. Accurate, frequently updated park data is more valuable than a sophisticated recommendation engine, so I’d invest in reliable attraction hours, closures, and wait-time estimates first. Location sharing can help families coordinate, but should be opt-in, time-limited, and easy to pause.

MVP, measurement & rollout

I’d pilot with a few attractions and families, testing both the map and itinerary flow. I’d measure task completion, route-finding success, data accuracy, and satisfaction, and observe where parents struggle while using the app with children. I’d expand only after validating accessibility and operational data quality, with clear fallback guidance to park signage and staff.

Product & growthHardRazorpayProduct ManagerProduct thinking round

14. How would you design an app for Swiggy’s delivery executives?

Model answer

Clarify & scope

I’d design for delivery executives completing restaurant pickups and customer drop-offs, while recognizing that their work also depends on dispatch, support, and payments. I’d optimize the app for reliable task completion in noisy, low-connectivity conditions—not for adding more features or maximizing time online.

User segments & pain points

I’d focus first on active delivery executives, including new joiners and experienced riders. Their biggest pains are unclear pickup instructions, inaccurate locations, waiting at restaurants, unsafe routing, confusing earnings, and difficulty getting help when an order goes wrong. New joiners need more guidance; experienced riders need speed and control.

Goals & success metrics

The North Star would be successful deliveries completed safely per active executive-hour. I’d track pickup and delivery completion, median time at each step, failed delivery rate, support resolution time, app crashes, and executive satisfaction. Guardrails would include late-delivery rate, safety incidents, cancellations, and earnings fairness; I would not optimize speed at the expense of safety.

Solutions

I’d explore three ideas: a simplified task-first home screen; context-aware pickup and drop-off guidance with landmark notes and customer contact options; and a lightweight help flow for delays, incorrect addresses, or customer unavailability. The app should make the next action obvious, support local languages and large touch targets, and save essential task details for temporary network loss.

Recommendation: Start with a reliable task flow and fast exception handling. Show order status, location, directions, and the next action together, with clear confirmation before consequential steps. Build in route choices rather than forcing a single route, and make emergency help accessible throughout a delivery.

Prioritization & trade-offs

I’d prioritize by impact on completed deliveries and executive effort saved, balanced against safety and implementation complexity. I’d build navigation and task-state reliability before advanced personalization. Offline support adds complexity, but is worthwhile for preserving instructions and task status during short outages; sensitive updates should sync when connectivity returns.

MVP, measurement & rollout

I’d pilot the new flow with a small, varied set of zones and compare it with the existing experience. I’d instrument each task transition and interview executives after shifts. Roll out gradually only if completion and support outcomes improve without worsening safety, cancellation, or earnings guardrails. I’d use the findings to refine the flow before expanding to more regions and languages.

Product & growthHardRazorpayProduct ManagerProblem solving round

15. How would you improve Amazon’s signup process to increase conversion?

Model answer

Clarify & scope

I’d define signup conversion as the share of eligible visitors who complete account creation, but I would not optimize that number in isolation. The goal is to help shoppers reach a useful first purchase with as little friction as possible, while preserving account security and a good repeat-purchase experience. I’d first clarify whether the largest loss happens before signup, during verification, or when signup is required at checkout.

User segments & pain points

I’d focus on first-time shoppers arriving with clear purchase intent, especially mobile users. They may be ready to buy but see a long form, password requirements, or an email/phone verification step before they understand the value of an account. Returning users who cannot access an account are a separate recovery problem and should be measured separately.

Goals & success metrics

The North Star would be incremental first orders per eligible visitor, not completed registrations alone. Leading metrics would include signup completion, time to first meaningful action, and checkout completion. Guardrails would include account takeover, fraud, duplicate accounts, verification cost, and customer support contacts.

Solutions

  • Reduce the form to essential information and explain why each field is needed.
  • Offer a familiar, secure one-time-code or supported identity option, with clear recovery paths and accessible error messages.
  • Let shoppers browse and build a cart before asking them to sign in; prompt at checkout and save details after purchase where consent and policy allow.

Recommendation: I’d test progressive signup: make account creation quick, but defer the requirement until the user reaches a moment where an account provides clear value. Keep an explicit sign-in path for existing customers. This avoids forcing registration on low-intent visitors while capturing details needed to complete an order.

Prioritization & trade-offs

I’d prioritize form simplification and a progressive prompt because they address common friction without requiring a complex identity integration. A one-time code can reduce password friction, but may add delivery cost and fail when messages are delayed. Guest checkout can increase first-order conversion, but may reduce account attachment and make order history less discoverable; I’d measure those effects rather than assume registration is always better.

MVP, measurement & rollout

I’d run a randomized experiment on eligible new users, comparing the existing flow with progressive signup. I’d evaluate first-order conversion and downstream repeat purchase over a suitable window, with fraud and support guardrails. Roll out gradually by platform and region, inspect funnel changes by segment, and keep a rollback path if security or order quality deteriorates.

Product & growthHardRazorpayProduct ManagerBusiness acumen round

16. How would you approach pricing a new product offering such as Swiggy Super, and do you think Swiggy may be underpricing it?

Model answer

Clarify & scope

I’d treat Swiggy Super as a two-sided value proposition: customers pay for convenience and savings, while Swiggy must cover the benefits without damaging contribution margin or restaurant economics. I’d first clarify the exact benefit bundle, eligible orders, and whether the goal is acquisition, frequency, retention, or profit.

User segments & pain points

I’d focus on frequent food-delivery customers, especially those who order several times a month and are sensitive to delivery fees. They need predictable savings and a clear sense of whether the membership is worth renewing. Lower-frequency users may prefer paying per order, while heavy users can be highly valuable but also expensive to serve.

Goals & success metrics

The North Star would be incremental contribution profit per eligible customer over the membership lifecycle. I’d track paid conversion, renewal, order frequency uplift versus a control group, average order value, benefit redemption, delivery and discount costs, and customer support contacts. Guardrails: restaurant participation, delivery reliability, and margins on orders that would have happened anyway.

Solutions

  1. Offer a simple membership with benefits customers can understand, such as delivery-fee savings, and clearly show the break-even point.
  2. Test a lower-priced entry tier and a premium tier only if there are distinct, valued benefits—not just more discounting.
  3. Use targeted offers for new or lapsed customers, rather than subsidizing all members equally.

Recommendation: Price based on measured incremental value, not the total face value of benefits. I’d estimate a customer’s expected monthly benefit and willingness to pay, then test prices and bundles by city and order-frequency segment.

Prioritization & trade-offs

To assess whether Swiggy is underpricing Super, I’d compare membership revenue plus incremental order contribution against benefit costs, acquisition costs, and servicing costs. If frequent members renew strongly, redeem benefits heavily, and still produce healthy incremental contribution, there may be room to raise price or introduce a premium tier. If retention depends on the current price, or benefits mostly subsidize orders customers would have placed anyway, raising the fee could destroy value. I would not call it underpriced from price alone.

MVP, measurement & rollout

Run a randomized price-and-bundle test among comparable users, with city and frequency stratification. Evaluate contribution profit and renewal across at least one renewal cycle; monitor complaints and order frequency as guardrails. Roll out gradually only if the higher-value offer improves long-term economics without materially increasing churn. A clear savings calculator at purchase can improve trust regardless of the chosen price.

System designHardRazorpayProduct ManagerProduct thinking round

17. How would you design an elevator system?

Model answer

1. Requirements & scale

Functional requirements

  • Serve passenger hall calls and cabin floor selections; assign elevators and update arrival estimates.
  • Support multiple elevators, floors, accessibility needs, maintenance mode, and emergency operation.
  • Provide operators with fleet health, alarms, and usage data.

Non-functional requirements

  • Safety is paramount: dispatch software must never replace certified, independent safety circuits.
  • Local control must continue during network or cloud outages; passenger-facing response should be fast and predictable.
  • Make assignments fairly, avoid unnecessary stops, and degrade safely when a car or sensor fails.

Assumptions and estimates: Consider a 100-floor building with 20 elevators and 2,000 trips per hour at peak. That is about 0.56 trips per second; even allowing 100 sensor events per trip, the building generates only about 56 events per second. A small time-series record of 200 bytes per event is roughly 1 GB/day, or about 0.4 TB/year before replication and retention policies. The control loop runs locally on a millisecond-to-second timescale; cloud telemetry is not in the critical path.

2. High-level architecture

I would separate safety-critical, real-time motion control from supervisory dispatch and cloud services. A certified elevator controller handles brakes, doors, speed limits, and interlocks. A local group controller coordinates dispatch across cars. The cloud provides fleet monitoring, configuration, and analytics, but cannot directly issue unsafe motion commands.

flowchart TD
  subgraph Client["Client"]
    P[Passenger panel]
    O[Operator console]
  end
  subgraph Edge["Edge/CDN"]
    G[Building gateway]
  end
  subgraph LB["Load Balancer"]
    L[Cloud ingress]
  end
  subgraph Services["API / Services"]
    D[Dispatch service]
    M[Monitoring API]
    C[Configuration service]
  end
  subgraph Cache["Cache"]
    X[Building state cache]
  end
  subgraph DB["Datastores"]
    R[(Building configuration SQL)]
    T[(Telemetry time series)]
  end
  subgraph MQ["Message Queue"]
    Q[Telemetry topic]
  end
  subgraph Workers["Workers"]
    W[Alert and analytics workers]
  end
  P -->|hall and cabin calls| G
  G -->|local requests| D
  D -->|assignments| G
  G -->|status and events| L
  O -->|monitor and configure| L
  L --> M
  L --> C
  M --> X
  C --> R
  G -->|telemetry| Q
  Q --> W
  W --> T
  W -->|alerts| M
Diagram

The diagram shows the supervisory path; the local controller remains able to operate if the cloud, gateway, or building network fails.

3. API design

  • POST /v1/buildings/{buildingId}/calls — submit a hall call with floor, direction, and request ID.
  • POST /v1/elevators/{elevatorId}/selections — submit a cabin floor selection.
  • GET /v1/buildings/{buildingId}/status — retrieve current car positions, modes, and estimated waits.
  • POST /v1/elevators/{elevatorId}/maintenance — authorized maintenance-mode change.
  • POST /v1/telemetry/batches — gateway uploads buffered, timestamped events.

Call requests are idempotent by request ID. Commands include a version and expiry so stale messages cannot be applied after a restart or network delay.

4. Data model & storage

  • Store buildings, floors, elevator capabilities, and configuration in a relational database. Key configuration reads are cached at the building gateway.
  • Keep live car state—position, direction, door state, mode, and assigned stops—in memory on the group controller, with periodic snapshots for recovery.
  • Write append-only sensor and trip events to a time-series store, partitioned by building and time. Retain high-resolution data briefly and roll up aggregates for longer-term analytics.
  • Do not treat the cloud database as authoritative for instantaneous car position; it can be stale during connectivity loss.

5. Deep dive

The dispatch objective is to minimize passenger wait and journey time while respecting direction, capacity, and accessibility constraints. For each eligible car, estimate pickup time from distance, direction, door cycles, and already committed stops. A simple score is cost = α × pickupSeconds + β × addedPassengerSeconds + γ × loadPenalty + δ × imbalancePenalty; choose the lowest-cost car, with weights tuned using simulation and observed outcomes. Avoid repeatedly moving a call between cars by adding reassignment hysteresis.

sequenceDiagram
  participant P as Passenger panel
  participant G as Local group controller
  participant E as Elevator controller
  participant C as Cloud monitoring
  P->>G: Hall call with request ID
  G->>G: Check state and score eligible cars
  G->>E: Assign pickup stop
  E-->>G: Acknowledge assignment and state
  G-->>P: Show assigned car and estimate
  G->>C: Send buffered trip and health events
  Note over E: Certified safety logic independently controls motion and doors
Diagram

If an elevator becomes unavailable, the group controller removes it from the candidate set and reassigns outstanding calls. If the group controller fails, a standby takes over from a recent snapshot; if that is unavailable, local elevator controllers continue safe operation, even if group coordination is reduced.

6. Scale, bottlenecks & trade-offs

The building is the natural isolation boundary: dispatch and state are local to each building, so scaling the cloud fleet does not add latency to control. Replicate cloud services across availability zones, partition telemetry by building and time, and use bounded gateway queues with backpressure. Monitor command latency, controller heartbeat, queue depth, stale-state age, missed calls, wait-time percentiles, and fault rates.

I would choose availability and local safety over globally consistent telemetry: dashboards may briefly show delayed data, but a network partition must not stop safe elevator operation. Dispatch is synchronous within the local controller; analytics and alerts are asynchronous. That makes the system resilient and keeps cloud outages away from passenger control, at the cost of eventually consistent fleet reporting.

System designHardRazorpayProduct ManagerTechnology grounding round

18. Can you describe the technology architecture of your current product in as much detail as possible?

Model answer

1. Requirements & scale

I’d answer this with the architecture of the product I actually own, being explicit about what I know and where I’m simplifying. Since the specific product isn’t given here, I’ll use a representative online payments platform to make the answer concrete; I would replace the scale and boundaries with my product’s real numbers in an interview.

Functional requirements

  • Accept payment requests from merchant integrations and route them to the appropriate payment method or provider.
  • Track an auditable payment lifecycle, handle asynchronous provider updates, and expose status to merchants.
  • Support refunds, reconciliation, risk checks, and operational investigation.

Non-functional requirements

  • Correctness and idempotency matter more than accepting a duplicate financial operation.
  • Keep checkout latency low, isolate provider failures, protect sensitive data, and maintain a durable audit trail.
  • Separate payment orchestration from settlement and reporting, which have different timing and consistency needs.

Illustrative scale: At 10 million attempts/day, average load is about 116 requests/second. Assuming a 10× peak, plan for roughly 1,200 requests/second, with additional headroom for retries and webhook bursts. At 2 KB of durable metadata per attempt, that is about 20 GB/day or 7.3 TB/year before indexes, replicas, and retention. Provider calls and network variability—not raw compute—are likely the main latency and availability constraints.

2. High-level architecture

I’d describe the system as a synchronous path for creating and initiating a payment, followed by asynchronous processing for provider updates, notifications, and reconciliation. The payment record and its state transitions are authoritative; caches and search indexes are derived views.

flowchart TD
  subgraph Client["Client"]
    U[Merchant checkout]
    A[Merchant API]
  end
  subgraph Edge["Edge/CDN"]
    E[WAF and API gateway]
  end
  subgraph LB["Load Balancer"]
    L[Regional ingress]
  end
  subgraph Services["API / Services"]
    P[Payment API]
    R[Routing and risk]
    V[Provider adapters]
    H[Webhook service]
  end
  subgraph Cache["Cache"]
    C[Idempotency and config cache]
  end
  subgraph Datastores["Datastores"]
    S[(Payments SQL)]
    O[(Object storage)]
    X[(Search index)]
  end
  subgraph MQ["Message Queue"]
    Q[Payment events]
  end
  subgraph Workers["Workers"]
    W[Webhook and reconciliation workers]
  end
  U -->|create payment| E
  A -->|payment and status APIs| E
  E --> L
  L --> P
  P -->|dedupe and merchant config| C
  P -->|persist state| S
  P --> R
  R --> V
  V -->|authorization request| B[Payment provider]
  B -->|response or callback| V
  V -->|state transition and outbox| S
  S -->|publish committed events| Q
  Q --> W
  W -->|merchant notifications| H
  W -->|reconciliation files| O
  W -->|reporting projection| X
Diagram

3. API design

  • POST /v1/payments — create a payment; require an idempotency key and merchant-scoped request.
  • GET /v1/payments/{paymentId} — retrieve authoritative payment status.
  • POST /v1/payments/{paymentId}/capture — capture an authorized payment where supported.
  • POST /v1/refunds — request a refund with its own idempotency key.
  • POST /v1/webhooks/provider/{provider} — receive authenticated provider callbacks.
  • GET /v1/settlements/{settlementId} — retrieve settlement and reconciliation status.

4. Data model & storage

I would keep payment lifecycle and financial records in a relational database because transactions, constraints, and auditable state transitions are essential. A payments record contains payment ID, merchant ID, amount in minor units, currency, current state, provider reference, and version. An append-only payment_events table records transitions and reasons. Refunds and settlements are separate entities linked to the payment.

Partition large tables by time and a stable merchant or payment key, while ensuring a payment’s transitions are handled consistently. Use a unique constraint on (merchant_id, idempotency_key) to prevent duplicate creation. Store large reconciliation files in object storage, and use a search index only for operational queries—not as the source of truth. Cache merchant configuration and bounded idempotency responses, with invalidation/versioning so configuration changes are safe.

5. Deep dive

The critical path is creating a payment without creating duplicate charges. The API validates the request, checks the idempotency key, applies risk and routing policy, and writes the initial state before or as it initiates the provider operation. The exact provider interaction depends on its protocol; the system must persist a stable internal ID and provider correlation ID so that timeouts can be resolved rather than blindly retried.

I’d use a transactional outbox: commit the payment state change and an event row in the same SQL transaction, then publish that event asynchronously. A consumer can safely retry because it tracks event IDs. Provider callbacks are authenticated, deduplicated, and validated against the expected payment and allowed state transitions. If the provider times out, mark the result as pending or unknown and query/reconcile it; do not report failure and automatically create a second charge.

sequenceDiagram
  participant M as Merchant
  participant P as Payment API
  participant D as Payments database
  participant G as Provider gateway
  participant B as Payment provider
  participant Q as Event queue
  M->>P: Create payment with idempotency key
  P->>D: Check key and persist payment intent
  P->>G: Initiate provider operation
  G->>B: Authorization request
  B-->>G: Result or timeout
  G->>D: Commit state and outbox event
  D->>Q: Publish committed event
  Q-->>M: Webhook worker sends status update
  B-->>P: Later callback or reconciliation result
Diagram

6. Scale, bottlenecks & trade-offs

Scale API services horizontally and isolate each provider behind an adapter, timeout, circuit breaker, and concurrency limit. Partition durable data by a key that preserves payment-level locality; replicate databases across zones and test backup restoration. Use regional deployment carefully: a payment should have one clear home region or ownership strategy to avoid conflicting writes. Queue consumers need bounded retries, dead-letter handling, and replay tooling with idempotent effects.

I’d favor strong consistency for payment state and idempotency, while accepting eventual consistency for dashboards, search, and notifications. Provider calls are synchronous when checkout needs an immediate result, but callbacks, webhooks, and reconciliation are asynchronous. This adds operational complexity and delayed status cases, but prevents transient provider or network failures from turning into duplicate financial operations. I’d finish by showing the actual system boundaries, p95/p99 latency, success and timeout rates, and one real failure mode from my product rather than presenting this illustrative architecture as personal experience.

System designHardRazorpayFrontend EngineerSystem design round

19. Create an optimized web app.

Model answer

1. Requirements & scale

Assumption: I’m designing a fast, accessible Razorpay merchant dashboard for viewing payments, filtering transactions, and opening payment details. It is a read-heavy web app; payment execution remains in the payments platform.

  • Functional: authenticate merchants; show a recent payments view; filter and paginate; open transaction details; handle loading, empty, error, and permission states.
  • Non-functional: fast first render on mid-range mobile devices, accessible interactions, secure merchant data isolation, resilient operation, and no stale or duplicated financial actions.
  • Performance targets: p75 LCP under 2.5 seconds, interaction response under 200 ms for local actions, and dashboard API p95 under 300 ms for common queries.

For sizing, assume 100,000 daily merchant users and 20 dashboard sessions per user: 2 million sessions/day. At five API calls per session, that is 10 million calls/day, about 116 average RPS; sizing for a 10× peak gives roughly 1,200 RPS. If the dashboard reads 10 million payment records/day at 1 KB each, that is about 10 GB/day of raw record growth before indexes and replication. The dashboard should query the payment system’s read model rather than scan its write tables.

2. High-level architecture

Serve versioned, content-hashed frontend assets from a CDN. Render the initial dashboard shell on the server for a quick first paint, then hydrate interactive areas. A backend-for-frontend (BFF) provides dashboard-specific, permission-checked APIs and aggregates read-model data. Cache only safe, short-lived data; never use a shared cache key that could cross merchant boundaries.

flowchart TD
  subgraph Client
    B["Merchant browser"]
  end
  subgraph Edge["Edge and CDN"]
    CDN["CDN assets and edge cache"]
    WAF["WAF and rate limits"]
  end
  subgraph LB["Load Balancer"]
    L["Regional load balancer"]
  end
  subgraph API["API and Services"]
    SSR["Web SSR and BFF"]
    AUTH["Auth and permissions"]
    PAY["Payments read API"]
  end
  subgraph Cache
    C["Tenant-scoped Redis cache"]
  end
  subgraph DB["Datastores"]
    R["Payments read replica"]
    S["Merchant and access SQL"]
  end
  subgraph MQ["Message Queue"]
    Q["Payment change events"]
  end
  subgraph Workers
    IDX["Read-model projector"]
  end
  B -->|"HTML and asset requests"| CDN
  B -->|"Authenticated dashboard requests"| WAF
  WAF -->|"Allowed requests"| L
  L -->|"SSR and API traffic"| SSR
  SSR -->|"Session validation"| AUTH
  SSR -->|"Payment list query"| PAY
  PAY -->|"Cache lookup"| C
  C -->|"Cache miss"| R
  PAY -->|"Merchant permissions"| S
  Q -->|"Payment updates"| IDX
  IDX -->|"Build read model"| R
Diagram

3. API design

  • GET /dashboard — server-rendered initial page and summary.
  • GET /v1/payments?from=&to=&status=&cursor=&limit= — filtered, cursor-paginated list; cap limit (for example, 100).
  • GET /v1/payments/{payment_id} — authorized details for one payment.
  • GET /v1/dashboard/summary?from=&to= — totals and counts for the selected period.

The BFF derives the merchant identity from the authenticated session, not from a caller-supplied merchant_id. APIs return request IDs and stable error codes; pagination cursors are opaque and bound to the query filters.

4. Data model & storage

  • Payments read model: payment ID, merchant ID, created time, amount in minor units, currency, status, and selected display fields. Store in a replicated SQL read model or a suitable indexed data store; partition or shard by merchant and time, and index (merchant_id, created_at, payment_id) for the common list query.
  • Merchant/access data: SQL, because role and account relationships need transactional updates and reliable authorization checks.
  • Cache: Redis for short-lived summaries or repeated first-page queries, keyed by merchant, role scope, normalized filters, and data version. Set a modest TTL and invalidate or version entries on payment events.
  • Assets: immutable, hashed JavaScript, CSS, and fonts on object storage behind the CDN. Do not cache authenticated HTML or sensitive payment responses publicly.

5. Deep dive

The main frontend optimization is to make the useful page visible before loading every dashboard feature. The server checks the session and merchant permissions, renders the navigation and first page of payments, and sends compact data with the HTML. The browser then hydrates the visible list; charts, export tools, and secondary panels are split into separate bundles and loaded when needed. Use responsive images only where relevant, avoid large chart libraries on the critical path, and reserve layout space to prevent cumulative layout shift.

sequenceDiagram
  participant U as Merchant browser
  participant CDN as CDN
  participant BFF as Dashboard BFF
  participant Auth as Auth service
  participant Read as Payments read model
  U->>CDN: Request dashboard document
  CDN->>BFF: Forward authenticated page request
  BFF->>Auth: Validate session and merchant access
  Auth-->>BFF: Authorized merchant context
  BFF->>Read: Fetch first page for merchant
  Read-->>BFF: Payments and summary
  BFF-->>U: HTML with initial data
  U->>CDN: Fetch hashed route chunks
  CDN-->>U: Cached static assets
  U->>BFF: Fetch next page with opaque cursor
  BFF-->>U: Authorized next-page results
Diagram

On the client, keep filter state in the URL so views are shareable and browser navigation works. Debounce text filters, cancel obsolete requests, and use request IDs so a slow response cannot overwrite results for newer filters. Show skeletons only for expected short waits, preserve existing data during refresh, and provide explicit retry/error states. Use virtualization only for genuinely long lists; cursor pagination is the default. Measure real-user LCP, INP, and CLS by route and device, alongside API latency and error rate.

6. Scale, bottlenecks & trade-offs

  • Rendering: SSR improves initial content and discovery but costs server capacity. Cache public assets aggressively; render personalized HTML per request and keep it private. Stream the shell where supported, but avoid making the UI depend on a slow secondary widget.
  • Data: replicas and a precomputed read model protect the payment write path from dashboard queries. Eventual consistency is acceptable for a dashboard if the UI communicates refresh behavior; payment execution and authoritative status checks must use strongly consistent payment services.
  • Caching: tenant-scoped keys reduce repeated reads, but invalidation is hard. Use short TTLs/versioned entries and fall back to the read store on cache failure. Never trade tenant isolation for hit rate.
  • Availability: deploy stateless BFF instances across zones, autoscale on latency and utilization, and use bounded timeouts, retries with jitter for safe reads, and circuit breakers. Degrade optional charts before the core payment list.
  • Trade-off: send a small initial payload and fetch details on demand rather than shipping a large client bundle or full transaction history. This reduces time-to-interactive and bandwidth while adding a small number of follow-up requests.

I’d validate the design with synthetic peak traffic, slow-network/device testing, accessibility checks, and production real-user monitoring before progressively rolling it out.

TechnicalMediumRazorpayFrontend EngineerSystem design round

20. How would you manage authentication and authorization?

Model answer

  1. Separate authentication from authorization. Authentication establishes who the user is; authorization decides what that identity may do to a particular resource. The frontend can guide the experience, but the backend must enforce every permission check—hiding a button is not security.
  2. Use a well-understood identity protocol. For a browser application, I’d use an established OpenID Connect provider and Authorization Code flow with PKCE rather than implementing password handling or token issuance myself. For a first-party web app, I generally prefer a server-managed session in a Secure, HttpOnly, appropriately SameSite cookie. If the architecture requires API access tokens in the browser, I’d keep them short-lived and avoid persistent storage such as localStorage, which is exposed to JavaScript and therefore to XSS.
  3. Protect the session lifecycle. Use TLS, rotate session identifiers after login or privilege changes, expire inactive sessions, and provide reliable logout and revocation. Protect cookie-authenticated state-changing requests against CSRF, for example with SameSite cookies plus CSRF tokens where appropriate. Validate token issuer, audience, signature, and expiry on the server; do not trust client-decoded claims. Use step-up authentication for sensitive actions.
  4. Model permissions around resources and actions. Start with roles for broad access, then use resource-level rules where needed. For a payments dashboard, for example, a merchant admin might manage team members, while a finance user can view settlements but not change account settings. The API should check both the user’s permission and their relationship to the requested merchant or resource. Keep authorization policy centralized, deny by default, and audit sensitive decisions.
  5. Keep the UI consistent with the API. Fetch the user’s permitted capabilities after authentication and use them to render appropriate routes and actions. Handle 401 by prompting re-authentication and 403 by showing an access-denied state; avoid repeated retries that create loops. Treat cached permissions as hints and refresh them after role changes or when an API reports a denial.
sequenceDiagram
  participant U as User
  participant B as Browser
  participant I as Identity Provider
  participant A as API
  participant P as Policy Service
  U->>B: Start sign-in
  B->>I: OIDC authorization with PKCE
  I-->>B: Authorization code
  B->>A: Exchange code and establish session
  A-->>B: Secure session cookie
  B->>A: Request resource with session
  A->>P: Check identity and resource permission
  P-->>A: Allow or deny
  A-->>B: Resource or 403 response
Diagram
  1. Monitor and test the boundaries. Log authentication events and authorization denials without recording secrets or tokens. Test direct API access, cross-merchant/resource access, expired sessions, CSRF, and role changes—not just whether the UI hides controls. This keeps the experience usable while ensuring the server remains the security boundary.

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