Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

System Design blueprint · E-Commerce

E-commerce platform: buy, sell, deliver, return

An end-to-end marketplace that onboards sellers, sells their stock to buyers, splits orders by seller and warehouse, ships through courier partners, and runs returns, refunds and seller settlement. It must never oversell stock, charge a buyer twice, lose an order after payment, or pay a seller for an item that was refunded.

Steps
9
Subjective questions
33
Objective questions
33

The problem and the outcome

Problem: Marketplaces join many sellers, warehouses, payment methods and courier partners. When these are linked by ad-hoc calls, stock oversells, paid orders get stuck, tracking goes stale, and refunds and seller payouts drift away from what actually happened.

Outcome: Every order runs through an explicit state machine driven by idempotent events, so stock, money and shipments stay consistent. Buyers see reliable tracking and refunds, and sellers are settled from a ledger that can be reconciled line by line.

Architecture

Buyerweb / appSellerbusinessSearchindex + ranking02Cart & checkoutprice, tax, address02Seller portalKYC, catalogue01Payment gatewayUPI, cards, COD04Order servicesaga + split03Inventoryper warehouse SKU03Shipment serviceAWB, manifest05Event busorder + tracking06Returns servicerequest, pickup08Courier partnerpickup, deliver07Refund & payoutdouble-entry ledger09Quality checkpass or fail08KYC, listings, stockstock per warehousesearch, browseadd to cart, checkoutplace orderreserve with TTLcreate payment intentwebhook: capturedOrderConfirmedper sub-orderAWB + handovertracking webhooksreturn requestreverse pickupitem at warehousepass: refundrefund to sourcesettlement payout

How it works, step by step

  1. Seller onboarding: the seller completes KYC (PAN, GSTIN, bank account verification), then creates listings that map to a canonical product and a seller SKU, with stock recorded per warehouse; listing changes flow to the search index via change data capture.
  2. Discovery and cart: the buyer searches an index that ranks by relevance, availability and delivery promise for their pincode; the cart re-prices every line and computes GST and delivery charges at checkout, never trusting client-side prices.
  3. Order placement: the order service creates the order with an idempotency key, splits it into sub-orders by seller and fulfilling warehouse, and reserves each SKU with a conditional decrement and a short expiry so abandoned checkouts release stock.
  4. Payment: the buyer pays through the gateway (UPI, cards, net banking, or COD); the order is confirmed only on a verified, signature-checked webhook or a status poll, and a reservation that expires without payment is released and the payment auto-refunded if it arrives late.
  5. Fulfilment: for each sub-order the shipment service picks a courier by serviceability and cost, generates the AWB and label, and on courier pickup the reservation is converted into a committed stock deduction.
  6. Tracking: courier webhooks and polls are normalised into a single status model (picked up, in transit, out for delivery, delivered, RTO) and published to the event bus, where a forward-only state machine ignores duplicate or out-of-order events and triggers buyer notifications.
  7. Delivery confirmation: delivery is confirmed by OTP or proof of delivery, COD cash is recorded against the courier remittance, and the return window for each item starts from this timestamp.
  8. Returns: the buyer raises a return within policy, the returns service books a reverse pickup with the courier, and the item goes through quality check at the warehouse; a failed check is sent back to the buyer or raised as a dispute.
  9. Refund and settlement: on a passed check the ledger posts the refund to the original payment method or to the wallet (COD returns need a wallet or verified bank account), and seller payouts are released only after the return window closes, net of commission, fees, tax collected at source and any refunds.

Tech stack

  • PostgreSQL for orders, inventory and the double-entry ledger
  • Kafka with a transactional outbox (e.g. Debezium) for order and tracking events
  • Temporal or a similar workflow engine for order and return sagas
  • OpenSearch or Elasticsearch for catalogue search
  • Redis for carts, sessions and short-lived reservation counters
  • Payment gateway or aggregator with UPI, cards and refunds API (e.g. Razorpay, PayU, Cashfree)
  • Courier aggregator or direct courier APIs for AWB, pickup and tracking webhooks
  • Object storage and a CDN for product images and proof-of-delivery photos

Key design decisions

  • Split one checkout into sub-orders by seller and warehouse, but keep one payment and one buyer-facing order so cancellation, refund and settlement work per sub-order line.
  • Reserve inventory at order placement with an expiry rather than at add-to-cart, and commit the deduction at courier pickup, so carts never lock stock and cancellations before pickup just release it.
  • Use the database as the source of truth and publish events through a transactional outbox, so no event is emitted for an order that was not saved and no saved order misses its event.
  • Model money in an append-only double-entry ledger (buyer, platform, seller, courier, tax accounts) and derive refunds and payouts from it, instead of updating balance columns.
  • Hold seller payouts until the return window closes and settle through the regulated escrow/nodal arrangement the payment aggregator provides, so refunds can be funded without clawing back from sellers.

