Morgan Stanley interview questions & answers

20 Morgan Stanley interview questions with full model answers — Behavioral, Technical, Coding, System design. Drawn from the same bank ChannelPulse drills from (117 Morgan Stanley questions in total).

BehavioralEasyMorgan StanleyInvestment Banking AnalystFit / superday

1. Walk me through your resume.

Model answer

The flow

  1. Introduction: Briefly introduce yourself and your educational background.
  2. Academic Achievements: Highlight relevant coursework and any honors or distinctions.
  3. Professional Experience: Discuss key internships or jobs, focusing on finance-related roles.
  4. Skills and Certifications: Mention any technical skills, languages, or certifications.
  5. Extracurricular Activities: Share leadership roles or relevant projects.
  6. Conclusion: Summarize why these experiences make you a fit for the role.

The answer

Introduction: Hi, I'm Alex Johnson, and I recently graduated from the University of Chicago with a degree in Economics. I have a strong academic background and a passion for finance, which has driven my career path so far.

Academic Achievements: During my time at university, I completed coursework in financial markets, corporate finance, and econometrics, earning a spot on the Dean's List for three consecutive years. My capstone project focused on analyzing the impact of interest rate changes on stock market volatility, which deepened my understanding of market dynamics.

Professional Experience: I interned at Goldman Sachs in their Investment Banking Division, where I supported the team in financial modeling and preparing pitch books for M&A deals. This experience honed my analytical skills and gave me exposure to high-stakes transactions. Prior to that, I worked at a boutique financial advisory firm, where I conducted industry research and assisted in the preparation of client presentations, gaining a holistic view of financial advisory services.

Skills and Certifications: I am proficient in Excel and financial modeling, and I have completed the Bloomberg Market Concepts certification. Additionally, I am fluent in Spanish, which I believe is an asset in today's global market.

Extracurricular Activities: At university, I was the president of the Finance Club, where I organized workshops and guest lectures to help students understand career paths in finance. I also led a student-run investment fund, which managed a portfolio of $50,000, providing hands-on experience in investment strategy and portfolio management.

Conclusion: These experiences have equipped me with a solid foundation in finance and strong analytical skills, making me well-prepared for the Investment Banking Analyst role at your firm. I am excited about the opportunity to contribute to your team and further develop my skills in a dynamic and challenging environment.

Why this works

  • Comprehensive Overview: The answer gives a structured walkthrough of the candidate's background, highlighting relevant experiences and skills.
  • Relevance to Role: Each section ties back to the skills and experiences needed for an Investment Banking Analyst, demonstrating the candidate's preparedness.
  • Quantifiable Achievements: By including specific achievements and responsibilities, the candidate provides evidence of their capabilities.
  • Engagement: The candidate connects their past experiences to their future aspirations, showing enthusiasm and commitment to the field.
  • Weakness in Alternatives: A weak answer might lack structure, omit key experiences, or fail to connect past experiences to the desired role, leaving the interviewer uncertain about the candidate's fit.
BehavioralEasyMorgan StanleySoftware Engineer1st Technical Interview

2. What was the subject you liked the least?

Model answer

  1. Situation — The subject I liked least at first was compiler design. I was studying it as part of my computer science degree, and I found the material more abstract than courses where I could see a program’s behavior immediately. Topics such as grammars, parsing, and intermediate representations felt like several layers of theory before I got to something practical.
  2. Task — I wanted to understand the subject well enough to use the ideas, rather than just memorize definitions for an exam. The challenge was to make the connection between the theory and the code I already knew.
  3. Action
  • I started by breaking the compiler pipeline into stages—lexing, parsing, semantic analysis, and code generation—and focused on what each stage received and produced.
  • I worked through small examples by hand, tracing how a short expression such as a + b * c became tokens and then a syntax tree.
  • I built a small parser for a limited expression grammar. Implementing it made concepts like precedence and associativity much less abstract.
  • When I got stuck, I compared my parse tree with the grammar rules instead of trying to memorize the rules in isolation.
  • I also discussed tricky examples with classmates, which helped me explain the concepts clearly and spot gaps in my own understanding.
  1. Result — I became much more comfortable with the subject and finished the course able to explain how the stages fit together, not just reproduce terminology. More importantly, I learned that a subject feeling abstract at first does not mean it is irrelevant; I need to find a small, practical problem that makes the ideas concrete. That approach has helped me when learning unfamiliar technical topics since then.
BehavioralMediumMorgan StanleySoftware EngineerFirst interview (coding and DSA)

3. Tell me about the project you worked on during your internship.

The full question

Tell me about the project you worked on during your internship. What technology stack did you use, and what were its advantages and disadvantages?

Model answer

  1. Situation — During my software engineering internship, our team needed to replace a manual process for reviewing operational exceptions with a small internal web application. Analysts were collecting information from multiple sources, which made it hard to see the status of an issue or follow up consistently. I worked with a mentor and two other engineers to deliver a usable first version within the internship.
  2. Task — I owned the end-to-end implementation of the exception review workflow: displaying assigned items, letting users update their status and notes, and recording changes reliably. The main constraint was to keep the tool simple while preserving traceability for operational users.
  3. Action
  • I used React and TypeScript for the interface, Java with Spring Boot for the REST API, and PostgreSQL for persistence. The team deployed it in our company’s cloud environment using its existing CI/CD pipeline.
  • I started by interviewing a few users and turning their workflow into a short set of acceptance criteria. That helped us avoid building features that were not needed for the initial release.
  • I designed the API around explicit status transitions and added server-side validation rather than relying on the UI. I also stored who made each change and when, so the history was reviewable.
  • I added automated tests for the transition rules and the most important API paths, then worked with my mentor to test the application using representative data.
  • The stack had trade-offs: React and TypeScript made the interface easy to evolve and caught many errors early, while Spring Boot provided a familiar structure for APIs and validation. The downside was that the frontend and backend required separate build and deployment steps, and the application introduced more operational complexity than a spreadsheet. PostgreSQL was a good fit for relational records and audit queries, but schema changes needed deliberate migrations.
  1. Result — We delivered the workflow to a pilot group, and users could find and update their assigned exceptions in one place instead of coordinating through several manual steps. The pilot also surfaced a couple of confusing status transitions, which we corrected before broader use. I learned to evaluate a stack not just by developer familiarity, but by how well it supports the users’ workflow, audit needs, and long-term operation.
BehavioralMediumMorgan StanleyGroup Product ManagerVirtual Superday

4. How do you handle difficult or demanding stakeholders?

Model answer

