<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chirag Saini on Medium]]></title>
        <description><![CDATA[Stories by Chirag Saini on Medium]]></description>
        <link>https://medium.com/@csaini3082?source=rss-765f923cc917------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mm-Ht3L5y0hxR-xf</url>
            <title>Stories by Chirag Saini on Medium</title>
            <link>https://medium.com/@csaini3082?source=rss-765f923cc917------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 09:59:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@csaini3082/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[My Urban Company SDE interview]]></title>
            <link>https://medium.com/@csaini3082/my-urban-company-sde-interview-ae9c2b48a76a?source=rss-765f923cc917------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9c2b48a76a</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Chirag Saini]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 13:49:39 GMT</pubDate>
            <atom:updated>2026-10-08T13:49:39.450Z</atom:updated>
            <content:encoded><![CDATA[<p>In February 2026 I interviewed for an SDE role at Urban Company. I had applied through a form they posted on LinkedIn, and both rounds were in person at their Gurugram office.</p><p>The DSA section is short because I don’t remember the exact questions. I’ve listed the problems closest to what I got. The LLD section is longer. I cleaned up what I drew on the whiteboard, wrote the code properly with tests, and put it on GitHub: <a href="https://github.com/chirag3082/restaurant-table-booking">https://github.com/chirag3082/restaurant-table-booking</a></p><h3>Round 1: DSA</h3><p>Two questions. The round was very collaborative and the interviewer was really nice throughout.</p><h4>Question 1: root to leaf path sums</h4><p>It was a binary tree problem about root to leaf paths and their sums. It wasn’t the plain textbook version, there was a twist on top, but I can’t recall the exact statement. Here are the problems that come closest. If you can do these comfortably, most variants of this question won’t surprise you.</p><ul><li><a href="https://leetcode.com/problems/path-sum/">Path Sum (LeetCode 112)</a>. Is there a root to leaf path with a given sum? Start here.</li><li><a href="https://leetcode.com/problems/path-sum-ii/">Path Sum II (LeetCode 113)</a>. Same thing, but return every such path.</li><li><a href="https://leetcode.com/problems/minimum-depth-of-binary-tree/">Minimum Depth of Binary Tree (LeetCode 111)</a>. The shortest root to leaf path, counted in nodes.</li><li><a href="https://www.geeksforgeeks.org/dsa/sum-leaf-nodes-minimum-level/">Sum of leaf nodes at minimum level (GfG)</a>. Find the shallowest leaves and add them up. BFS works well here.</li><li><a href="https://www.geeksforgeeks.org/dsa/sum-nodes-longest-path-root-leaf-node/">Sum of nodes on the longest path from root to leaf (GfG)</a>. If two paths are equally long, take the larger sum.</li><li><a href="https://leetcode.com/problems/sum-root-to-leaf-numbers/">Sum Root to Leaf Numbers (LeetCode 129)</a>. Each path forms a number, add them all.</li><li><a href="https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/">Insufficient Nodes in Root to Leaf Paths (LeetCode 1080)</a>. Delete nodes where every path through them sums below a limit. Looks easy, isn’t.</li><li><a href="https://leetcode.com/problems/path-sum-iii/">Path Sum III (LeetCode 437)</a>. Paths can start and end anywhere going down. Needs prefix sums.</li><li><a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/">Binary Tree Maximum Path Sum (LeetCode 124)</a>. The hard one, where the path doesn’t have to touch the root at all.</li></ul><p>Most of these use the same DFS. You carry something down the tree, like a running sum or a depth, and make a decision when you reach a leaf.</p><p>The mistake I see most is with a node that has only one child. That node isn’t a leaf. If you treat the missing child as an empty path with sum 0, any question that asks for a minimum gives the wrong answer. Returning a large value for a null child fixes it:</p><pre>// Smallest root to leaf sum. A missing child returns MAX_VALUE so it never wins the min.<br>int minPathSum(TreeNode node) {<br>    if (node == null) return Integer.MAX_VALUE;<br>    if (node.left == null &amp;&amp; node.right == null) return node.val;<br>    return node.val + Math.min(minPathSum(node.left), minPathSum(node.right));<br>}</pre><p>Minimum Depth (111) has exactly the same trap, which is probably why it gets asked so much.</p><h4>Question 2: a Merge Intervals variant</h4><p>Again I don’t remember the exact twist. The base problem is to sort by start time, walk through the list, and either extend the last merged interval or start a new one.</p><pre>int[][] merge(int[][] intervals) {<br>    Arrays.sort(intervals, Comparator.comparingInt(a -&gt; a[0]));<br>    List&lt;int[]&gt; merged = new ArrayList&lt;&gt;();<br>    for (int[] current : intervals) {<br>        if (!merged.isEmpty() &amp;&amp; current[0] &lt;= merged.getLast()[1]) {<br>            merged.getLast()[1] = Math.max(merged.getLast()[1], current[1]);<br>        } else {<br>            merged.add(current);<br>        }<br>    }<br>    return merged.toArray(new int[0][]);<br>}</pre><p>Before writing any code, ask whether intervals that only touch, like [1, 3] and [3, 5], count as overlapping. It decides whether that check is &lt;= or &lt;, and interviewers notice when you ask.</p><p>Variants worth practising:</p><ul><li><a href="https://leetcode.com/problems/merge-intervals/">Merge Intervals (LeetCode 56)</a>. The base problem.</li><li><a href="https://leetcode.com/problems/insert-interval/">Insert Interval (LeetCode 57)</a>. The list is already sorted and merged. Add one more.</li><li><a href="https://leetcode.com/problems/non-overlapping-intervals/">Non-overlapping Intervals (LeetCode 435)</a>. Fewest removals so nothing overlaps. Sort by end time this time.</li><li><a href="https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/">Minimum Number of Arrows to Burst Balloons (LeetCode 452)</a>. Same greedy idea as 435.</li><li><a href="https://leetcode.com/problems/interval-list-intersections/">Interval List Intersections (LeetCode 986)</a>. Two sorted lists, two pointers.</li><li><a href="https://leetcode.com/problems/meeting-rooms-ii/">Meeting Rooms II (LeetCode 253)</a>. How many rooms you need at the busiest moment. It’s premium. “Minimum platforms” on GfG is the same problem for free.</li><li><a href="https://leetcode.com/problems/car-pooling/">Car Pooling (LeetCode 1094)</a>. Capacity over time.</li><li><a href="https://leetcode.com/problems/my-calendar-i/">My Calendar I (LeetCode 729)</a> and <a href="https://leetcode.com/problems/my-calendar-ii/">My Calendar II (LeetCode 731)</a>. Accept a booking only if it doesn’t overlap too much.</li></ul><p>The last three are basically small booking systems, and they turned out to be good prep for round 2.</p><h3>Round 2: Low level design</h3><p>The interviewer opened with a premise. He and I are business partners who own a restaurant, and we want our customers to be able to book tables with us.</p><p>Before drawing anything I asked what he wanted to see. He gave me three things that had to work:</p><ol><li>A user can make a reservation</li><li>A user can place an order</li><li>A user can make a payment</li></ol><p>For each of those he wanted the entities, their attributes and how they relate to each other. Then he wanted actual code: the main function for each of the three, and how I’d structure the code around them.</p><p>Here’s my whiteboard at the end of the round. The requirements are top left, the entities are top middle, and the scribbles next to “time” are the availability idea I’ll get to below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUNIWBs8NhwKwNWgoq8Fbg.jpeg" /></figure><p><em>The whiteboard at the end of the round.</em></p><p>The rest of this post goes through the design in roughly that order. Everything is cleaned up and the code actually runs.</p><h4>Scope</h4><p>These are the assumptions the code makes. In an interview I’d say them out loud before drawing, because each one removes a whole category of questions.</p><ul><li>One restaurant.</li><li>The day is split into 30 minute slots, and a booking covers whole slots. 1:00 to 2:00 is fine, 1:15 to 2:00 isn’t.</li><li>Each booking gets one table.</li><li>You order against a reservation. No walk-ins.</li><li>One bill per visit, paid in one go.</li></ul><h4>Entities and relationships</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FC4F6bJRObhApM0UhLJyg.png" /></figure><p><em>The same design, redrawn. Code is in the GitHub repo.</em></p><ul><li><strong>User</strong> is whoever books. Name and phone are enough here.</li><li><strong>Table</strong> has an id and a capacity. Capacity matters more than you’d think, I’ll come back to it.</li><li><strong>Slot</strong> is a 30 minute block. On the whiteboard slots were just times written next to lists of tables. In code I made it a small type of its own, because the rule that a slot starts on the hour or half hour has to live somewhere.</li><li><strong>Reservation</strong> ties together a user, a table, the party size, the slots it covers and a status.</li><li><strong>Menu</strong> and <strong>MenuItem</strong>, where an item has a name and a price.</li><li><strong>Order</strong> belongs to a reservation and has a waiter and a set of items with quantities. A reservation can have several orders, say starters first and dessert later.</li><li><strong>Waiter</strong> is assigned on the first order and stays with the table for the rest of the visit.</li><li><strong>Bill</strong> covers every order on the reservation.</li><li><strong>Payment</strong> records that the bill was paid, how much and when.</li><li><strong>Restaurant</strong> is the entry point. It owns the tables and the menu, and every call from outside goes through it.</li></ul><p>In words: a user has many reservations, a reservation has one table and many orders, all the orders end up on one bill, and that bill gets one payment.</p><h4>The interesting part: availability</h4><p>Underneath, a booking is an interval problem. Can I fit [1:00, 2:00) on some table without overlapping anything already there? That’s the same check as My Calendar from round 1.</p><p>Instead of storing intervals per table, I split time into 30 minute slots and kept a map from each slot to the tables still free in it:</p><pre>freeTables: Map&lt;Slot, Set&lt;Table&gt;&gt;</pre><pre>1:00  -&gt;  {T1, T2}<br>1:30  -&gt;  {T1, T2, T3}<br>2:00  -&gt;  {T2, T3}</pre><p>Those are the actual values from my whiteboard. Now say 2 people want 1:00 to 2:00.</p><ol><li>The booking needs the 1:00 and 1:30 slots.</li><li>The tables free in both are T1 and T2. T3 is taken at 1:00.</li><li>Pick the smallest table that seats 2. If T2 seats 2 and T1 seats 4, that’s T2.</li><li>Remove T2 from both slots and save the reservation.</li></ol><p>Step 3 matters more than it looks. If you hand out the first free table, a couple can end up at a table for six, and then a family of six gets turned away even though the restaurant has room. Going smallest first avoids that.</p><p>The slot approach does cost you something. You can’t book 1:15, and a restaurant that wants 15 minute slots would double the size of the map. In exchange, the check is a set lookup, and a slot that nobody has booked doesn’t need an entry at all. That fits how restaurants take bookings anyway.</p><p>In code, step 2 and step 3 collapse into one loop. If the tables are sorted smallest first, the first one that seats the party and is free in every slot is the answer:</p><pre>public synchronized Optional&lt;Table&gt; claimSmallestFit(List&lt;Slot&gt; slots, int partySize) {<br>    for (Table table : tablesSmallestFirst) {<br>        if (table.capacity() &gt;= partySize &amp;&amp; isFreeInAll(table, slots)) {<br>            for (Slot slot : slots) {<br>                free(slot).remove(table);<br>            }<br>            return Optional.of(table);<br>        }<br>    }<br>    return Optional.empty();<br>}</pre><pre>private Set&lt;Table&gt; free(Slot slot) {<br>    // A slot nobody has booked yet isn&#39;t in the map, so every table is free.<br>    return freeTables.computeIfAbsent(slot, s -&gt; new HashSet&lt;&gt;(tablesSmallestFirst));<br>}</pre><p>The synchronized is doing a lot of work there. I&#39;ll come back to it.</p><h4>How the code is structured</h4><pre>com.chirag.restaurant<br>  Restaurant              the only class callers use<br>  model/                  User, Table, Slot, Reservation, Menu, MenuItem,<br>                          Order, Waiter, Bill, Payment<br>  service/<br>    TableAvailability     slot -&gt; free tables, smallest fit<br>    ReservationService    reserve, cancel<br>    OrderService          orders against a reservation<br>    PaymentService        bill and pay</pre><p>Restaurant is a thin layer over the services, and each public method maps to one of the three things the interviewer asked for:</p><pre>// 1. Users can make reservations<br>public Reservation book(User user, int partySize, LocalDateTime from, LocalDateTime to)</pre><pre>// 2. Users can place an order<br>public Order placeOrder(long reservationId, Map&lt;String, Integer&gt; itemQuantities)</pre><pre>// 3. Users can make a payment<br>public Bill requestBill(long reservationId)<br>public Payment pay(long billId, int amount)</pre><p>The model classes don’t know about each other’s rules. The services do the checking, and each service does one thing.</p><h4>1. Making a reservation</h4><pre>public Reservation reserve(User user, int partySize, LocalDateTime from, LocalDateTime to) {<br>    if (partySize &lt;= 0) {<br>        throw new IllegalArgumentException(&quot;Party size must be positive: &quot; + partySize);<br>    }<br>    List&lt;Slot&gt; slots = Slot.between(from, to);<br>    Table table = availability.claimSmallestFit(slots, partySize)<br>            .orElseThrow(() -&gt; new NoTableAvailableException(partySize, from, to));</pre><pre>    Reservation reservation = new Reservation(ids.incrementAndGet(), user, table, partySize, slots);<br>    reservations.put(reservation.id(), reservation);<br>    return reservation;<br>}</pre><p>Slot.between turns 1:00 to 2:00 into the 1:00 and 1:30 slots. It rejects anything that isn&#39;t on a half hour boundary, and anything where from isn&#39;t before to. Cancelling does the reverse. It marks the reservation cancelled and puts the table back into each slot.</p><h4>2. Placing an order</h4><pre>public Order placeOrder(long reservationId, Map&lt;String, Integer&gt; itemQuantities) {<br>    Map&lt;MenuItem, Integer&gt; items = new LinkedHashMap&lt;&gt;();<br>    itemQuantities.forEach((itemId, quantity) -&gt; {<br>        if (quantity &lt;= 0) {<br>            throw new IllegalArgumentException(&quot;Quantity must be positive for &quot; + itemId);<br>        }<br>        items.merge(menu.get(itemId), quantity, Integer::sum); // throws if not on the menu<br>    });</pre><pre>    Reservation reservation = reservations.get(reservationId);<br>    synchronized (reservation) {<br>        if (reservation.status() != ReservationStatus.CONFIRMED) {<br>            throw new IllegalStateException(&quot;Can&#39;t order on reservation &quot; + reservationId<br>                    + &quot;, it is &quot; + reservation.status());<br>        }<br>        Waiter waiter = waiterByReservation.computeIfAbsent(reservationId,<br>                id -&gt; waiters.get(Math.floorMod(nextWaiter.getAndIncrement(), waiters.size())));<br>        Order order = new Order(ids.incrementAndGet(), reservation, waiter, items);<br>        ordersByReservation.computeIfAbsent(reservationId, id -&gt; new ArrayList&lt;&gt;()).add(order);<br>        return order;<br>    }<br>}</pre><p>The status check is what stops you ordering on a cancelled reservation, or after the bill is out. The reservation moves through a fixed set of states:</p><pre>CONFIRMED -&gt; BILLED -&gt; COMPLETED<br>CONFIRMED -&gt; CANCELLED</pre><p>Every move goes through one method that checks where you are first:</p><pre>public synchronized void transition(ReservationStatus from, ReservationStatus to) {<br>    if (status != from) {<br>        throw new IllegalStateException(&quot;Reservation &quot; + id + &quot; is &quot; + status<br>                + &quot;, expected &quot; + from + &quot; to move to &quot; + to);<br>    }<br>    status = to;<br>}</pre><p>It’s a small thing, but it means no service can put a reservation into a state that doesn’t make sense.</p><h4>3. Making a payment</h4><p>Paying is two steps. First you ask for the bill, then you pay it.</p><pre>public Bill generateBill(long reservationId) {<br>    Reservation reservation = reservations.get(reservationId);<br>    synchronized (reservation) {<br>        Bill existing = billByReservation.get(reservationId);<br>        if (existing != null) {<br>            return existing; // asking twice gives the same bill<br>        }<br>        List&lt;Order&gt; placed = orders.ordersFor(reservationId);<br>        if (placed.isEmpty()) {<br>            throw new IllegalStateException(&quot;Nothing was ordered on reservation &quot; + reservationId);<br>        }<br>        reservation.transition(ReservationStatus.CONFIRMED, ReservationStatus.BILLED);</pre><pre>        Bill bill = new Bill(billIds.incrementAndGet(), reservation, placed);<br>        bills.put(bill.id(), bill);<br>        billByReservation.put(reservationId, bill);<br>        return bill;<br>    }<br>}</pre><pre>public Payment pay(long billId, int amount) {<br>    Bill bill = getBill(billId);<br>    if (amount != bill.total()) {<br>        throw new IllegalArgumentException(&quot;Bill &quot; + billId + &quot; is &quot; + bill.total() + &quot;, got &quot; + amount);<br>    }<br>    bill.markPaid(); // throws if it&#39;s already paid<br>    bill.reservation().transition(ReservationStatus.BILLED, ReservationStatus.COMPLETED);<br>    return new Payment(paymentIds.incrementAndGet(), bill, amount, clock.instant());<br>}</pre><p>Two details here. Asking for the bill twice returns the same bill, so a double tap in an app doesn’t create two. And markPaid is synchronized and refuses to run twice, so the same bill can&#39;t be paid twice even if two requests arrive together.</p><p>There’s no payment gateway in this version. We didn’t get into that in the interview, and it would be a separate design on its own.</p><h4>Two people, one table, same moment</h4><p>This is what I’d add to what I did in the room. Steps 2 to 4 of the availability check have to happen as one unit. If they don’t, two requests for 1:00 can both see T2 as free, and both book it.</p><p>That’s why claimSmallestFit is synchronized. To check that it actually matters, the repo has a test where 50 threads try to book the same hour at once, with only 3 tables in the restaurant. With the lock in place, exactly 3 succeed every time. When I removed synchronized and ran it again, every run failed, and in one of them 20 people got bookings for those same 3 tables.</p><pre>@RepeatedTest(20)<br>void sameSlotIsNeverGivenToTwoPeople() throws InterruptedException {<br>    // 3 tables, 50 threads, all asking for 20:00 to 21:00 at the same moment<br>    ...<br>    assertEquals(3, booked.size());<br>    // and no table id appears twice<br>}</pre><p>One lock for the whole restaurant sounds heavy, but one restaurant gets very few bookings per second, so it’s fine. If it ever wasn’t, you could lock per table instead.</p><p>The lock only works inside one process, though. Once bookings are in a database and there’s more than one app server, the database has to enforce it. The simplest way is a row per table per slot, with the pair as the primary key:</p><pre>CREATE TABLE table_slot_bookings (<br>    table_id       VARCHAR   NOT NULL,<br>    slot_start     TIMESTAMP NOT NULL,<br>    reservation_id BIGINT    NOT NULL,<br>    PRIMARY KEY (table_id, slot_start)<br>);</pre><p>A booking inserts one row per slot inside a transaction. If another request got there first, the insert fails on the key, the transaction rolls back, and you try the next table. No locks in application code at all.</p><h4>What I’d add with more time</h4><ul><li><strong>Groups bigger than any single table.</strong> Joining two tables means the availability check has to look at pairs of tables that are next to each other. That’s a much more interesting problem.</li><li><strong>No-shows.</strong> Release the table if nobody turns up 15 minutes after the booking starts.</li><li><strong>Holds.</strong> If booking needs a deposit, hold the table for a few minutes while the user pays, and release it if they don’t.</li><li><strong>A real payment gateway</strong>, with an idempotency key so a retry never charges twice. Different payment methods would be a reasonable place for the strategy pattern.</li><li>**Money as paise in a long**, or BigDecimal. Whole rupees in an int keep the example readable but wouldn&#39;t survive a real menu.</li></ul><h3>What I’d tell someone preparing</h3><p>Ask what they want to see before you draw anything. The three requirements he gave me decided where my time went.</p><p>In the LLD round, get one flow working end to end before making anything clever. A working book() that picks the right table is worth more than a perfect class diagram with no logic behind it.</p><p>For DSA, the tree and interval patterns above cover a lot of ground. Practise the variants and not only the LeetCode originals.</p><p>The full code, with tests and a demo that replays the whiteboard example, is here: <a href="https://github.com/chirag3082/restaurant-table-booking">https://github.com/chirag3082/restaurant-table-booking</a></p><p>If you’ve done this kind of round somewhere else, I’d like to hear how you handled big groups.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9c2b48a76a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a flight booking system: how I’d answer it now]]></title>
            <link>https://medium.com/@csaini3082/designing-a-flight-booking-system-how-id-answer-it-now-bbdaf231cc92?source=rss-765f923cc917------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbdaf231cc92</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Chirag Saini]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 23:40:34 GMT</pubDate>
            <atom:updated>2026-10-05T06:34:03.247Z</atom:updated>
            <content:encoded><![CDATA[<p>In January I was asked to design a flight booking system in an interview at Park+. It was my first system design round and it didn’t go the way I wanted. I wrote about the interview itself in a separate post.</p><p>This one is the answer I would give if I got the same question today. I’m writing it because most of what makes this problem hard sits in one place: the few minutes between a user picking a seat and finishing payment. If you take away one thing, take that. Hold the seat with an expiry, check availability and claim the seat in a single atomic update, and confirm everything in one transaction once payment succeeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36n1A5DeGEnYkHJEpzto4Q.jpeg" /><figcaption>A picture of a Departure Board</figcaption></figure><h3>The problem</h3><p>The prompt was one line: design a flight booking system. The interviewer then narrowed it down to this flow:</p><ol><li>The user searches for a flight.</li><li>The user sees which seats are vacant and picks the one they want.</li><li>The user makes the payment.</li></ol><p>They wanted to see the objects and how they relate, the choice of database, how to stop two people booking the same seat, and the SQL queries the backend would run along with how to make them fast.</p><h3>Step 1: Ask before drawing anything</h3><p>These are the questions I would ask in the first few minutes:</p><ul><li>Is this one airline that owns its seat inventory, or an aggregator pulling seats from many airlines? This changes whether we even own the seat data.</li><li>Roughly how many searches compared to bookings? Search is going to be read heavy. Booking is low volume but has contention.</li><li>Do we need cancellations and refunds, or just the happy path?</li><li>Are we integrating with a payment gateway? (Yes, nobody builds their own in an interview.)</li><li>How long can a user hold a seat while they are paying?</li><li>Do you want me to focus on the schema and queries, or on services and scaling?</li></ul><p>For the rest of this post I’ll assume a single platform that owns its inventory, the search to seat to payment flow, and a 10 minute hold on a seat during payment.</p><p><strong>Functional requirements</strong></p><ul><li>Search flights by source, destination and date.</li><li>See the seat map for a flight with what is free and what isn’t.</li><li>Hold a seat and pay for it.</li><li>Get a confirmed booking.</li></ul><p><strong>Non-functional requirements</strong></p><ul><li>A seat can never be sold to two people.</li><li>Search should be fast. It’s fine if search results are a few seconds stale.</li><li>If a payment fails or the user just closes the tab, the seat shouldn’t stay locked forever.</li></ul><p>The first two points are the main tension in this problem. Search can be a little stale. Booking can’t be.</p><h3>Step 2: Entities and how they relate</h3><ul><li><strong>Flight</strong>: a scheduled flight on a specific date, for example DEL to BLR on 15 Jan. Has a flight number, source, destination, departure and arrival time.</li><li><strong>Seat</strong>: a seat on a specific flight. Has a seat number like 12A, a class, a price and a status.</li><li><strong>User</strong>: the person booking.</li><li><strong>Booking</strong>: links a user to a flight. Has a status like PENDING, CONFIRMED, EXPIRED or CANCELLED.</li><li><strong>Payment</strong>: belongs to a booking. Stores the amount, the gateway’s reference and a status.</li></ul><p>The associations:</p><ul><li>One flight has many seats.</li><li>One user has many bookings.</li><li>One booking can cover one or more seats (if you book for family), and a seat belongs to at most one booking.</li><li>One booking can have more than one payment attempt, since payments fail and get retried.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhP5QqvEvmyhZX1GOoPx7w.png" /><figcaption>Data Model</figcaption></figure><p>In a real system the seat layout belongs to the aircraft, and what you sell is a seat on a particular flight. So there would be a layout table per aircraft and an inventory table per flight. Here I’ve merged them into one seats table, which is fine as long as you say out loud that you’re simplifying.</p><h3>Step 3: Which database</h3><p>I went with a relational database in the interview and I’d make the same call now.</p><ul><li>Booking a seat touches several rows (the seat, the booking, the payment) and they all need to succeed or fail together. That’s a transaction, and relational databases give you ACID guarantees out of the box.</li><li>The main rule of the system, one seat per booking, maps directly onto row level locks and unique constraints.</li><li>The data is structured and naturally relational. Flights have seats, bookings have payments.</li></ul><p>Postgres or MySQL would both be fine.</p><p>Where something else could help is search. If searches massively outnumber bookings, you can cache search results in Redis with a short expiry, or index flights in something like Elasticsearch. That’s an optimisation on top. The source of truth for seats and bookings stays in the relational database.</p><h3>Step 4: Schema</h3><p>Here is a rough schema in Postgres, one table at a time. I’ve left out the users table to keep it short.</p><pre>CREATE TABLE flights (<br>  id              BIGSERIAL PRIMARY KEY,<br>  flight_number   VARCHAR(10) NOT NULL,<br>  source          CHAR(3) NOT NULL,     -- airport code, e.g. DEL<br>  destination     CHAR(3) NOT NULL,<br>  departure_time  TIMESTAMPTZ NOT NULL,<br>  arrival_time    TIMESTAMPTZ NOT NULL<br>);</pre><pre>CREATE TABLE bookings (<br>  id          BIGSERIAL PRIMARY KEY,<br>  user_id     BIGINT NOT NULL REFERENCES users(id),<br>  flight_id   BIGINT NOT NULL REFERENCES flights(id),<br>  -- PENDING, CONFIRMED, EXPIRED, CANCELLED<br>  status      VARCHAR(20) NOT NULL,<br>  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()<br>);</pre><pre>CREATE TABLE seats (<br>  id           BIGSERIAL PRIMARY KEY,<br>  flight_id    BIGINT NOT NULL REFERENCES flights(id),<br>  seat_number  VARCHAR(4) NOT NULL,     -- e.g. 12A<br>  seat_class   VARCHAR(20) NOT NULL,<br>  price        NUMERIC(10,2) NOT NULL,<br>  -- AVAILABLE, HELD, BOOKED<br>  status       VARCHAR(20) NOT NULL DEFAULT &#39;AVAILABLE&#39;,<br>  booking_id   BIGINT REFERENCES bookings(id),<br>  held_until   TIMESTAMPTZ,<br>  version      INT NOT NULL DEFAULT 0,<br>  UNIQUE (flight_id, seat_number)<br>);</pre><pre>CREATE TABLE payments (<br>  id               BIGSERIAL PRIMARY KEY,<br>  booking_id       BIGINT NOT NULL REFERENCES bookings(id),<br>  amount           NUMERIC(10,2) NOT NULL,<br>  -- INITIATED, SUCCESS, FAILED<br>  status           VARCHAR(20) NOT NULL,<br>  gateway_ref      VARCHAR(100),<br>  idempotency_key  VARCHAR(64) NOT NULL UNIQUE<br>);</pre><h3>Step 5: Stopping double booking</h3><p>This is the heart of the question, so it’s worth showing the actual failure first.</p><p>User A and user B both open the seat map and see 12A is free. Both click it at almost the same moment. If the code reads the seat, checks that it’s AVAILABLE, and then writes BOOKED, both reads can happen before either write. Both writes succeed. Two people now own 12A.</p><p>There are a few ways to fix this.</p><p><strong>Option 1: Pessimistic locking</strong></p><p>Lock the row when you read it, so nobody else can touch it until you’re done.</p><pre>BEGIN;<br>SELECT id, status, held_until<br>FROM seats<br>WHERE flight_id = 101 AND seat_number = &#39;12A&#39;<br>FOR UPDATE;<br>-- app checks status is AVAILABLE, or HELD but expired<br>UPDATE seats<br>SET status = &#39;HELD&#39;,<br>    booking_id = 5001,<br>    held_until = now() + interval &#39;10 minutes&#39;<br>WHERE id = 7788;<br>COMMIT;</pre><p>The second transaction waits at FOR UPDATE until the first one commits. When it finally reads the row it sees HELD and fails cleanly. This is simple and safe. The cost is that transactions queue up behind each other on a busy seat. The rule to remember is to keep this transaction short. Never hold a database lock while you wait for the payment gateway to respond.</p><p><strong>Option 2: Optimistic locking</strong></p><p>Don’t lock on read. Instead, use a version column and only write if nobody else changed the row since you read it.</p><pre>UPDATE seats<br>SET status = &#39;HELD&#39;,<br>    booking_id = 5001,<br>    held_until = now() + interval &#39;10 minutes&#39;,<br>    version = version + 1<br>WHERE id = 7788 AND version = 3;</pre><p>If this updates 0 rows, someone else got there first, and the app tells the user to pick another seat. Nothing blocks. This works well when conflicts are rare, which is true for most seats on most flights.</p><p><strong>Option 3: A conditional update</strong></p><p>This is probably what I would actually use. Put the availability check inside the update itself.</p><pre>UPDATE seats<br>SET status = &#39;HELD&#39;,<br>    booking_id = 5001,<br>    held_until = now() + interval &#39;10 minutes&#39;<br>WHERE flight_id = 101<br>  AND seat_number = &#39;12A&#39;<br>  AND (status = &#39;AVAILABLE&#39;<br>       OR (status = &#39;HELD&#39; AND held_until &lt; now()));</pre><p>It’s one statement, the database locks the row only for that statement, and the row count tells you if you won. It’s really optimistic locking where the seat’s state does the job of the version number.</p><p>Which one to pick depends on contention. For normal seat selection I’d go with option 2 or 3. Pessimistic locking is fine too, as long as you can explain the trade-off.</p><h3>Step 6: The payment window</h3><p>Payment is slow and it can fail. People close the tab halfway. So booking needs two phases: hold the seat, then confirm it.</p><ol><li>When the user picks a seat, create a booking with status PENDING and mark the seat HELD with held_until set 10 minutes ahead.</li><li>Send the user to the payment gateway with an idempotency key for this attempt.</li><li>When the gateway confirms success (usually through a webhook), run one transaction that marks the payment SUCCESS, the booking CONFIRMED and the seat BOOKED. Before doing that, check that the seat is still held by this booking.</li><li>If the payment fails or the 10 minutes run out, the seat goes back to AVAILABLE.</li></ol><p>Here is the whole flow in one picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UeIYd9XqHhf7UfzhZQRKw.png" /></figure><p>For step 4 there are two layers. The conditional update from option 3 already treats an expired hold as free, so nobody is stuck waiting. On top of that, a small background job cleans up expired holds every minute so the seat map looks right:</p><pre>UPDATE seats<br>SET status = &#39;AVAILABLE&#39;, booking_id = NULL, held_until = NULL<br>WHERE status = &#39;HELD&#39; AND held_until &lt; now();</pre><p>Two edge cases are worth naming in an interview:</p><ul><li>Payment gateways can send the same webhook more than once. The unique idempotency key and a status check before confirming stop you from processing it twice.</li><li>A payment can succeed just after the hold expired and someone else already took the seat. You either refund automatically, or set the gateway session timeout shorter than the hold so this almost never happens.</li></ul><h3>Step 7: The queries and how to make them fast</h3><p>The interviewer wanted actual queries, so here are the main ones.</p><p><strong>Searching for flights</strong></p><pre>SELECT id, flight_number, departure_time, arrival_time<br>FROM flights<br>WHERE source = &#39;DEL&#39;<br>  AND destination = &#39;BLR&#39;<br>  AND departure_time &gt;= &#39;2026-01-15&#39;<br>  AND departure_time &lt;  &#39;2026-01-16&#39;<br>ORDER BY departure_time;</pre><pre>CREATE INDEX idx_flights_route_time<br>ON flights (source, destination, departure_time);</pre><p>The order of columns matters here. The two equality columns go first and the range column goes last. With that order the database can jump straight to DEL to BLR flights and read that day’s flights already sorted, so the ORDER BY is free too. If departure_time came first, the range condition would stop the index from narrowing down on source and destination efficiently.</p><p><strong>Loading the seat map</strong></p><pre>SELECT seat_number, seat_class, price, status, held_until<br>FROM seats<br>WHERE flight_id = 101;</pre><p>No new index is needed for this one. The UNIQUE (flight_id, seat_number) constraint already creates an index that starts with flight_id. Unique constraints give you an index for free, which is easy to forget.</p><p><strong>Cleaning up expired holds</strong></p><pre>CREATE INDEX idx_seats_held<br>ON seats (held_until)<br>WHERE status = &#39;HELD&#39;;</pre><p>This is a partial index in Postgres. Only a tiny fraction of seats are held at any moment, so the index stays small and the cleanup job doesn’t scan the whole table.</p><p><strong>A user’s booking history</strong></p><pre>CREATE INDEX idx_bookings_user<br>ON bookings (user_id, created_at DESC);</pre><p>One more thing on performance. The seat map can be slightly stale and that’s okay, because the booking step re-checks availability in the database anyway. So the read path can be cached and the write path stays strict.</p><h3>Wrapping up</h3><p>If I had to pick the one part of this question that matters most, it’s the gap between choosing a seat and paying for it. Get the hold and confirm flow right and handle concurrent updates on the seat row, and most of the rest follows.</p><p>If you’d design any part of this differently, I’d like to hear how.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbdaf231cc92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My first system design interview, at Park+]]></title>
            <link>https://medium.com/@csaini3082/my-first-system-design-interview-at-park-98be8128d7d8?source=rss-765f923cc917------2</link>
            <guid isPermaLink="false">https://medium.com/p/98be8128d7d8</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[job-interview]]></category>
            <category><![CDATA[careers]]></category>
            <dc:creator><![CDATA[Chirag Saini]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 11:29:11 GMT</pubDate>
            <atom:updated>2026-10-02T11:29:11.049Z</atom:updated>
            <content:encoded><![CDATA[<p>In January this year I interviewed at Park+ for an SDE role. There were three rounds and at the end I didn’t get the offer.</p><p>The second round was a system design round, the first one I had ever given, and the question was to design a flight booking system. I’m writing this so that anyone with a design round coming up can skip the mistakes I made in it.</p><p>The key takeaways, which I go into at the end: ask clarifying questions before drawing anything, know at least one hard part of the problem properly, practice explaining out loud, and be ready to write real SQL.</p><p>I’ve written up how I would design the flight booking system now in a separate post.</p><h3>Round 1: CS fundamentals and Java</h3><p>Round 1 was about CS fundamentals and core Java. There were questions on how garbage collection works in the JVM, some general CS concepts, and database indexing. There was also a medium DSA problem, Koko Eating Bananas, which is a binary search on the answer.</p><p>I was able to answer everything and felt confident the whole way through. The feedback for this round was very positive, so I went into the next round feeling good.</p><h3>Round 2: Design a flight booking system</h3><p>The prompt was one line. Design a flight booking system.</p><h4>The mistake I made in the first two minutes</h4><p>I started drawing. Flight, Seat, User, Booking, Payment. I was already thinking about which object holds a reference to which.</p><p>I didn’t ask a single clarifying question. I didn’t know if they wanted a high level design with services and scaling, or a low level one with classes and a database schema. I didn’t know what was in scope. Search? Payments? Cancellations? One airline or many?</p><p>The interviewer was kind about it and steered me back. They laid out the flow they had in mind:</p><ol><li>The user searches for a flight.</li><li>The user sees which seats are vacant and picks the one they want.</li><li>The user makes the payment.</li></ol><p>Once I heard that, it was obvious what they cared about. The data model, the database, and the gap between picking a seat and paying for it, which is exactly where two people can end up fighting over the same seat.</p><h4>What they asked me</h4><ul><li>Which objects I picked and how they are associated with each other.</li><li>Which database I would use and why.</li><li>How I would stop the same seat from being booked twice.</li><li>The actual SQL queries the backend would run for this flow, and how I would make them fast.</li></ul><p>For the database I went with a relational one and explained my reasoning. Booking a seat means updating the seat, creating the booking and recording the payment, and all of that has to succeed or fail together. A relational database gives you ACID transactions for exactly that. The data is also very structured, with clear relationships between flights, seats, bookings and payments. Even so, I wasn’t fully sure it was the answer they were looking for.</p><p>For double booking I talked about optimistic and pessimistic locking in the database, and when you’d use each. This felt like solid ground and I think it went in my favour.</p><p>Then came the SQL. They wanted the queries for searching flights and loading seats, and how I’d speed them up with indexes. I could get the queries out, but I was slower and less sure here than I wanted to be.</p><p>I got nervous while sketching all of this. I knew most of the pieces on their own but I couldn’t put them together cleanly with someone watching.</p><h3>Round 3: Hiring manager</h3><p>Even though round 2 didn’t go well, I was called back for a third round with the hiring manager. It was a mix of DSA, my past experience, and Java and Spring Boot questions. Most of it went fine. I struggled a bit with the DSA problem.</p><p>A few days later I heard back. It was a no.</p><h3>What I’m taking away from this</h3><ul><li>Ask clarifying questions before you draw anything. The interviewer almost always has a specific flow in mind, and you’re wasting time until you know what it is.</li><li>The part that went well was the part I actually understood. I knew locking properly, so I could talk about it under pressure. The parts I only half knew fell apart.</li><li>Practice out loud with a timer. Reading about system design and explaining it while someone watches you are very different skills.</li><li>Expect to write real SQL and real schemas. It wasn’t all boxes and arrows.</li></ul><p>I didn’t get the role. But I’m much better prepared for the next design round than I was in January, and that’s mostly because of this one.</p><p>If you want to see how I’d answer the question now, I’ve covered it in a separate post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98be8128d7d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>