Common mistakes

  • Confirming orders from the client redirect instead of the server-verified webhook, which creates paid-but-missing or unpaid-but-confirmed orders.
  • Processing courier or payment webhooks without idempotency and ordering checks, so a late 'in transit' event overwrites 'delivered' or a refund is issued twice.
  • Reading stock from the search index or cache at checkout, which oversells during sales; the conditional decrement must run on the authoritative inventory row.
  • Refunding before quality check or settling the seller before the return window closes, which leaks money on fraudulent or damaged returns.
  • Ignoring RTO (return to origin) as a separate flow, so undelivered COD parcels never restock and seller and courier charges are wrong.

What to measure

  • Checkout conversion and payment success rate by method
  • Oversell or cancellation-due-to-stock rate per seller
  • Order-to-ship time and on-time delivery against the promised date
  • Tracking event lag from courier scan to buyer notification
  • Refund turnaround time and ledger-to-bank reconciliation mismatches

Most-asked interview questions

Subjective questions 33

1How do you stop overselling when thousands of buyers check out the same product during a flash sale?Asked almost every time

I make the inventory row per SKU per warehouse the single source of truth and reserve with a conditional update, something like decrement available where available is at least the requested quantity, inside a transaction. The reservation has an expiry, so unpaid checkouts release stock automatically. Search and product pages read cached availability, which may be slightly stale, but checkout never trusts it. For very hot SKUs I can pre-load a counter in Redis with an atomic decrement to absorb the burst, then write reservations to the database asynchronously with reconciliation. I commit the actual deduction at courier pickup. Finally I monitor stock-related cancellations per seller, because sellers updating stock late is a common real cause of overselling.

2Walk me through what happens if payment succeeds but your order service crashes before confirming the order.Asked almost every time

The order already exists in a pending state with an idempotency key before we create the payment intent, so nothing is lost. The gateway sends a signed webhook; if our service was down, the gateway retries, and we also run a reconciler that polls the gateway for pending orders older than a few minutes. Whichever path arrives first confirms the order, and the idempotency key makes the second a no-op. If the reservation already expired and stock is gone, we do not silently drop it: we either re-reserve from another warehouse or cancel and trigger an automatic refund, and tell the buyer. The confirmation and its event are written together through an outbox, so downstream shipment creation cannot miss it.

3Sketch the high-level architecture for this marketplace and explain where you draw the service boundaries.Asked almost every time

I split by business capability and data ownership. Seller service owns KYC and listings. Catalog and search own canonical products and a search index fed by change data capture. Cart and pricing re-price lines and compute GST and delivery charges. Order service owns orders and sub-orders. Inventory owns per-warehouse stock and reservations. Payment wraps the gateways. Shipment owns courier selection, AWBs and tracking. Returns owns reverse pickup and quality check. A double-entry ledger owns all money movement and seller payouts. Services talk through synchronous APIs only on the checkout path. Everything else goes through an event bus using the outbox pattern. Each service owns its own database. That way a slow courier API or search reindex never blocks order placement or payment.

4Design the core data model for orders, sub-orders, line items and shipments.Asked almost every time

An order is the buyer's checkout. It holds buyer ID, idempotency key, address snapshot, totals, payment status and a state. Sub-orders hang off it, one per seller and fulfilling warehouse pair, each with its own state, invoice number and GST breakup, because each seller issues its own tax invoice. Order lines belong to a sub-order. Each line holds the seller SKU, quantity, unit price snapshot, tax rate and amounts, and its own return and refund state, since returns are per item. Shipments reference a sub-order and carry the courier, AWB and tracking state. Reservations link a line to a warehouse stock row with an expiry. I snapshot prices and addresses rather than referencing mutable tables, so invoices and refunds stay reproducible.

5Why use a saga instead of a distributed two-phase commit across order, inventory and payment?Asked almost every time

The participants include external systems, such as payment gateways and couriers, that cannot join a two-phase commit. Even internally, 2PC holds locks across services and blocks if the coordinator fails, which is unacceptable during a sale. A saga breaks the flow into local transactions, each publishing an event, and each with a compensating action: reserve stock, then release on failure; capture payment, then refund; create the AWB, then cancel it. I prefer an orchestrated saga for checkout, with the order service as a durable state machine, because the flow and its timeouts are visible in one place. The cost is temporary inconsistency and the need for idempotent steps, which we handle with idempotency keys and the outbox.

6How would you design the refund and seller settlement so the money always adds up?Very often asked

I use an append-only double-entry ledger with accounts for the buyer, platform commission, each seller, courier charges and tax payable. Every business event, capture, cancellation, return refund, COD remittance, posts balanced entries; nothing edits a balance directly. Refunds go back to the original payment method through the gateway refund API, or to the wallet if the buyer chooses or the order was COD. Seller payouts are computed from the ledger after the return window closes, net of commission, fees, tax collected at source and refunds, and paid through the aggregator's escrow arrangement. A daily reconciliation job matches ledger entries against gateway settlement reports and bank statements, and any mismatch opens a ticket rather than being auto-corrected.

7Give a back-of-envelope capacity estimate for a flash sale, and say which numbers drive your design.Very often asked