Situation

At a growing product organization, I led a roadmap area where Sales wanted customer-specific commitments, Engineering was concerned about reliability, and Support was seeing repeated friction in the same workflow. Each group had a valid perspective, but the debate was becoming a sequence of escalations rather than a decision about customer and business impact.

Task

I was accountable for aligning the stakeholders on a plan that protected important customer relationships without creating an unsustainable set of one-off commitments or increasing operational risk.

Action

  • I met with the stakeholders individually first. I asked what outcome they were protecting, what evidence they had, and what would make them comfortable with a different solution. That helped distinguish the stated request from the underlying need.
  • I brought the group together around a shared problem statement and evidence: affected customer segments, frequency of the issue, revenue exposure, support burden, and engineering cost. I made uncertainty visible rather than presenting estimates as facts.
  • I laid out options with explicit trade-offs: a bespoke fix for one customer, a reusable capability for the affected segment, or a short-term operational workaround while we validated demand.
  • I recommended the reusable option, with a limited pilot and a clear reliability guardrail. I explained what we would not do in that release and why, then documented the decision, owner, and revisit criteria.
  • When a stakeholder disagreed, I stayed firm on the decision process while remaining open to new evidence. For example, I invited Sales to identify additional customers who would use the capability and used that evidence to refine the pilot scope.

Result

The teams aligned on a staged plan rather than continuing to negotiate individual promises. We addressed the recurring customer problem while limiting bespoke work and monitoring reliability. I learned that demanding stakeholders are often responding to real incentives or risks; my job is to understand those, create a shared fact base, and make a transparent decision—not to avoid disagreement.

What interviewers listen for

  • Empathy without surrendering product judgment.
  • Clear trade-offs, decision rights, and follow-through.
  • Influence across functions, not reliance on escalation.
BehavioralMediumMorgan StanleySoftware EngineerHR round

5. What role did you play on your team during college projects?

Model answer

  1. Situation — In a college team project, four of us built a web application to help students find study groups for courses they were taking. The work was part of a semester-long software engineering course, so we had to balance implementation with design reviews, testing, and a fixed demo date. The team had different levels of experience, and early on we were making overlapping changes without a clear plan.
  2. Task — I took on the role of technical coordinator and backend contributor. My goal was to help the team agree on a manageable design, keep work moving, and deliver a reliable application without taking ownership away from the other team members.
  3. Action
  • I helped break the project into user-facing features—course search, group creation, and joining a group—and wrote down the API contracts so frontend and backend work could proceed in parallel.
  • I implemented the core backend endpoints and data model, while another teammate focused on the interface and others worked on testing and documentation.
  • I set up small pull requests and code reviews. When we disagreed about adding a recommendation feature late in the project, I suggested we first finish the core join-and-leave flow and only add recommendations if testing left enough time.
  • I organized a short weekly check-in where each person shared progress and blockers. For example, when the frontend was blocked by incomplete API behavior, I added a simple mock response and clarified the expected error cases so that work could continue.
  • I tried to make decisions visible rather than simply choosing an approach myself: I explained the trade-offs, asked the relevant teammate to review them, and documented the final choice.
  1. Result — We completed the core application and demonstrated the full flow of finding a course group and joining it. The project was delivered on time, and the clearer API boundaries reduced integration surprises near the demo. I learned that team leadership in a student project is often less about having the most ideas and more about making responsibilities clear, listening early, and helping others make progress.
BehavioralMediumMorgan StanleySoftware Engineer1st Technical Interview

6. What did you learn in TCS?

Model answer

  1. Situation — At TCS, I learned how software engineering works in a large delivery environment, where a solution has to satisfy users and business requirements while also fitting the team’s standards and release process. On one project, I worked on a Java application and collaborated with developers, testers, and a business-facing team.
  2. Task — My responsibility was to deliver changes reliably, but I also needed to learn how to work within an existing codebase and communicate clearly when requirements or dependencies were unclear.
  3. Action
  • I learned to clarify acceptance criteria before coding. I would confirm expected behavior with the relevant team member and write down edge cases rather than rely on assumptions.
  • I became more disciplined about reading existing code and tests before proposing a change, which helped me preserve established behavior.
  • I used code reviews as a learning tool: I addressed feedback, asked why a pattern was preferred, and applied that guidance in later work.
  • I worked closely with QA to reproduce defects and distinguish a code issue from a test-data or environment issue. For example, when a scenario failed only with a particular input, I traced the input through the relevant validation and processing steps before changing the implementation.
  • I also learned to communicate risk early. If a dependency or unclear requirement could affect a delivery date, I raised it with the team instead of waiting until the end of the task.
  1. Result — I grew from focusing mainly on whether my code worked locally to thinking about whether the change was testable, maintainable, and safe to release. I was able to take on changes with less day-to-day guidance and contribute more effectively across development and testing. The biggest lesson I took from TCS was that strong engineering is not just writing code; it is delivering dependable changes through collaboration, feedback, and clear ownership.
CodingEasyMorgan StanleySoftware Engineer

7. Palindrome Linked List (LeetCode)

Model answer

The task

Determine whether a singly linked list reads the same from front to back and back to front. Return a boolean without relying on access to nodes by index.

Key idea

Find the midpoint with slow and fast pointers, then reverse the second half. Compare the two halves node by node; reverse the second half again afterward to restore the original list.

Approach

  1. Advance slow by one node and fast by two until fast reaches the end.
  2. For an odd-length list, move the start of the second half past the middle node.
  3. Reverse the second half in place.
  4. Compare corresponding values from the head and reversed second half.
  5. Restore the second half before returning the result.
class Solution:
    def isPalindrome(self, head):
        def reverse(node):
            previous = None
            while node:
                following = node.next
                node.next = previous
                previous = node
                node = following
            return previous

        slow = fast = head

        # Find the midpoint. For odd length, fast ends on the final node.
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

        # Skip the middle node when the list has odd length.
        second_half_start = slow.next if fast else slow
        reversed_half = reverse(second_half_start)

        # Compare the first half with the reversed second half.
        left = head
        right = reversed_half
        is_palindrome = True

        while right:
            if left.val != right.val:
                is_palindrome = False
                break
            left = left.next
            right = right.next

        # Restore the list to its original structure.
        reverse(reversed_half)
        return is_palindrome

Complexity:

  • Time: O(n), to find the midpoint, reverse, compare, and restore.
  • Space: O(1), using only a few pointers.