I state my assumptions out loud. Say 10 million daily active users normally, and a sale that brings 2 million people in the first ten minutes, each doing about 20 search or product reads. That is roughly 40 million reads in 600 seconds, or about 65,000 reads per second, so catalog and search need caches and horizontal scaling. If 5 percent check out, that is 100,000 orders in ten minutes, about 170 per second on average, with peaks several times higher. The hard number is not orders per second overall. It is writes per second on a single hot SKU's stock row, which can hit thousands. That pushes me towards bucketed counters or a queue in front of that SKU, rather than simply adding more database nodes.

8A buyer's UPI payment succeeds two minutes after their stock reservation expired and the stock was sold to someone else. What happens?Very often asked

The payment webhook arrives, gets verified, and the payment service finds the order in an expired or cancelled state. It must not fulfil it. First it tries to re-reserve the same SKUs with a conditional decrement. If stock is available, I can confirm the order, provided that is our policy and the price is unchanged. If not, I record the payment against the order and trigger an automatic refund through the gateway's refund API with an idempotency key. The ledger posts both the capture and the refund. The buyer gets a clear notification. A reconciliation job later checks that every captured payment maps to either a confirmed order or a completed refund, so no money is stranded.

9Webhooks from the payment gateway sometimes never arrive. How do you make sure no paid order is left pending?Very often asked

I never depend on webhooks alone. When an order sits in payment-pending past a short threshold, a scheduler polls the gateway's order-status API with backoff until the payment is final or the reservation expires. Separately, a daily reconciliation job pulls the gateway's settlement report and matches every captured transaction against our payment records. Any mismatch raises an alert and goes into a repair queue. A captured but unknown payment either confirms the order or triggers a refund. A payment we marked successful that the gateway does not show is investigated before fulfilment. Webhook handlers and pollers write through the same idempotent confirm function, so whichever arrives first wins and the other is a no-op.

10Search shows a product as in stock, but checkout says it is sold out. Is that a bug, and how do you limit it?Very often asked

It is expected eventual consistency, not a correctness bug. The search index is fed by change data capture with some lag, while inventory is the source of truth at reservation time. So we can never oversell, but the buyer may be disappointed. To limit it, I stream stock changes with low lag. I index availability as coarse bands, such as in stock, low or out, rather than exact counts, so fewer updates are needed. When stock crosses zero I push a priority update. On the product page I fetch live availability from the inventory service or a short-TTL cache. I also track the rate of sold-out-at-checkout events as a metric, so lag regressions get noticed.

11How does checkout compute GST correctly when one cart has items from sellers in different states?Very often asked

GST is computed per sub-order, because each seller is the supplier and issues its own invoice. For each line, the tax engine takes the product's HSN code and rate, the seller's GSTIN state, and the place of supply, which is usually the buyer's delivery state. If supplier and place of supply are in the same state, it applies CGST plus SGST. If they differ, it applies IGST. Discounts that reduce the transaction value are applied before tax, according to the rules we have encoded. All of this runs on the server from catalog data, never from client prices. The computed breakup is stored on the line, so the invoice, credit notes and refunds reuse the exact figures.

12Explain how the tracking state machine handles duplicate, out-of-order and contradictory courier events.Very often asked

I map each courier's raw statuses into our normalised model and give each state a rank: picked up, in transit, out for delivery, then delivered or RTO as terminal states. Each event carries the courier's event time and a source ID. The consumer is idempotent on courier, AWB and event ID. A transition is applied only if it moves forward in rank, so a late 'in transit' after 'delivered' is stored in history but does not change state. Repeated 'out for delivery' attempts after failed deliveries are recorded as attempts, not as regressions. Genuinely contradictory terminal events, such as RTO after delivered, go to a manual exception queue rather than being auto-applied, because they affect refunds and payouts.

13A buyer's refund is approved after the seller has already been paid for that item. How do you recover the money?Very often asked

This should be rare, because payouts wait for the return window, but disputes, chargebacks and late RTOs make it possible. The ledger posts the refund to the buyer from the platform's account. It also posts a recovery entry debiting the seller's payable account, which can go negative. The next settlement run nets this negative balance against new earnings before paying anything. If the seller has no upcoming sales, an ageing process escalates to a direct recovery request under the seller agreement, and may suspend the listings. Tax documents follow too: the seller issues a credit note, and tax collected at source adjusts according to the rules. The buyer is never kept waiting on recovery from the seller.

14How do you handle a buyer cancelling one item from a multi-seller order before it ships?Very often asked

Cancellation works at line level. The order service checks that the line's sub-order has not been handed to a courier. If an AWB exists but pickup has not happened, it cancels the AWB too. It releases that line's reservation back to warehouse stock and recomputes the sub-order totals. Delivery charges are reapportioned according to policy. The ledger posts a partial refund for the line amount plus its tax, and the payment service issues the gateway refund with an idempotency key. The seller issues a credit note, or the invoice is never generated if we only invoice at dispatch. Other sub-orders are untouched. If the sub-order is already in transit, the request becomes a return after delivery or an RTO request, not a cancellation.

15How do you store and protect seller KYC data such as PAN and bank account details?Very often asked

I treat it as sensitive personal and financial data. Verification is done through licensed providers: PAN and GSTIN lookups, and bank account verification via a penny-drop or similar check. I store only what we need: the verification result, reference IDs and masked values for display. Full account numbers and PAN go into a separate, access-controlled vault with field-level encryption using keys in a KMS. Other services receive tokens, not raw values. Access is role-based, logged and reviewed. Under the DPDP Act we record the purpose and consent, limit retention to what the law and the contract need, and handle breach notification. Payout files are generated inside the payout service, so bank details never move around the event bus.

16How do you choose partition keys and ordering guarantees on the event bus?Very often asked

Ordering matters within an entity, not globally. Order lifecycle events are partitioned by order ID, so confirmation, cancellation and refund for one order are consumed in sequence. Shipment tracking events are keyed by AWB or shipment ID. Inventory change events are keyed by SKU and warehouse. Consumers still assume at-least-once delivery and possible reordering after rebalances or retries. So every event carries a version or sequence, and consumers are idempotent and reject stale versions. I avoid low-cardinality keys like seller ID for large sellers, because they create hot partitions. Failed events go to a retry topic and then to a dead-letter topic with alerts, rather than blocking the partition.

17Who generates the order idempotency key, what is its scope, and how long do you keep it?Very often asked

The client generates a unique key when the buyer starts checkout and reuses it on every retry of that same attempt. The server stores the key, the buyer ID, a hash of the request payload, and the resulting order ID or response. A unique constraint on buyer plus key makes duplicates return the original response. If the same key arrives with a different payload, we reject it with an error instead of guessing. The key lives at least as long as client retries and reservation expiry, typically hours to days. The order row keeps it permanently for audit. Downstream, the order ID itself becomes the idempotency reference for the gateway, refunds and courier calls.

18How would you compute the delivery promise shown for a buyer's pincode?Often asked

For each candidate warehouse holding stock, I need three things: processing time at that warehouse, which depends on the cut-off time and current backlog; courier serviceability between the origin and destination pincodes; and the courier's transit time for that lane. These come from courier serviceability files and our own historical delivery data. I precompute a lane table from warehouse pincode to destination pincode, with the best courier and its expected days, and refresh it regularly. At query time I pick the warehouse with stock that gives the earliest reliable date. I use a high percentile of historical transit time, not the average, so promises are kept. Search ranking uses the same data so results match the product page.

19The preferred courier's API is down when you need to generate AWBs for thousands of sub-orders. What do you do?Often asked

Shipment creation is asynchronous, so the order is already safe. The shipment service calls the courier with retries, exponential backoff and jitter, wrapped in a circuit breaker. When the breaker opens, the allocation engine falls back to the next serviceable courier for that lane, ranked by cost and performance. Work items sit in a durable queue, so nothing is lost and we resume when the courier recovers. Every AWB request carries our shipment ID as an idempotency reference, so a timeout followed by a retry cannot create two AWBs. If it does, a cleanup job cancels the orphan. I alert on the share of sub-orders breaching their dispatch SLA, not just on API errors.

20How do you reconcile cash-on-delivery money with courier partners?Often asked

When delivery is confirmed for a COD shipment, the ledger posts a receivable from that courier for the collected amount. Couriers remit cash periodically with a remittance file listing AWBs and amounts. A reconciliation job matches each line against our receivables. Matched items close the receivable. Short payments, missing AWBs or amounts for undelivered shipments become exceptions with ageing reports. Seller payouts for COD items depend on the return window closing, and I would also wait for the remittance to be received, so we never pay out cash we have not collected. Courier performance dashboards track remittance delays, and persistent short remittance can trigger reduced allocation to that courier.

21A returned item fails quality check because the buyer sent back a different product. Walk me through the flow.Often asked

The warehouse records the failed check with photos, weight and the reason against the return line. The refund is not posted. The returns service moves the line to a QC-failed state and notifies the buyer with the evidence. The buyer can accept reshipment of the item they returned, or raise a dispute within a defined period. Disputes go to a support queue where an agent reviews evidence from the seller, warehouse and courier. Depending on the outcome, we refund, reject, or partially refund. Throughout, the seller's settlement for that line stays on hold. The pattern also feeds fraud signals: repeated QC failures from one buyer or address raise their risk score.

22Can the platform store buyers' card numbers for faster checkout?Often asked

No. Under RBI rules, merchants and marketplaces must not store actual card numbers. Saved cards work through card-on-file tokenisation: with the buyer's consent, the card network or issuer issues a token specific to our merchant and that card. We store only the token, the last four digits and the issuer name. Card entry happens in the gateway's hosted fields or SDK, so raw card data never touches our servers. That sharply reduces our PCI DSS scope. We still follow PCI requirements for any component in the payment flow, never log payment payloads with sensitive data, and keep the payment service isolated on the network from the rest of the platform.

23A seller updates stock from their own system via API while buyers hold reservations on that SKU. How do you avoid corrupting the count?Often asked