Common follow-ups

  • What if the list must not be modified, even temporarily? Use a stack to store values, which takes O(n) extra space.
  • How can recursion solve it? Recursively compare nodes from the ends, using O(n) call-stack space.
  • What about empty or single-node lists? Both are palindromes; the code handles them directly.
CodingEasyMorgan StanleySoftware Engineer

8. Merge Sorted Array (LeetCode)

Model answer

The task

Combine two already sorted arrays into one sorted array, placing the result in the first array. The first array has enough spare capacity to hold all elements from both arrays.

Key idea

Fill the first array from right to left. Comparing the largest remaining elements avoids overwriting values in the first array that have not yet been processed.

Approach

  1. Set pointers to the last valid elements of both arrays.
  2. Set a write pointer to the last slot in the first array.
  3. While the second array still has elements, compare the values at the two read pointers.
  4. Write the larger value at the write pointer, then move the corresponding read pointer and the write pointer left.
  5. Any remaining elements from the second array are copied into the first. Remaining elements from the first are already in place.
class Solution:
    def merge(self, nums1: list[int], m: int, nums2: list[int], n: int) -> None:
        """Merge nums2 into nums1 in-place, keeping nums1 sorted."""
        i = m - 1          # Last initialized element in nums1
        j = n - 1          # Last element in nums2
        write = m + n - 1  # Last available position in nums1

        # Fill from the back so unread nums1 elements are not overwritten.
        while j >= 0:
            if i >= 0 and nums1[i] > nums2[j]:
                nums1[write] = nums1[i]
                i -= 1
            else:
                nums1[write] = nums2[j]
                j -= 1
            write -= 1

Complexity:

  • Time: O(m + n), since each element is considered at most once.
  • Space: O(1), because the merge modifies the first array directly.

Common follow-ups

  • What if the arrays are sorted in descending order? Reverse the comparison or adapt the traversal direction.
  • What if the result must go into a separate array? Use two forward pointers and allocate O(m + n) extra space.
  • What if either array is empty? The loop naturally handles it; if the second is empty, the first is already complete.
  • Why merge from the end? Writing from the front could overwrite unprocessed elements in the first array.
CodingEasyMorgan StanleySoftware Engineer

9. Palindrome Number (LeetCode)

Model answer

The task

Determine whether an integer reads the same from left to right and right to left. Negative values are not palindromes.

Key idea

Reverse only the last half of the digits, then compare it with the remaining first half. This avoids converting to a string and keeps the extra space constant.

Approach

  1. Return False for negative integers.
  2. Return False for positive integers ending in zero; zero itself is a palindrome.
  3. Repeatedly move the last digit from the number to a reversed-half accumulator.
  4. Stop when the accumulator has at least as many digits as the remaining number.
  5. Compare the halves directly for even digit counts, or discard the middle digit for odd counts.
class Solution:
    def isPalindrome(self, x: int) -> bool:
        # Negative numbers have a leading minus sign, so they cannot be palindromes.
        if x < 0:
            return False

        # A positive number ending in zero would need a leading zero to be palindromic.
        if x != 0 and x % 10 == 0:
            return False

        reversed_half = 0

        # Move digits until the reversed half is at least as long as the remaining half.
        while x > reversed_half:
            reversed_half = reversed_half * 10 + x % 10
            x //= 10

        # For an odd number of digits, ignore the middle digit.
        return x == reversed_half or x == reversed_half // 10

Complexity:

  • Time: O(log₁₀ n), for processing the digits of the number.
  • Space: O(1), using only a few integer variables.

Common follow-ups

  • How would you check a palindrome by converting to a string? Compare symmetric characters, using O(log n) extra space.
  • How would you avoid integer overflow in a fixed-width language? Reversing only half the digits keeps the accumulator bounded.
  • What about zero and numbers ending in zero? Zero is palindromic; other numbers ending in zero are not.
CodingEasyMorgan StanleySoftware Engineer

10. Two Sum (LeetCode)

Model answer

The task

Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.

Key idea

As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.

Approach

  1. Create a dictionary mapping previously seen values to their indices.
  2. For each element, compute the complement needed to reach the target.
  3. If that complement is in the dictionary, return its stored index and the current index.
  4. Otherwise, store the current value and index, then continue.
from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Map each value already visited to its index.
        seen = {}

        for index, value in enumerate(nums):
            complement = target - value

            # A match must come from an earlier, distinct element.
            if complement in seen:
                return [seen[complement], index]

            seen[value] = index

        # The standard problem guarantees a solution.
        raise ValueError("No two elements sum to the target")

Complexity:

  • Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
  • Space: O(n), for the dictionary of values seen so far.

Common follow-ups

  • What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
  • What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
  • What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingEasyMorgan StanleySoftware Engineer

11. Maximum Length Substring With Two Occurrences (LeetCode)

Model answer

The task

Find the length of the longest contiguous part of a string in which no character appears more than twice.

Key idea

Use a sliding window and keep a frequency count for each character inside it. If adding a character makes its count exceed two, move the window’s left edge until the count is valid again.

Approach

  1. Initialize the window’s left edge, character counts, and best length.
  2. Extend the right edge one character at a time, updating its count.
  3. While that character appears more than twice, remove characters from the left edge.
  4. Update the best length after restoring the window condition.
  5. Return the best length.
class Solution:
    def maximumLengthSubstring(self, s: str) -> int:
        counts = {}
        left = 0
        best = 0

        for right, char in enumerate(s):
            counts[char] = counts.get(char, 0) + 1

            # Restore the condition that each character occurs at most twice.
            while counts[char] > 2:
                left_char = s[left]
                counts[left_char] -= 1
                left += 1

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

        return best

Complexity:

  • Time: O(n), since each character enters and leaves the window at most once.
  • Space: O(min(n, Σ)), for counts of distinct characters in the string, where Σ is the character-set size.

Common follow-ups

  • What if each character may appear at most k times? Replace the threshold 2 with k.
  • What if the substring must contain exactly k distinct characters? Track the number of distinct characters and shrink while the window has too many.
  • Can this handle a stream of characters? Yes; keep the window’s counts and indices, retaining enough recent characters to remove from the left.
System designMediumMorgan StanleySoftware EngineerFirst interview (coding and DSA)

12. Design a data structure that supports both queue and stack operations, with every operation running in O(1) time.

Model answer

1. Requirements & scale

Requirements

  • Support push, pop, and peek for a stack, plus enqueue, dequeue, and front for a queue.
  • Each operation must be worst-case O(1), not merely amortized O(1).
  • Define the contract: the stack and queue are independent collections; an item added to one is not implicitly part of the other. This avoids ambiguous behavior when operations are interleaved.
  • Return an empty result or a defined error on removal from an empty collection.