I keep on-hand stock, reserved quantity and committed quantity as separate fields. Available stock is on-hand minus reserved. A seller update sets on-hand stock, or applies a delta. It never overwrites the reserved figure. Updates carry a version or sequence number, so a stale feed that arrives late is rejected. If the seller sets on-hand below the current reserved quantity, available goes to zero, and we flag that the seller may not be able to fulfil existing orders, instead of cancelling them silently. Bulk feeds are processed per warehouse and per SKU using the same conditional-update path, and every change emits a CDC event so search reflects it.

24What would you monitor and alert on for this workflow?Often asked

I focus on business invariants, not just service health. On the money side: captured payments without a confirmed order or refund, ledger imbalance, refunds stuck past their SLA, and payout failures. On inventory: negative available stock, which should never happen, reservation expiry rate, and sold-out-at-checkout rate. On orders: checkout success rate split by payment method, and payment-pending age. On fulfilment: sub-orders breaching dispatch SLA, AWB failures per courier, and tracking events stuck in the dead-letter queue. On returns: QC backlog age. Each also has standard RED metrics: rate, errors and duration. Reconciliation jobs report their mismatch counts as metrics. Alerts page on invariant breaches immediately, while trend metrics go to dashboards.

25What fraud and abuse patterns would you design for, and how?Often asked

On the seller side: fake or duplicate sellers, prevented with KYC and by checking whether PAN, GSTIN or bank accounts are reused across accounts; and counterfeit listings, handled through brand-gating and reports. On the buyer side: COD refusal abuse, handled by limiting COD by risk score and pincode; return fraud such as sending back a different item, caught by warehouse QC with photos and serial checks; and promotion abuse through multiple accounts, detected with device and payment fingerprints. On payments: card testing and chargebacks, handled by gateway risk tools plus our own velocity limits. I feed these signals into a risk score consulted at checkout, COD eligibility and returns. Rules stay explainable, because support must justify decisions to customers.

26How would you design disaster recovery for the order and ledger databases?Often asked

These need the lowest data loss, so I run synchronous replication within a region across availability zones, giving effectively zero data loss for a zone failure. I add asynchronous replication to a second region for a regional disaster. I state the RPO honestly: a regional failover can lose the last seconds of writes. Reconciliation against the gateways and courier systems is what repairs that gap: payments captured but missing from our database are found and fixed. Failover is a rehearsed runbook with fencing, so two primaries never accept writes. I take backups with point-in-time recovery, and run regular restore drills. Stateless services and caches are simply redeployed. Search can be rebuilt from the catalog.

27The seller changes a product's price while a buyer is on the payment page. Which price does the buyer pay?Often asked

At order placement, the server re-prices every line and snapshots the price and tax onto the order. That is the contract. The amount sent to the gateway is derived from that snapshot, so a later price change does not affect the order in flight. If the price changed between the cart view and placing the order, checkout shows the new total and asks the buyer to confirm before creating the payment. If the reservation expires and the buyer retries, we re-price again. Coupons and offers are validated server-side at the same moment. This avoids charging a different amount from the one shown, and avoids a seller being bound to a stale price indefinitely.

28How do you handle a shipment that ends in RTO because the buyer refused delivery or could not be reached?Often asked

When the RTO status becomes terminal, meaning delivered back to origin, the warehouse checks the item and restocks it. That stock is added back to on-hand via the inventory service, because the committed deduction happened at pickup. For prepaid orders, the ledger posts a refund to the original method. Policy decides whether forward shipping is deducted. For COD, no cash was collected, so the courier receivable is cancelled. The seller gets no payout for that line, and the RTO shipping cost is allocated according to the seller agreement. Repeated COD refusals feed the buyer risk score. Since the item never reached the buyer, there is no return window. The line is closed as RTO.

29How do you cache the catalog and product pages without showing wrong prices or stock?Often asked

I split the page into static and dynamic parts. Product content, images and specifications are cached heavily in a CDN and application cache, and invalidated through CDC events when a listing changes. Price, offers, stock band and the delivery promise are fetched from fast services with short TTLs, or are invalidated on change. Prices shown on the page are advisory, because checkout re-prices from the source of truth anyway. To protect against stampedes when a sale starts, I pre-warm caches for promoted SKUs, use request coalescing, and set a small stale-while-revalidate window. Personalised fields such as the buyer's pincode promise are computed per request, not cached in shared layers.

30A buyer asks you to delete their account under the DPDP Act, but GST rules require you to keep invoices. How do you reconcile the two?Often asked

The DPDP Act allows retention where another law requires it, so erasure is scoped, not absolute. I delete or anonymise data whose purpose has ended: profile, saved addresses, browsing history, recommendations and marketing consent. Invoices, order records and ledger entries that tax and accounting laws require are kept for the statutory period. They are moved to a restricted archive, with access limited to finance and compliance roles. Each data category has a documented purpose and retention rule. A scheduled job deletes the archived records when their legal period ends. Open obligations such as pending refunds or disputes must be closed first. The buyer is told what was deleted and what was kept, and why.

31A buyer wants to cancel an order that has been picked up by the courier but not yet delivered. How do you handle it?Often asked