Scale and complexity

  • For n stored items, storage is O(n); each operation touches a fixed number of pointers.
  • This is an in-memory data-structure guarantee. Network calls and lock contention, if exposed as a service, are outside the algorithmic O(1) guarantee.

2. High-level architecture

For a local library, the API calls the structure directly. If exposed to multiple application instances, keep each structure process-local or use a single-owner service; a distributed shared structure adds coordination latency and is not literally O(1) end-to-end.

flowchart TD
  subgraph Client["Client"]
    C["Caller"]
  end
  subgraph Edge["Edge/CDN"]
    E["Not required for local use"]
  end
  subgraph LB["Load Balancer"]
    L["Optional service routing"]
  end
  subgraph API["API / Services"]
    A["Stack and queue API"]
    R["Operation router"]
  end
  subgraph Cache["Cache"]
    K["No cache; pointers are authoritative"]
  end
  subgraph Stores["Datastores"]
    S["Stack: top pointer and linked nodes"]
    Q["Queue: head, tail, and linked nodes"]
  end
  subgraph MQ["Message Queue"]
    M["Not required; operations are synchronous"]
  end
  subgraph Workers["Workers"]
    W["Not required for local operations"]
  end
  C -->|"method call"| E --> L --> A --> R
  R -->|"stack operation"| S
  R -->|"queue operation"| Q
Diagram

3. API design

  • push(value): add a value to the stack.
  • pop(): remove and return the stack's most recently pushed value.
  • peek(): return the stack top without removing it.
  • enqueue(value): add a value to the queue tail.
  • dequeue(): remove and return the queue head.
  • front(): return the queue head without removing it.

4. Data model & storage

Use a doubly linked node with value, prev, and next fields. Maintain separate sentinels and metadata for each collection:

  • Stack: a sentinel and a top pointer. Push inserts immediately after the sentinel; pop removes the top node.
  • Queue: a sentinel plus head and tail pointers. Enqueue inserts at the tail; dequeue removes the head.
  • Sentinels simplify empty and single-element cases: there are no special null-pointer branches for boundary updates. An empty collection has its sentinel linked to itself.

The two collections can share a node type and helper methods, but not nodes or endpoints. If a node must belong to both collections, represent that explicitly with two link fields or two memberships; do not reuse one set of pointers.

5. Deep dive

Each operation updates a constant number of fields. For example, stack push creates one node and links it between the sentinel and the old top. Stack pop unlinks the top node and returns its value. Queue enqueue links a new node between the tail and sentinel; dequeue unlinks the head and advances the head pointer. No traversal, array shifting, or resizing is involved, so the guarantee is worst-case O(1).

sequenceDiagram
  participant C as Caller
  participant A as Operation API
  participant L as Linked structure
  C->>A: enqueue(value)
  A->>L: link node after tail
  L-->>A: updated tail
  A-->>C: success
  C->>A: dequeue()
  A->>L: unlink head
  L-->>A: value and updated head
  A-->>C: value
Diagram

If the intended contract is instead one collection that can be used from either end, implement a deque with addFirst, addLast, removeFirst, and removeLast, also worst-case O(1) using a doubly linked list. Stack operations can use one end and queue operations can use opposite ends. State this contract clearly: interleaving those operations does not create two independent ADTs.

For concurrent callers, protect each collection's pointer updates with a mutex. A lock-free implementation is possible but requires careful memory reclamation and is unnecessary unless measured contention justifies it. The mutex does not change the number of pointer operations, though waiting time is not bounded O(1).

6. Scale, bottlenecks & trade-offs

  • Linked nodes provide predictable operation time but have per-node allocation and pointer overhead and poorer cache locality than arrays.
  • A dynamically resizing array can make an individual push O(n), so it does not meet a strict worst-case requirement without a more specialized representation.
  • Separate structures make semantics easy to reason about and test. A shared deque uses less duplicated metadata but must document how mixed stack/queue operations interact.
  • Test empty, one-element, and alternating operations; assert links and endpoints after each mutation. In production, expose size counters for observability, updated in the same critical section as the pointers.
System designMediumMorgan StanleySoftware Engineer2nd Technical Interview

13. Design classes for an online retail store such as Amazon.

Model answer

1. Requirements & scale

Functional requirements

  • Browse and search a catalog; view product details, prices, and availability.
  • Maintain carts, place orders, pay, and track fulfillment, cancellation, and returns.
  • Support multiple sellers, warehouses, promotions, and inventory updates.
  • Prevent overselling and make checkout idempotent.

Non-functional requirements

  • Highly available browsing and search; checkout must preserve financial and inventory correctness.
  • Low latency: roughly 200 ms for common reads and a few seconds for checkout.
  • Secure handling of personal and payment data; auditable order and payment transitions.

Back-of-the-envelope: Assume 100 million active customers, 1 million orders/day, and 50 million catalog items. Average order rate is about 12/s; at a 20× peak, roughly 240 orders/s. Search and product reads may reach 50,000 QPS. At 2 KB per order, raw order data is about 2 GB/day, or 0.7 TB/year before indexes and replicas. Product images dominate storage, so keep them in object storage and serve through a CDN.

2. High-level architecture

The class model below sits behind APIs; services own their domain logic rather than letting clients mutate entities directly.

flowchart TD
  subgraph Client
    C["Web and mobile"]
  end
  subgraph Edge/CDN
    E["CDN and WAF"]
  end
  subgraph Load Balancer
    L["Regional API load balancer"]
  end
  subgraph API / Services
    A["Catalog API"]
    O["Order and checkout service"]
    I["Inventory service"]
    P["Payment service"]
  end
  subgraph Cache
    K["Redis catalog and cart cache"]
  end
  subgraph Datastores
    D["Catalog search index"]
    R["Order and payment SQL"]
    V["Inventory SQL"]
    B["Image object storage"]
  end
  subgraph Message Queue
    Q["Order events"]
  end
  subgraph Workers
    W["Fulfillment and notification workers"]
  end
  C -->|"HTTPS requests"| E
  E -->|"API traffic"| L
  E -->|"image requests"| B
  L --> A
  L --> O
  A -->|"cache lookup"| K
  A -->|"search and product reads"| D
  O -->|"reserve stock"| I
  O -->|"order transaction"| R
  O -->|"authorize payment"| P
  I -->|"stock transaction"| V
  O -->|"order placed event"| Q
  Q -->|"asynchronous work"| W
  W -->|"shipment updates"| R