The reservation is already committed and the parcel is moving, so a normal cancellation is no longer possible. Where the courier supports it, we raise an RTO request, so the shipment is returned to the warehouse without a delivery attempt. Otherwise the buyer can refuse delivery. Either way, the line moves into a cancellation-in-transit state. The refund for prepaid orders is posted only once the RTO is delivered back and checked, or earlier if the policy accepts that risk for low-value items. COD orders need no refund. The item is restocked after warehouse checks, and the costs follow the cancellation policy. The tracking state machine drives all of this, so the cancellation and courier events cannot conflict.

32A seller payout fails because their bank account was closed. What should the system do?Sometimes asked

The payout service sends transfers with an idempotency reference per settlement batch line. When the bank or payout provider reports a failure or a reversal, the ledger reverses the payout entry, so the amount sits back in the seller's payable balance. Nothing is lost or double-paid. The seller is notified and asked to add and re-verify a new account through the same penny-drop check. Payouts stay on hold until verification succeeds. Retries apply only to transient errors such as timeouts, never to permanent failures like a closed account. Finance gets an ageing report of held payouts, and changes to bank details trigger extra verification and a cooling period to reduce account-takeover risk.

33How would you test that the system never double-charges or double-ships under failures?Sometimes asked

I write the invariants as automated checks: one confirmed order per idempotency key; every captured payment maps to a confirmed order or a refund; available stock is never negative; ledger debits equal credits. Then I attack them. Contract tests replay gateway and courier webhooks duplicated, out of order and delayed. Fault injection kills the order service between the database commit and the event publish, and between the gateway call and the response. Load tests run a flash-sale scenario on one hot SKU. In staging, chaos experiments drop broker partitions and fail over the database. After every run, the reconciliation jobs execute and must report zero unexplained mismatches. Production runs the same reconciliations continuously.

Objective questions 33

1A payment gateway delivers the same 'payment captured' webhook three times. What prevents the order from being confirmed and fulfilled three times?Asked almost every time
  1. AProcessing the webhook idempotently, keyed on the payment or order ID with a state checkCorrect answer
  2. BSending the webhook to three separate queues
  3. CAsking the gateway to disable retries
  4. DIncreasing the webhook timeout

Why: Gateways deliberately retry webhooks, so the handler must treat repeats as no-ops by keying on a unique ID and only moving the order forward from the expected state.

2Which SQL statement safely reserves one unit of stock without overselling under concurrent checkouts?Asked almost every time
  1. ASELECT available FROM stock WHERE sku = ?, then UPDATE stock SET available = <value read minus 1> in the application
  2. BUPDATE stock SET available = available - 1 WHERE sku = ? AND warehouse = ? AND available >= 1, then check that one row was affectedCorrect answer
  3. CUPDATE stock SET available = available - 1 WHERE sku = ?
  4. DINSERT INTO reservations, and reconcile stock with a nightly batch job

Why: The conditional decrement is atomic in the database, and an affected row count of zero means no stock was left, so concurrent buyers cannot drive the count below zero.

3What is the correct way to verify a payment gateway webhook before confirming an order?Asked almost every time
  1. ATrust the payload, because the URL is secret
  2. BConfirm the order from the client-side success callback
  3. CCheck that the request came from a known IP address only
  4. DCompute an HMAC over the raw request body with the shared webhook secret, compare it with the signature header, then confirm the statusCorrect answer

Why: Signature verification over the raw body proves authenticity and integrity. The status can also be cross-checked by polling the gateway.

4Why does the order service reserve inventory with an expiry at order placement instead of deducting stock when an item is added to the cart?Very often asked
  1. AGST rules require deduction only at delivery
  2. BCarts are stored in Redis and cannot touch the database
  3. CDeducting at add-to-cart would lock stock for buyers who never pay, while an expiring reservation frees it automaticallyCorrect answer
  4. DReservations make search results faster

Why: Most carts are abandoned; an expiring reservation holds stock only during the payment window and releases it if payment never completes.

5Which pattern guarantees that an 'OrderConfirmed' event is published if and only if the order confirmation is committed to the database?Very often asked
  1. APublishing to Kafka first, then writing the database
  2. BTransactional outbox: write the event to an outbox table in the same transaction, then relay it to the brokerCorrect answer
  3. CHaving consumers poll the orders table every second
  4. DTwo-phase commit between the database and every consumer

Why: The outbox row commits atomically with the order change, and a relay publishes it at least once, so state and events cannot diverge; consumers handle duplicates idempotently.

6A seller registered in Karnataka ships to a buyer in Maharashtra. Which GST applies to that sub-order?Very often asked
  1. AIGSTCorrect answer
  2. BNo GST, because it is a marketplace sale
  3. CCGST plus SGST of Karnataka
  4. DCGST plus SGST of Maharashtra

Why: When the supplier's state and the place of supply differ, the supply is inter-state and attracts IGST.

7A shipment is in state 'delivered', and then an 'in transit' event arrives from the courier. What should the forward-only state machine do?Very often asked
  1. ARecord the event in history, but leave the state as 'delivered'Correct answer
  2. BDelete the shipment and recreate it
  3. CCrash the consumer so the event is retried
  4. DMove the shipment back to 'in transit'

Why: Lower-ranked events after a terminal state are late or out-of-order, so they are stored for audit but do not change state.

8Which partition key best preserves the order of lifecycle events for a single order on Kafka?Very often asked
  1. ASeller ID
  2. BOrder IDCorrect answer
  3. CEvent type
  4. DRandom key, for even spread

Why: Keying by order ID routes all events for an order to one partition, which preserves their relative order.

9What may an Indian merchant store to support saved cards under RBI rules?Very often asked
  1. AThe full card number encrypted with AES
  2. BThe card number and CVV in a vault
  3. CA network or issuer token plus the last four digits and the issuer nameCorrect answer
  4. DThe card number hashed with SHA-256

Why: RBI card-on-file tokenisation forbids merchants from storing actual card data, so only tokens and limited display data are kept.

10When should a seller's payout for an item be released in this design?Very often asked
  1. AAt courier pickup
  2. BAfter the return window closes, net of commission, fees, TCS and refundsCorrect answer
  3. CWhen the order is placed
  4. DAs soon as the buyer pays

Why: Waiting for the return window avoids paying sellers for items that are later refunded.

11At which step does a stock reservation become a committed stock deduction?Very often asked
  1. AAfter the return window closes
  2. BWhen the item is added to the cart
  3. CWhen the order is created
  4. DOn courier pickup of the sub-orderCorrect answer

Why: In this workflow, the reservation converts to a committed deduction when the courier picks up the shipment.

12A client retries order creation with the same idempotency key but a different cart payload. What should the server do?Very often asked
  1. ASilently return the first order
  2. BCreate a second order
  3. COverwrite the first order with the new payload
  4. DReject the request with an error such as 409 or 422, because the key is being reused for a different requestCorrect answer

Why: Matching a payload hash to the key detects misuse. Returning or overwriting would hide a client bug and risk charging for the wrong cart.

13In an orchestrated checkout saga, payment fails after stock was reserved. What is the compensating action?Very often asked
  1. ADeduct the stock permanently
  2. BRoll back the database with a distributed transaction
  3. CRelease the reservation and mark the order payment-failed or cancelledCorrect answer
  4. DKeep the reservation until a human reviews it

Why: Sagas undo completed local steps with compensations. Here that means releasing reserved stock.

14Which invariant must always hold in a double-entry ledger?Very often asked
  1. ASeller balances equal the order totals
  2. BEvery account balance is positive
  3. CFor each transaction, total debits equal total creditsCorrect answer
  4. DRefunds are stored as updates to the original entry

Why: Balanced entries per transaction ensure money is never created or lost. Corrections are made with new entries, not edits.

15How should monetary amounts be stored in the order and ledger services?Very often asked
  1. AAs integer paise, or a fixed-precision decimal, with the currency recordedCorrect answer
  2. BAs strings formatted for display
  3. CAs float paise
  4. DAs floating-point rupees

Why: Binary floating point introduces rounding errors. Integer minor units or fixed decimals keep sums exact.

16A payment is captured after its reservation expired and the stock is gone. What is the correct behaviour?Very often asked
  1. AIgnore the webhook
  2. BConfirm the order and backorder the item silently
  3. CKeep the money as a store credit without telling the buyer
  4. DRecord the payment and trigger an idempotent automatic refund to the buyerCorrect answer

Why: The workflow requires a late payment for a released reservation to be auto-refunded, so money is never stranded.

17What is the main purpose of the daily payment reconciliation job?Very often asked
  1. ATo match the gateway's settlement reports against internal payment and order records and surface mismatchesCorrect answer
  2. BTo recompute GST rates
  3. CTo rebuild the search index
  4. DTo speed up checkout

Why: Reconciliation catches missed webhooks, crashes and mismatches that real-time flows cannot guarantee to avoid.

18A single hot SKU's stock row becomes a write bottleneck during a flash sale. Which mitigation is appropriate?Very often asked
  1. ACache the stock count in the browser
  2. BIncrease the reservation expiry
  3. CRemove the conditional check to speed up writes
  4. DSplit the stock into several bucketed counter rows and reserve from any bucket with stock, or serialise requests through a queueCorrect answer

Why: Bucketing spreads contention across rows while keeping each decrement conditional. A queue serialises access without row-lock contention.

19What delivery guarantee should event consumers such as notifications and the tracking state machine assume?Very often asked
  1. AAt-most-once delivery, so retries are pointless
  2. BGlobal ordering across all topics
  3. CExactly-once end-to-end delivery, so no deduplication is needed
  4. DAt-least-once delivery, with idempotent processing keyed on an event ID or versionCorrect answer

Why: Brokers redeliver on retries and rebalances, so consumers must deduplicate to avoid duplicate side effects.

20The same seller ships to a buyer in its own state. How is GST split on the invoice?Often asked
  1. ACGST and SGSTCorrect answer
  2. BOnly CGST
  3. COnly SGST
  4. DIGST only

Why: An intra-state supply is taxed as central GST plus state GST.