Diagram

3. API design

  • GET /v1/products/{productId} — product detail and availability summary.
  • GET /v1/search?q=...&cursor=... — ranked catalog results.
  • POST /v1/carts/{cartId}/items — add or update a cart line.
  • POST /v1/orders — create an order; require an Idempotency-Key.
  • GET /v1/orders/{orderId} — retrieve order status and shipment tracking.
  • POST /v1/orders/{orderId}/cancel — request cancellation subject to fulfillment state.

4. Data model & storage

Use SQL for transactional entities: Order(order_id, customer_id, status, total, created_at), OrderLine(order_id, product_id, seller_id, quantity, unit_price), Payment(payment_id, order_id, status, provider_ref), and Inventory(warehouse_id, sku, available, reserved, version). Store order lines with a copied price so later catalog changes do not rewrite purchase history. Partition large order tables by time and shard by customer_id or order_id, keeping an order lookup index.

Catalog attributes can use a relational source of truth, with a search index for full-text and faceted queries. Cache popular product reads and carts in Redis with bounded TTLs; cache is never authoritative for stock. Store images in object storage, served via CDN. Keep card data with a compliant payment provider; persist only provider tokens and references.

5. Deep dive

Core classes and responsibilities:

  • Product owns identity and descriptive data; SKU represents a purchasable variant. SellerOffer supplies seller-specific price and fulfillment options.
  • Cart contains CartItem values and is editable; checkout snapshots those values into immutable OrderLine records.
  • Order controls legal state transitions, such as PENDING_PAYMENT → CONFIRMED → FULFILLING → SHIPPED, and records cancellation or return states.
  • InventoryService reserves and releases stock; PaymentService authorizes, captures, and refunds through a provider adapter.
  • CheckoutService coordinates these operations and uses an outbox record written in the same transaction as the order, so events are not lost after commit.

For each SKU, reserve with an atomic conditional update, for example available >= quantity, decrementing available and incrementing reserved in one transaction. If payment fails, release the reservation. If payment succeeds, confirm the order and publish OrderPlaced through the outbox. Consumers must be idempotent because queue delivery is at least once. Use reservation expiry and a compensating worker for abandoned checkouts.

sequenceDiagram
  participant C as Customer
  participant O as CheckoutService
  participant I as InventoryService
  participant P as PaymentService
  participant Q as EventQueue
  C->>O: Submit cart and idempotency key
  O->>I: Reserve SKU quantities
  I-->>O: Reservation result
  O->>P: Authorize payment
  P-->>O: Authorization result
  O->>O: Commit order and outbox event
  O-->>C: Order confirmation
  O->>Q: Publish OrderPlaced
Diagram

6. Scale, bottlenecks & trade-offs

Replicate catalog reads and search indexes across regions; rebuild indexes asynchronously from the catalog source. Keep order writes in a home region per customer to avoid multi-region transaction complexity, with replicated disaster-recovery copies. Inventory is the critical contention point for popular SKUs: partition by warehouse and SKU, use short reservation leases, and route allocation across warehouses. Do not promise globally linearizable stock without accepting latency and availability costs.

Browsing can tolerate stale prices or availability briefly, but checkout must revalidate price and reserve inventory. SQL transactions suit orders, payments, and stock invariants; search indexes and caches favor read throughput. Queue-based fulfillment improves resilience but introduces eventual consistency, so expose explicit order states and retry safely. Payment and inventory calls need timeouts, circuit breakers, idempotency keys, and reconciliation jobs to resolve ambiguous outcomes.

System designMediumMorgan StanleySoftware Engineer2nd Technical Interview

14. Design classes for a car parking system.

Model answer

1. Requirements & scale

Functional requirements

  • Manage multiple facilities, floors, and spot types; find and allocate a compatible spot.
  • Issue tickets at entry, calculate fees, accept payment, and open the exit gate.
  • Support reservations, lost tickets, EV charging, accessibility needs, and staff overrides.
  • Track occupancy and report availability to drivers and operators.

Non-functional requirements

  • Entry and exit must keep working during a network outage; local decisions should be fast.
  • A spot must not be assigned to two active vehicles at once.
  • Payment and gate actions need audit records, while personal data is minimized.

Back-of-the-envelope: Assume 10,000 facilities, averaging 500 spots, for 5 million spots total. If 5% of spots change state per minute, that is about 4,200 updates/s; a 10× event peak is around 42,000/s. At 100,000 entry/exit events per facility per day, total event volume is 1 billion/day across the network. At 300 bytes per event, that is about 300 GB/day raw, so retain hot operational data separately from archived events. A facility typically needs only hundreds of local allocation operations per second at peak.

2. High-level architecture

The object model is scoped by ParkingLot; each facility can continue operating against its local controller if connectivity to the central platform fails.

flowchart TD
  subgraph Client
    C["Driver app and operator console"]
    G["Entry and exit gates"]
  end
  subgraph Edge/CDN
    E["WAF and API edge"]
  end
  subgraph Load Balancer
    L["Regional load balancer"]
  end
  subgraph API / Services
    A["Facility API"]
    S["Spot allocation service"]
    T["Ticket and pricing service"]
    P["Payment service"]
  end
  subgraph Cache
    K["Facility availability cache"]
  end
  subgraph Datastores
    D["Facility and ticket SQL"]
    V["Occupancy event store"]
    B["Receipt archive"]
  end
  subgraph Message Queue
    Q["Gate and payment events"]
  end
  subgraph Workers
    W["Reconciliation and reporting workers"]
  end
  C -->|"availability and reservation requests"| E
  E --> L
  G -->|"entry and exit events"| A
  L --> A
  A --> S
  A --> T
  T --> P
  S -->|"availability lookup"| K
  S -->|"atomic spot allocation"| D
  T -->|"ticket transaction"| D
  P -->|"payment record"| D
  A -->|"occupancy and audit events"| Q
  Q -->|"persist events"| V
  Q -->|"reconcile and report"| W
  W -->|"receipts"| B
Diagram

3. API design

  • GET /v1/facilities/{facilityId}/availability — counts by floor and spot type.
  • POST /v1/reservations — reserve a facility, time window, and vehicle class.
  • POST /v1/tickets/entry — create or resume an entry ticket for a vehicle.
  • POST /v1/tickets/{ticketId}/quote — calculate a fee at exit time.
  • POST /v1/tickets/{ticketId}/payment — collect payment with an idempotency key.
  • POST /v1/gates/{gateId}/open — authorized, audited gate command.

4. Data model & storage

Use SQL for invariants and operational records: ParkingLot(lot_id, timezone, policy_id), Floor(floor_id, lot_id), ParkingSpot(spot_id, floor_id, type, status, version), Vehicle(vehicle_id, plate_hash, class), Ticket(ticket_id, lot_id, vehicle_id, spot_id, entry_at, exit_at, status), Reservation(reservation_id, lot_id, start_at, end_at, status), and Payment(payment_id, ticket_id, amount, status, provider_ref). Enforce at most one active ticket per spot with a conditional update or database constraint. Partition tickets by lot_id and time; keep facility-local operations close to their controller.

Redis can cache availability counts, but allocation must use the authoritative database or a facility-local transactional store. Append gate, spot, and payment changes to an event store for audit and analytics. Store receipts in object storage. Hash license plates where possible and apply retention policies to identifiable records.

5. Deep dive

Class responsibilities and relationships:

  • ParkingLot contains Floor objects; each floor contains ParkingSpot instances. A spot has a type such as compact, accessible, or EV, and a state such as available, occupied, or out of service.
  • Vehicle carries a vehicle class and optional charging requirements. SpotAssignmentStrategy selects a compatible spot, keeping policy separate from the facility entity; strategies can prefer nearest, smallest-fit, or reserved spaces.
  • Ticket represents one visit and owns entry/exit timestamps and lifecycle state. FeePolicy calculates charges from duration, facility rules, and discounts; Payment records a provider outcome, not card details.
  • ParkingService coordinates ticket creation, assignment, fee calculation, and gate commands. GateController is an adapter for hardware, and ReservationService prevents incompatible bookings.

On entry, the allocator filters by facility, type, and reservation eligibility, then atomically changes one candidate from available to occupied using its version or a conditional update. If no spot can be safely claimed, it tries another candidate; it never trusts a cached count as a reservation. The ticket and spot assignment are committed together. At exit, calculate the fee from the entry time and current time, charge idempotently, mark the ticket paid/closed, release the spot, and issue the gate command. If payment succeeds but the response is lost, query the provider by idempotency key before charging again.

sequenceDiagram
  participant D as Driver
  participant G as GateController
  participant S as ParkingService
  participant DB as FacilityDatabase
  participant P as PaymentProvider
  D->>G: Present entry request
  G->>S: Request compatible spot
  S->>DB: Atomically claim available spot
  DB-->>S: Spot and assignment confirmed
  S->>DB: Create active ticket
  S-->>G: Ticket and gate authorization
  G-->>D: Open entry gate
  D->>S: Request exit quote and payment
  S->>P: Charge with idempotency key
  P-->>S: Payment outcome
  S->>DB: Close ticket and release spot
Diagram

6. Scale, bottlenecks & trade-offs

Partition data and allocation by facility so one busy location does not contend with every other lot. Run a local controller with durable storage and cached policies; synchronize events to the cloud asynchronously. During a central outage, allow entry only when local capacity and payment policy permit, and reconcile once connectivity returns. This favors facility availability over globally fresh occupancy; the local database remains authoritative for that facility.

Use optimistic version checks or row-level locking to handle simultaneous arrivals. A single global allocator is simpler but adds latency and is a failure bottleneck. Cached availability is fast but can be stale, so show approximate counts and confirm only on successful allocation. Keep SQL for ticket, payment, and spot-state invariants; use an event stream for audit and analytics. Payment providers and gate hardware can fail independently: use bounded retries, idempotency, manual operator procedures, and reconciliation for uncertain outcomes. Specify fail-safe gate behavior with facility safety requirements rather than assuming payment logic alone controls emergency access.

System designHardMorgan StanleySoftware EngineerSystem design round

15. Design the low-level architecture for a ticket-booking system like BookMyShow.

The full question

Design the low-level architecture for a ticket-booking system like BookMyShow. Expose APIs for searching by city, theatre, and movie, and handle concurrency during seat booking.

Model answer

1. Requirements & scale

Functional requirements

  • Search movies and showtimes by city, theatre, movie, date, and language/format.
  • Display seat availability for a particular show and let a customer temporarily hold multiple seats, confirm payment, or cancel.
  • Prevent two customers from booking the same seat; support hold expiry, retries, and booking lookup.
  • Provide theatre/partner APIs for inventory and schedule updates.

Non-functional requirements

  • Search should be highly available and tolerate slightly stale availability; booking correctness must be strongly consistent.
  • Target search p95 under 300 ms, seat-map p95 under 500 ms, and booking confirmation p95 under 2 seconds excluding external payment latency.
  • Make booking and payment calls idempotent and auditable. Avoid claiming a seat is confirmed until the authoritative transaction succeeds.

Illustrative scale

  • Assume 10 million searches/day: average 116 QPS; at a 10x peak, about 1,200 QPS.
  • Assume 1 million booking attempts/day: average 12 QPS; at a 20x peak, about 240 QPS. A blockbuster can create a much higher per-show hotspot, so capacity must be tested against hot shows.
  • If 100,000 active shows each have 200 seats, 20 million seat rows at roughly 200 bytes each are about 4 GB raw; indexes, replicas, and history multiply that. Search documents and cached seat maps are rebuildable.

2. High-level architecture

flowchart TD
  subgraph Client["Client"]
    App["Mobile and web apps"]
    Partner["Theatre partners"]
  end
  subgraph Edge["Edge/CDN"]
    CDN["Static assets and rate limits"]
  end
  subgraph LB["Load Balancer"]
    LB1["Regional routing"]
  end
  subgraph Services["API / Services"]
    Search["Discovery API"]
    Booking["Booking API"]
    Inventory["Show and seat service"]
    Payment["Payment adapter"]
  end
  subgraph Cache["Cache"]
    Redis["Search and seat-map cache"]
  end
  subgraph Stores["Datastores"]
    SQL["Booking and seat SQL primary"]
    SearchDB["Search index"]
    Blob["Audit and ticket documents"]
  end
  subgraph Queue["Message Queue"]
    Events["Booking and catalogue events"]
  end
  subgraph Workers["Workers"]
    Indexer["Search indexer"]
    Expirer["Hold expiry worker"]
    Notifier["Ticket and notification worker"]
  end
  App -->|"search and booking requests"| CDN --> LB1
  Partner -->|"schedule and inventory updates"| LB1
  LB1 --> Search
  LB1 --> Booking
  LB1 --> Inventory
  Search -->|"query"| SearchDB
  Search -->|"results and seat map"| Redis
  Booking -->|"atomic hold and confirm"| SQL
  Inventory -->|"authoritative inventory"| SQL
  Booking -->|"authorize and capture"| Payment
  Booking -->|"domain events"| Events
  SQL -->|"outbox events"| Events
  Events --> Indexer
  Events --> Expirer
  Events --> Notifier
  Indexer -->|"catalogue updates"| SearchDB
  Notifier --> Blob