21Which approach is typical for streaming listing changes from the seller database to the search index?Often asked
  1. AA nightly full export only
  2. BHaving search query the seller database directly
  3. CDual-writing from application code to the database and the index
  4. DLog-based change data capture, such as Debezium reading the database write-ahead log or binlogCorrect answer

Why: Log-based CDC captures every committed change reliably and in order, without the inconsistency risk of dual writes.

22A COD order is returned and passes quality check. Where can the refund go?Often asked
  1. ATo the buyer's wallet or a verified bank accountCorrect answer
  2. BTo the courier, who returns the cash
  3. CNowhere, because COD orders are not refundable
  4. DBack to the original payment method, because the cash was collected

Why: COD has no electronic instrument to reverse, so the refund needs a wallet credit or a verified bank account.

23From which event does the return window for an item start?Often asked
  1. ACourier pickup
  2. BDelivery confirmation via OTP or proof of deliveryCorrect answer
  3. COrder placement
  4. DPayment capture

Why: The workflow starts each item's return window from the confirmed delivery timestamp.

24Which statement about the search index's availability data is correct?Often asked
  1. AIt must be updated before every inventory write commits
  2. BIt must be strongly consistent with inventory, or overselling occurs
  3. CIt is eventually consistent; reservation at checkout is the source of truth that prevents oversellingCorrect answer
  4. DIt should be the system of record for stock

Why: Search can lag. Correctness comes from the conditional reservation at checkout, not from the index.

25In Indian e-commerce logistics, what does RTO mean?Often asked
  1. AReturn to Origin: the shipment goes back to the seller or warehouse undeliveredCorrect answer
  2. BRefund Transfer Order
  3. CReverse Transit Optimisation
  4. DRegional Transport Office approval

Why: RTO happens when delivery fails or is refused and the parcel is sent back to its origin.

26Which Indian law primarily governs the processing of buyers' and sellers' digital personal data?Often asked
  1. ADigital Personal Data Protection Act 2023Correct answer
  2. BConsumer Protection Act 2019
  3. CPayment and Settlement Systems Act 2007
  4. DInformation Technology Act 2000, Section 43A rules only

Why: The DPDP Act 2023 and its rules are India's personal data protection framework, replacing the earlier Section 43A regime.

27How does a GSTIN relate to the seller's PAN?Often asked
  1. AThe GSTIN is the PAN with a prefix of 'GST'
  2. BThe PAN embeds the GSTIN
  3. CThey are unrelated identifiers
  4. DThe 15-character GSTIN embeds the 10-character PAN after a 2-digit state codeCorrect answer

Why: A GSTIN is a state code, then the PAN, then the entity number, a 'Z' and a check digit, so you can cross-validate it against the PAN.

28What is penny-drop verification used for during seller onboarding?Often asked
  1. AVerifying GST returns
  2. BChecking the seller's credit score
  3. CTesting the payment gateway's load capacity
  4. DConfirming that a bank account exists and matching the account holder's name by sending a small creditCorrect answer

Why: A small test credit returns the beneficiary name from the bank, which confirms the account before payouts.

29Which retry strategy suits calls to a flaky courier API?Often asked
  1. ARetrying on a fixed one-second interval forever
  2. BImmediate tight-loop retries until success
  3. CExponential backoff with jitter, a retry cap and a circuit breakerCorrect answer
  4. DNo retries at all

Why: Backoff with jitter avoids synchronised retry storms, and a circuit breaker allows fallback to another courier.

30The cart shows a price from the client app. What does checkout use to charge the buyer?Often asked
  1. AA server-side re-price from the catalog and offer services, snapshotted onto the orderCorrect answer
  2. BThe lowest price seen in the session
  3. CThe price in the search index
  4. DThe client-sent price, if it is signed by the app

Why: Client prices can be tampered with or stale. The server re-prices and snapshots the amount that is actually charged.

31A refund is issued after the seller was paid, and the seller has no balance. How does the ledger handle it?Often asked
  1. AWrites the amount off automatically
  2. BDeletes the original payout entry
  3. CDebits the seller's payable account, letting it go negative, and nets it against future settlementsCorrect answer
  4. DDelays the buyer's refund until the seller pays

Why: An append-only recovery entry records the debt, and future payouts are offset, while the buyer is refunded promptly.

32What does AWB stand for in courier shipping?Sometimes asked
  1. AAutomated Warehouse Batch
  2. BAir WaybillCorrect answer
  3. CAddress Within Boundary
  4. DApproved Weight Band

Why: An Air Waybill number uniquely identifies a shipment with the courier and is used for labels and tracking.

33Right after placing an order, a buyer opens 'My Orders' and the order is missing because the read replica is lagging. What is the best fix?Sometimes asked
  1. ARoute reads of the buyer's own recent orders to the primary, or a caught-up replica, for a short window after the writeCorrect answer
  2. BTell users to refresh
  3. CCache an empty result
  4. DSwitch the whole system to synchronous replicas everywhere

Why: Read-your-writes routing fixes the visible lag for the writer without giving up replicas for general reads.

Track your progress through every blueprint in your dashboard.

Start learning