Diagram

3. API design

  • GET /v1/cities/{cityId}/movies?date=&language=&format= — discover movies and showtimes in a city.
  • GET /v1/theatres/{theatreId}/shows?date=&movieId= — list matching shows for a theatre.
  • GET /v1/movies/{movieId}/shows?cityId=&date= — list shows by movie and city.
  • GET /v1/shows/{showId}/seats — return seat map and availability version.
  • POST /v1/holds — hold requested seats; require an idempotency key; return holdId and expiry.
  • POST /v1/bookings — confirm a valid hold, with payment authorization reference and idempotency key.
  • DELETE /v1/holds/{holdId} — release a hold; repeated calls are safe.
  • GET /v1/bookings/{bookingId} — retrieve booking and ticket status.

4. Data model & storage

Use a relational database such as PostgreSQL or a distributed SQL store for authoritative seat state and bookings. Core tables:

  • Show(show_id, theatre_id, movie_id, start_time, status); partition by date or region where operationally useful.
  • Seat(show_id, seat_id, status, hold_id, hold_expires_at, booking_id, version) with primary key (show_id, seat_id).
  • Hold(hold_id, user_id, show_id, status, expires_at, idempotency_key) and Booking(booking_id, user_id, show_id, status, payment_ref).
  • Unique constraints on (show_id, seat_id) in booking details and on the idempotency key's scope.

Use a search index for city/movie/theatre discovery, updated asynchronously from an outbox. Redis can cache search results and seat-map snapshots, but never decide that a seat is bookable. Keep an append-only event/audit trail for state transitions and support reconciliation with the payment provider.

5. Deep dive

Model seats with a state machine: AVAILABLE → HELD → BOOKED; an expired or released hold returns to AVAILABLE. The database is the authority. On hold, validate the show and seat IDs, then execute one transaction that conditionally changes every requested seat from available to held. Require the affected-row count to equal the requested seat count; otherwise roll back the entire transaction and return a conflict. Lock requested rows in sorted seat-ID order, or use conditional updates with version checks, to reduce deadlocks. A unique idempotency record ensures retries return the original result rather than creating a second hold.

sequenceDiagram
  participant U as User
  participant B as Booking API
  participant D as SQL primary
  participant P as Payment provider
  U->>B: POST hold with seats and idempotency key
  B->>D: Transactionally claim all available seats
  D-->>B: Hold ID and expiry, or conflict
  B-->>U: Hold result
  U->>B: Confirm hold
  B->>P: Authorize payment with stable request key
  P-->>B: Authorization result
  B->>D: Transaction: mark seats and booking confirmed
  D-->>B: Commit
  B-->>U: Booking confirmation
Diagram

Use a short hold duration, for example five minutes, and check expiry in the confirmation transaction; do not rely solely on a background worker. The expiry worker is cleanup, not the correctness mechanism. If payment succeeds but the database confirmation fails, retry with the same payment key and reconcile; if confirmation cannot complete, void or refund the authorization. Prefer authorization followed by database commit and then capture where the provider supports it, with an outbox event for downstream ticket delivery.

6. Scale, bottlenecks & trade-offs

  • Keep search read-heavy traffic on the index and cache; invalidate or version cached seat maps after booking events. Search availability is eventually consistent, but the hold endpoint always revalidates against SQL.
  • Partition seat data by show_id so one show’s transaction touches a bounded set of rows. A highly popular show is a hot key; rate-limit and queue excess attempts per show, while preserving a final atomic database claim. Do not serialize all cities behind one global lock.
  • Use multi-AZ database replication and backups. Route writes to the primary; replicas may serve non-authoritative reads. During a primary failover, pause or reject booking writes until the new primary is fenced, rather than risk split-brain double bookings.
  • Search-index lag is an availability-versus-freshness trade-off. Booking chooses consistency over availability: if authoritative inventory cannot be reached, fail closed and do not promise seats.
  • Monitor hold-to-confirm conversion, conflicts, expiry rate, payment/database mismatches, per-show lock waits, index lag, and booking latency. Reconcile seat, booking, and payment state continuously.
TechnicalEasyMorgan StanleyInvestment Banking AnalystTechnical interview

16. Walk me through the three financial statements.

Model answer

The flow

  1. Income Statement: Start with the revenue and expenses to find net income.
  2. Cash Flow Statement: Adjust net income for non-cash items and changes in working capital to find cash flow from operations.
  3. Balance Sheet: Use cash flow to adjust assets and liabilities, ensuring the balance sheet balances.
  4. Linkages: Show how net income links to retained earnings and cash flow affects cash and equivalents.
  5. Validation: Confirm that the accounting equation (Assets = Liabilities + Equity) holds.

The answer

1. Income Statement:

  • Begin with the revenue, say $500,000.
  • Subtract operating expenses of $300,000 to get an operating income of $200,000.
  • Deduct interest and taxes, say $50,000, leaving a net income of $150,000.

2. Cash Flow Statement:

  • Start with the net income of $150,000.
  • Adjust for non-cash items like depreciation, say $20,000, adding it back.
  • Consider changes in working capital, for example, an increase in accounts receivable by $10,000, which is subtracted.
  • Cash flow from operations would be $160,000 ($150,000 + $20,000 - $10,000).

3. Balance Sheet:

  • Begin with last period's balance sheet, where assets were $1,000,000, liabilities $600,000, and equity $400,000.
  • Add the net income to retained earnings in equity, increasing it by $150,000.
  • Adjust cash and equivalents by the cash flow from operations, increasing it by $160,000.
  • Ensure that the new balance sheet balances: Assets = $1,160,000, Liabilities = $600,000, Equity = $550,000.

4. Linkages:

  • The net income of $150,000 increases retained earnings.
  • The cash flow from operations affects the cash and equivalents on the balance sheet.

5. Validation:

  • Confirm that the balance sheet equation holds: $1,160,000 = $600,000 + $550,000.

Why this works

  • Understanding Interconnections: The interviewer wants to see if you understand how the three statements are interconnected.
  • Sanity Check: Ensures you can logically walk through the statements and maintain the integrity of the accounting equation.
  • Common Pitfall: Weak answers often fail to correctly link net income to retained earnings or cash flow changes to the balance sheet.
  • Practical Insight: Demonstrates ability to interpret financial data and understand its impact on a company's financial position.
  • Holistic View: Shows you can see the big picture of a company's financial health, not just isolated numbers.
TechnicalEasyMorgan StanleyInvestment Banking AnalystTechnical interview

17. How do the three financial statements link together?

Model answer

The flow

  1. Income Statement: Start with net income at the bottom of the income statement.
  2. Cash Flow Statement: Use net income as the starting point for the cash flow from operations.
  3. Adjustments: Adjust for non-cash items and changes in working capital.
  4. Cash Flow Statement: Calculate cash flows from investing and financing activities.
  5. Balance Sheet: Update cash and retained earnings using the cash flow statement.
  6. Balance Sheet: Ensure assets equal liabilities plus equity.

The answer

Income Statement

  • Begin with the income statement, which shows the company's revenues, expenses, and resulting net income.
  • Assume net income is $100 million.

Cash Flow Statement

  • Start with the net income of $100 million as the first line in the cash flow from operations.
  • Adjustments: Add back non-cash expenses like depreciation ($10 million) and changes in working capital (e.g., a $5 million decrease in accounts receivable).
  • Cash flow from operations is now $115 million.
  • Investing Activities: Assume a capital expenditure of $20 million.
  • Financing Activities: Assume the company issued $30 million in new debt.
  • Total cash flow is $125 million ($115 million from operations - $20 million from investing + $30 million from financing).

Balance Sheet

  • Update the cash balance by adding the total cash flow of $125 million.
  • Adjust retained earnings by adding the net income of $100 million.
  • Ensure that the balance sheet balances: assets (including updated cash) equal liabilities (including new debt) plus equity (including updated retained earnings).

Why this works

  • Interviewer Objective: They want to see if you understand how financial statements are interconnected and how changes in one affect the others.
  • Sanity Check: A strong answer will ensure the balance sheet remains balanced after adjustments.
  • Common Pitfalls: Weak answers often miss how non-cash items and working capital adjustments affect cash flow, leading to incorrect cash balance updates.
  • Understanding: Demonstrates a comprehensive understanding of financial statements, a critical skill for an investment banking analyst.
TechnicalEasyMorgan StanleySoftware Engineer1st Technical Interview

18. What is a WebSocket?

Model answer

A WebSocket is a protocol that creates a persistent, full-duplex connection between a client and a server. Once connected, either side can send messages independently, without opening a new HTTP request for every update. This is useful for use cases such as live notifications, collaborative applications, and streaming market data.

The connection usually starts as an HTTP request with an Upgrade: websocket header. If the server accepts it, it responds with 101 Switching Protocols; communication then continues over the established connection using WebSocket frames. wss:// is WebSocket over TLS, analogous to HTTPS.

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: HTTP Upgrade request
    S-->>C: 101 Switching Protocols
    C->>S: WebSocket data frame
    S-->>C: WebSocket data frame
    C->>S: Ping or Close frame
    S-->>C: Pong or Close response
Diagram

A strong implementation should account for a few operational details:

  • Lifecycle: Connections are long-lived, so clients and servers need heartbeats, timeouts, and reconnection behavior. WebSocket control frames include ping, pong, and close.
  • Security: Use wss://, validate the Origin, authenticate the connection, and authorize each message type. A successful handshake does not mean every later action is permitted.
  • Scale: Each connection consumes server and network resources. At scale, services need connection limits, load balancing, and a way to deliver events to the server currently holding a user’s connection—often through a shared pub/sub or message system.
  • Reliability: A disconnected client can miss messages. If delivery matters, add sequence numbers, acknowledgements, or a durable event log and let the client resume from its last confirmed position.

Compared with polling, WebSockets reduce repeated request overhead and provide low-latency server-to-client updates, but they add connection-management and delivery-complexity. I would choose them when updates are frequent or latency-sensitive; for infrequent updates, ordinary HTTP or server-sent events may be simpler.

TechnicalEasyMorgan StanleySoftware Engineer1st Technical Interview

19. What are semaphores and mutexes?

Model answer

A mutex and a semaphore are synchronization primitives used to coordinate concurrent threads, but they express different intent.

  • A mutex protects a critical section or shared resource. It has ownership: the thread that locks it is expected to unlock it. For example, a mutex can ensure only one thread updates an in-memory account balance at a time.
  • A semaphore maintains a counter. A thread acquires a permit, reducing the count, and releases one to increase it. A counting semaphore can limit access to a pool of, for example, 10 connections. A binary semaphore has a count of 0 or 1, but unlike a mutex it generally does not imply ownership.
  • Both can block threads, so incorrect use can cause deadlocks or starvation. A mutex is usually the right choice for exclusive ownership of shared state; a semaphore is useful for limiting concurrency or signaling available capacity.

For example, if there are three permits, at most three workers can enter the protected section concurrently:

flowchart LR
    A[Worker requests permit] --> B{Permit available?}
    B -->|Yes| C[Acquire permit and proceed]
    B -->|No| D[Wait]
    C --> E[Release permit when finished]
    E --> A
Diagram

In production code, I would use the language's established synchronization APIs and ensure permits or locks are released reliably, including on exceptions. For shared financial state, I would also consider whether a database transaction or another higher-level consistency mechanism is more appropriate than an in-process lock.

TechnicalEasyMorgan StanleySoftware Engineer1st Technical Interview

20. What is a man-in-the-middle attack?

Model answer

A man-in-the-middle (MITM) attack occurs when an attacker positions themselves between two parties and intercepts, relays, or alters their communication while each party believes it is communicating directly with the other.

For example, an attacker on a compromised network might impersonate a service to a client and impersonate the client to the service. They could then read or modify data unless the parties authenticate each other and protect the channel.

sequenceDiagram
    participant C as Client
    participant A as Attacker
    participant S as Service
    C->>A: Request intended for service
    A->>S: Relayed or modified request
    S-->>A: Response
    A-->>C: Relayed or modified response
Diagram

Defenses include:

  • Use correctly configured TLS and validate the server certificate and hostname; encryption without authentication does not reliably prevent MITM.
  • Use mutual TLS or other strong client authentication where appropriate, and protect private keys.
  • Prevent downgrade and insecure-redirect attacks with controls such as HSTS for web applications.
  • Avoid accepting certificate errors or trusting certificates supplied by untrusted sources.
  • For sensitive financial transactions, add transaction-level controls such as authorization checks, audit trails, and confirmation of critical transaction details.

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