diff --git a/14. Design Online Shopping System/OnlineShoppingSystem.md b/14. Design Online Shopping System/OnlineShoppingSystem.md
new file mode 100644
index 0000000..f36b872
--- /dev/null
+++ b/14. Design Online Shopping System/OnlineShoppingSystem.md
@@ -0,0 +1,907 @@
+# Online Shopping Service
+
+
+
+- [Introduction](#introduction)
+ * [What is an Online Shopping Service](#what-is-an-online-shopping-service)
+ * [How Online Shopping Works](#how-online-shopping-works)
+- [Requirements](#requirements)
+ * [Functional Requirements](#functional-requirements)
+ * [Non-Functional Requirements](#non-functional-requirements)
+- [API Design](#api-design)
+ * [Product Recommendations](#product-recommendations)
+ * [Product Search](#product-search)
+ * [Cart Management](#cart-management)
+ * [Checkout](#checkout)
+ * [Order Tracking](#order-tracking)
+- [High Level Design](#high-level-design)
+ * [Note](#note)
+ * [Recommendations Flow](#recommendations-flow)
+ * [Product Search Flow](#product-search-flow)
+ * [Cart Management Flow](#cart-management-flow)
+ * [Checkout Flow](#checkout-flow)
+ * [Order Tracking Flow](#order-tracking-flow)
+- [Deep Dive Insights](#deep-dive-insights)
+ * [Database Selection](#database-selection)
+ * [Database Modelling](#database-modelling)
+ * [Search Algorithm](#search-algorithm)
+ * [Inventory Consistency](#inventory-consistency)
+ * [Recommendation Engine](#recommendation-engine)
+
+
+
+## Introduction
+### What is an Online Shopping Service
+Imagine a supermarket. You walk through the store, see different products, pick products, add them to your shopping cart, and go to the counter for checkout.
+At the counter, the cashier scans your items, accepts you payment and give you a receipt. After you leave, you can use the receipt to return your products if needed.
+
+
+
+An online shopping works the same way. The only difference is that everything happens digitally through internet.
+Instead of going to a physical store, you go to an online shopping website/app to browse and purchase the products you need. Similar to a physical shopping cart, the online store provides a digital cart where you can add the items you like and pay digitally using you Card, UPI, etc. Like the cashier, the backend system performs several tasks such as checking for inventory, handling payment, and generating receipt. Once your order is placed, you can track the status of the order until it reaches
+
+### How Online Shopping Works
+In an online shopping store, you search for the product you like to buy (Ex: sport shoes). The backend system runs a search algorithm to fetch and display all the results matching your description. The result includes different brands, shoe colors, and sizes. You pick the one you like and add it to the cart. During checkout, the backend system collects your address and process the payment through payment gateway. After placing the order, the system sends you regular updates about the delivery. The backend system remembers the products you viewed and purchased, and starts recommending similar products you might be interested in.
+
+
+
+There are multiple systems involved within the online shopping system to provide the best shopping experience for the customers:
+* Search Service - Fetch and display the product results matching the customer's description
+* Cart Management Service - Manages the item added to the shopping cart.
+* Payments Service - Securely handles the online payments
+* Order Management Service - Place and track customer orders
+* Recommendation Service - Provide recommendations to customers based on their preferences.
+
+---
+
+## Requirements
+### Functional Requirements
+In an ideal online shopping scenario, the user goes through a sequence of flows to purchase a product. The functional requirements are derived from this user journey.
+
+
+
+> We ignored the "Detail Page" flow in this design as it is a simple API to display the details of the product.
+
+* **Search products:** Users should be able to search for products using keywords.
+* **Add items to cart:** Users should be able to add products to their cart.
+* **View cart:** Users should be able to view all items in their cart with price, quantity, and total cost.
+* **Checkout and place order:** Users should be able to place an order with selected items and complete the payment.
+* **Track order status:** Users should be able to view order status and track shipment progress.
+* **View recommendations:** Users should receive personalized recommendations based on browsing and order history.
+
+### Non-Functional Requirements
+* **Low latency:** Search results should be returned within 500 ms.
+* **High availability:** The service should remain available during peak shopping events like Black Friday and Prime Day.
+* **Strong consistency:** Inventory must be strongly consistent to prevent overselling.
+* **Security:** User data, payment information, and order details must be encrypted and protected.
+* **Scalability:** The system should scale automatically to handle traffic spikes during sales and promotional events.
+---
+## API Design
+### Product Recommendations
+Recommendations allows the users to discover products they might be interested in based on their browsing history, and past purchases.
+
+This API retrieves personalized product recommendations for a user.
+
+
+
+**HTTP Method & Endpoint**
+
+We use `GET` method since we are retrieving recommendation data. The endpoint would be `/v1/recommendations`.
+
+**Query Parameters**
+
+```
+GET /v1/recommendations?limit=10
+```
+
+- `limit` - Number of recommendations to return (optional, default: 10)
+
+**HTTP Response**
+
+```json
+{
+ "recommendations": [
+ {
+ "productId": "prod_11111",
+ "name": "Apple AirPods Pro (2nd Gen)",
+ "price": 249.99,
+ "rating": 4.9,
+ "imageUrl": "https://cdn.shopping.com/images/prod_11111.jpg",
+ "reason": "Based on your recent views"
+ },
+ {
+ "productId": "prod_22222",
+ "name": "Bose QuietComfort 45",
+ "price": 329.99,
+ "rating": 4.7,
+ "imageUrl": "https://cdn.shopping.com/images/prod_22222.jpg",
+ "reason": "Customers who bought Sony headphones also bought this"
+ },
+ {
+ "productId": "prod_33333",
+ "name": "Anker USB-C Charging Cable",
+ "price": 14.99,
+ "rating": 4.6,
+ "imageUrl": "https://cdn.shopping.com/images/prod_33333.jpg",
+ "reason": "Frequently bought together"
+ }
+ ]
+}
+```
+
+### Product Search
+Product search allows the customers to search for the product they are interested in. For example, the customer enters keywords like "wireless headphones" and the system returns the relevant products. The search also supports adding filters like brand, price range, ratings. It also supports sorting options like price, ratings, etc.
+
+This API allows users to search for products using keywords and apply filters and sorting.
+
+
+
+**HTTP Method & Endpoint**
+
+This tells the server what action to perform. We use the `GET` method as we want to search the product with the given criteria. The `GET` method is used for read-only operations that don't alter system state. We will use the endpoint `/v1/products/search`. Here, `v1` means version 1 and is called API versioning. API versioning allows you to make changes to your APIs without breaking existing clients by using version numbers like `/v1/` or `/v2/` in the URL path.
+
+**Query Parameters**
+
+Since this is a `GET` request, search criteria are passed as query parameters in the URL rather than in the request body.
+
+```
+GET /v1/products/search?
+ q=wireless+headphones
+ &category=electronics
+ &minPrice=50
+ &maxPrice=200
+ &brand=Sony
+ &sort=price_asc
+ &page=1
+ &limit=20
+```
+
+- `q` - The search keyword or phrase
+- `category` - Filter by product category (optional)
+- `minPrice` - Minimum price filter (optional)
+- `maxPrice` - Maximum price filter (optional)
+- `brand` - Filter by brand name (optional)
+- `sort` - Sorting criteria: `relevance`, `price_asc`, `price_desc`, `rating`, `newest` (optional, default: `relevance`)
+- `page` - Page number for pagination (optional, default: 1)
+- `limit` - Number of results per page (optional, default: 20)
+
+**HTTP Response**
+
+The server returns a list of products matching the search criteria along with pagination metadata.
+
+```json
+{
+ "products": [
+ {
+ "productId": "prod_12345",
+ "name": "Sony WH-1000XM5 Wireless Headphones",
+ "description": "Industry-leading noise canceling headphones",
+ "price": 399.99,
+ "brand": "Sony",
+ "rating": 4.8,
+ "reviewCount": 2547,
+ "imageUrl": "https://cdn.shopping.com/images/prod_12345.jpg",
+ "inStock": true,
+ "availableQuantity": 145
+ },
+ {
+ "productId": "prod_67890",
+ "name": "Sony WF-1000XM4 Wireless Earbuds",
+ "description": "True wireless earbuds with exceptional sound",
+ "price": 279.99,
+ "brand": "Sony",
+ "rating": 4.7,
+ "reviewCount": 1823,
+ "imageUrl": "https://cdn.shopping.com/images/prod_67890.jpg",
+ "inStock": true,
+ "availableQuantity": 89
+ }
+ ],
+ "pagination": {
+ "currentPage": 1,
+ "totalPages": 15,
+ "totalResults": 287,
+ "hasNext": true
+ },
+ "filters": {
+ "availableBrands": ["Sony", "Bose", "Apple", "Samsung"],
+ "priceRange": {
+ "min": 29.99,
+ "max": 549.99
+ }
+ }
+}
+```
+
+### Cart Management
+The shopping cart allows the users to add their items they want to buy. Users can add items, remove items, update quantities, and view their cart contents before proceeding to checkout.
+
+> By default, a cart is created for a customer when they sign up on the shopping website. Therefore, there is no API to explicitly create a cart. However, the API design is extensible and can support multiple carts in the future by distinguishing carts using a `cartId`.
+
+#### View Cart
+
+This API fetches all the items currently added to the user's cart.
+
+
+
+**HTTP Method & Endpoint**
+
+We use the `GET` method since we are only retrieving information. The endpoint would be `/v1/cart/{cartId}`. We only pass `cartId` in the parameter which is
+sufficient to fetch cart information.
+
+**HTTP Response**
+
+```json
+{
+ "cartId": "cart_789",
+ "items": [
+ {
+ "cartItemId": "item_001",
+ "productId": "prod_12345",
+ "name": "Sony WH-1000XM5 Wireless Headphones",
+ "price": 399.99,
+ "quantity": 2,
+ "imageUrl": "https://cdn.shopping.com/images/prod_12345.jpg",
+ "inStock": true,
+ "subtotal": 799.98
+ },
+ {
+ "cartItemId": "item_002",
+ "productId": "prod_98765",
+ "name": "Samsung Galaxy Buds Pro",
+ "price": 199.99,
+ "quantity": 1,
+ "imageUrl": "https://cdn.shopping.com/images/prod_98765.jpg",
+ "inStock": true,
+ "subtotal": 199.99
+ }
+ ],
+ "summary": {
+ "subtotal": 999.97,
+ "tax": 79.99,
+ "shipping": 0.00,
+ "total": 1079.96,
+ "itemCount": 3
+ }
+}
+```
+
+#### Add Items to Cart
+
+This API allows users to add a product and the quantity to their shopping cart.
+
+
+
+**HTTP Method & Endpoint**
+
+We use `POST` method because adding an item to the cart creates a new entry in our system. The endpoint would be `/v1/cart/{cartId}/items`.
+
+**HTTP Body**
+
+```json
+{
+ "productId": "prod_12345",
+ "quantity": 2
+}
+```
+
+**HTTP Response**
+
+```json
+{
+ "cartId": "cart_789",
+ "cartItemId": "item_001",
+ "productId": "prod_12345",
+ "status": "success",
+ "message": "Item added to cart successfully",
+ "cartItemCount": 3
+}
+```
+
+#### Update Item Quantity
+This API allows users to modify the quantity of items already present in the cart
+
+
+
+**HTTP Method & Endpoint**
+
+We use `PATCH` method for this API because it updates only a specific field (quantity) of an existing
+item without replacing the entire item. The endpoint would be `/v1/cart/{cartId}/items/{itemId}`
+
+**HTTP Body**
+```json
+{
+ "quantity": 3
+}
+```
+
+**HTTP Response**
+```json
+{
+ "cartId": "cart_789",
+ "cartItemId": "item_001",
+ "productId": "prod_12345",
+ "status": "success",
+ "message": "Cart item quantity updated successfully",
+ "cartItemCount": 4
+}
+```
+
+#### Remove from Cart
+
+This API allows users to remove an item from the cart.
+
+
+
+**HTTP Method & Endpoint**
+
+We use the `DELETE` method since we are removing an item from the cart. The endpoint would be `/v1/cart/{cartId}/items/{itemId}`.
+
+**HTTP Response**
+
+```json
+{
+ "status": "success",
+ "cartItemId": "item_001",
+ "productId": "prod_12345",
+ "message": "Item removed from cart successfully",
+ "cartItemCount": 1
+}
+```
+
+### Checkout
+
+Checkout is the process where the users confirms their purchase. The user selects their delivery address and the payment method for checkout.
+The system checks inventory, reserve products, processes payment, and creates an order.
+
+This API allows users to place an order with items from their cart.
+
+
+
+**HTTP Method & Endpoint**
+
+We use the `POST` method because placing an order creates a new order record in the system. The endpoint would be `/v1/orders`.
+
+>
+
+**HTTP Body**
+
+```json
+{
+ "cartId": "cart_789",
+ "shippingAddressId": "address_123",
+ "paymentMethodId": "payment_xyz"
+}
+```
+
+**HTTP Response**
+
+```json
+{
+ "orderId": "order_54321",
+ "status": "ORDER_PLACED",
+ "estimatedDelivery": "2026-01-30",
+ "total": 1079.96,
+ "message": "Order placed successfully"
+}
+```
+
+### Order Tracking
+
+This API allows the users to track the current status of their order.
+
+
+
+**HTTP Method & Endpoint**
+
+We use the `GET` method since this is a read-only operation. The endpoint would be `/v1/orders/{orderId}`.
+
+**HTTP Response**
+
+```json
+{
+ "orderId": "order_54321",
+ "status": "SHIPPED",
+ "placedAt": "2026-01-26T14:32:00Z",
+ "items": [
+ {
+ "productId": "prod_12345",
+ "name": "Sony WH-1000XM5 Wireless Headphones",
+ "quantity": 2,
+ "price": 399.99
+ }
+ ],
+ "shippingAddress": {
+ "name": "John Doe",
+ "street": "123 Main Street",
+ "city": "Seattle",
+ "state": "WA",
+ "zipCode": "98101"
+ },
+ "tracking": {
+ "carrier": "UPS",
+ "trackingNumber": "1Z999AA10123456784",
+ "estimatedDelivery": "2026-01-30",
+ "currentLocation": "Seattle Distribution Center",
+ "history": [
+ {
+ "status": "ORDER_PLACED",
+ "timestamp": "2026-01-26T14:32:00Z",
+ "location": "Online"
+ },
+ {
+ "status": "PAYMENT_PROCESSED",
+ "timestamp": "2026-01-26T14:32:15Z",
+ "location": "Payment Gateway"
+ },
+ {
+ "status": "SHIPPED",
+ "timestamp": "2026-01-27T09:15:00Z",
+ "location": "Fulfillment Center - Tacoma, WA"
+ }
+ ]
+ },
+ "payment": {
+ "subtotal": 999.97,
+ "tax": 79.99,
+ "shipping": 0.00,
+ "total": 1079.96,
+ "paymentMethod": "CREDIT_CARD ending in 4242"
+ }
+}
+```
+
+## High Level Design
+
+Before diving deep into the high-level design of each component, we will first understand the different services involved in an online shopping system.
+
+* **API Gateway** - The entry point for all client requests, handles routing, authentication, and rate limiting.
+* **Order Service** - Receives the customer order and executes it.
+* **Cart Service** - Provides the details of the customer's cart such as items, and quantities.
+* **Inventory Service** - Checks item availability and temporarily reserves item for the customer's order.
+* **Fulfillment Service** - Handles the actual delivery of items in the customer's order.
+* **Address Service** - Provides the address of the customer to ship order
+* **Payment Service** - Deducts money from the customer's payment method.
+* **Notification Service** - Sends order confirmation/failure notification to the customers.
+* **Recommendation Service** - Shows recommendations for customers in the landing page.
+* **Product Search Service** - Fetch and return products based on customers search query.
+
+### Note
+
+Throughout this high-level design, we will discuss several backend services such as
+the Order Service, Inventory Service, Cart Service, etc. In a real system, each service typically sits behind an **API Gateway and a Load Balancer**, which receive incoming requests and route them to the appropriate backend servers. To keep the diagrams simple, I haven't shown these components explicitly, but you can assume they exist in front of every backend service.
+
+
+
+### Recommendations Flow
+
+The recommendations are shown on the landing page (home page) of the website.
+It shows personalized product suggestions to help users discover items they might like.
+In general, recommendations are shown based on data such as user's behavior, purchase history, etc. Recommendation system consists of two flows:
+1. **Recommendation Generation**: Customer data is analyzed to generate recommendations
+2. **Recommendation Retrieval**: Customer's recommendation is fetched and shown on their landing page.
+
+#### Recommendation Generation (Batch Processing)
+
+
+
+1. Every night (or on a fixed schedule), a batch job runs in the **Recommendation Service** to generate recommendations for all users.
+2. The **Recommendation Service** fetches user activity data from the **User Activity Database** and past purchases from the **Order Database**. User activities include their search queries, product views, cart additions, etc,
+3. The service also fetches product metadata from the **Product Catalog Database**, including categories, brands, descriptions, and attributes.
+4. The **Recommendation Service** runs machine learning models (collaborative filtering, content-based filtering, etc) to compute personalized recommendations for each user. Refer [Recommendation Engine](#recommendation-engine) section for more details
+5. The generated recommendations are stored in a **Recommendations Cache** (like Redis) with a TTL (Ex: 4 hours) for fast retrieval.
+
+#### Recommendation Retrieval (Real-time)
+
+
+
+1. When the user visits the landing page, a request (`GET /v1/recommendations`) is sent to the Recommendation Service to fetch the latest recommendations.
+2. The API Gateway of the shopping service receives the request and routes it to the *Recommendation Service**.
+3. The **Recommendation Service** checks the **Recommendations Cache** for pre-computed recommendations for this user. If recommendations are found in the cache (cache hit), they are returned.
+4. On cache miss, the **Recommendation Service** falls back to location-based trending products fetched from **Trending Product Cache**. Trending data is cached because it changes infrequently and is read frequently, allowing low-latency access.
+5. The recommendations are returned to the user's device and displayed on the page.
+
+### Product Search Flow
+The product search flow allows users to find the products using keywords, filters, and sorting options.
+The search engine indexes millions of products efficiently and returns the relevant search results in milliseconds.
+
+
+
+1. The user enters a search query like "wireless headphones" in the search bar on the mobile app or the website.
+2. The request reaches the **API Gateway** of the shopping service, which routes the request to the **Product Search Service**.
+3. The **Product Search Service** queries the **Search Index** (powered by Elasticsearch or similar technology) to fetching matching products. The search index stores pre-processed product data optimized for fast retrieval. It uses an inverted index structure where each word points to all products containing that word. Refer [Search Algorithm](#search-algorithm) section for more details.
+4. The search engine calculates a **relevance score** for each product based on factors like keyword matching, popularity, ratings, and user preferences. Products are ranked by this score.
+5. If the user has applied filters such as price range, brand, ratings, the search engine applies these filters to narrow down results.
+6. If the user selected sorting options like price low to high, newest arrivals, the results are sorted accordingly.
+7. The **Product Search Service** retrieves additional product details like images, prices, from the **Product Catalog Cache**. We use cache because product data is read frequently and changes infrequently, making it safe to cache for low-latency access.
+8. It also fetches the available quantity information from the **Inventory Cache**. Inventory cache is updated when data is updated in the `Inventory Database`
+ * Although inventory data must be strongly consistent to prevent overselling, we use cache because search page has higher traffic than cart or checkout. Hitting the inventory database for every search request is not scalable. Therefore, we display approximate availability from cache on the search page, and validate actual availability during the cart or checkout flow.
+9. The search service returns paginated results to the API Gateway, which sends them back to the user's device.
+10. The user's search query and clicked products are logged to the **User Activity Database** for future recommendation generation.
+
+### Cart Management Flow
+The cart management flow allows users to add products to their cart, update quantities, remove items, and view cart contents before checkout.
+
+#### 1. View Cart
+
+
+
+1. The user navigates to the cart page by clicking the cart icon. The request (`GET /v1/cart/{cartId}`) reaches the **API Gateway**. 2
+2. The **API Gateway** routes the request to the **Cart Service**.
+3. The **Cart Service** retrieves all cart items for the user from the **Cart Database**.
+4. For each cart item, the **Cart Service** fetches the latest product details (price, name, image) from the **Product Catalog Cache** to ensure prices are up-to-date.
+5. The **Cart Service** also verifies stock availability for each item by calling the **Inventory Service**. If any item is out of stock, it's flagged in the response so the user can remove it before checkout.
+6. The **Cart Service** calculates the subtotal, estimated tax, and total cost.
+7. The cart details are returned to the user's device and displayed on the cart page.
+
+#### 2. Add to Cart Flow
+
+
+
+1. The user clicks the "Add to Cart" button on a product page. The request (`POST /v1/cart/{cartId}/items`) reaches the **API Gateway** with the user ID, product ID, and desired quantity.
+2. The **API Gateway** routes the request to the **Cart Service**.
+3. The **Cart Service** first checks if the product is in stock by querying the **Inventory Service**.
+4. The **Inventory Service** checks the **Inventory Database** for the product's available quantity. If sufficient stock is available, the **Inventory Service** returns a success response.
+5. The **Cart Service** adds the item to the user's cart in the **Cart Database**.
+6. The **Cart Service** returns a success response with the updated cart item count. The user sees a confirmation message like "Item added to cart (3 items)".
+
+#### 3. Update Item Quantity Flow
+
+
+
+1. The user modifies the quantity of items in the cart. The request (`PATCH /v1/cart/{cartId}/items/{itemId}`) reaches the **API Gateway** with the user ID, product ID, and desired quantity.
+2. The **API Gateway** routes the request to the **Cart Service**.
+3. The **Cart Service** first checks if the sufficient quantities are available in stock by querying the **Inventory Service**.
+4. The **Inventory Service** checks the **Inventory Database** for the product's available quantity. If sufficient stock is available, the **Inventory Service** returns a success response.
+5. The **Cart Service** updates the item quantity in the **Cart Database**.
+6. The **Cart Service** returns a success response with the updated cart item count.
+
+#### 4. Remove from Cart Flow
+
+
+
+1. The user clicks the "Remove" button next to a cart item. The request (`DELETE /v1/cart/{cartId}/items/{itemId}`) reaches the **API Gateway**.
+2. The **API Gateway** routes the request to the **Cart Service**.
+3. The **Cart Service** deletes the specified item from the **Cart Database**.
+4. The **Cart Service** returns a success response with the updated cart item count.
+
+### Checkout Flow
+The Order/checkout flow is treated as an **atomic operation**: inventory reservation, payment processing, and order creation must either all succeed or all fail as a single logical unit. If any of the step fails, the system rolls back prior actions (for example, releasing reserved inventory) and no order is created.
+
+
+
+#### 1. Checkout Initiation
+1. The user goes to the checkout page, confirms shipping address and payment method, clicks **Place Your Order**. The client sends `POST /v1/orders` request with cart ID, address ID, and payment method ID.
+2. The **API Gateway** of the shopping service authenticates the user and routes the request to the **Order Service**.
+
+#### 2. Cart Validation & Inventory Reservation
+1. The **Order Service** invokes the **Cart Service** to fetch the cart items. The Cart Service fetches the data from **Cart Database** and return them.
+2. The **Order Service** requests the **Inventory Service** to reserve stock for all the cart items.
+3. The **Inventory Service** locks (reserves) the quantities for the cart items so that no other customer can buy them until this order is created/failed.
+For example, If 5 units of an item are available and a customer reserves 3 during checkout, only the remaining 2 units are available for other customers.
+4. If any item is unavailable, the reservation fails and checkout is aborted.
+
+#### 3. Payment Processing & Order Creation
+1. Once inventory is successfully reserved, the **Order Service** initiates the payment by invoking the **Payment Service** with the customers payment method ID. The Payment Service talks to the bank to
+deduct money from the customer's account. In most cases, OTP authentication is required. In such case, the Payment Service redirects the customers to the bank page to enter the OTP.
+2. If the payment fails:
+ * Reserved inventory is immediately released.
+ * No order is created.
+3. If the payment succeeds:
+ * A new order record is created in the **Order Database**.
+ * Reserved inventory is converted to committed sales and the quantities are decremented from available stock.
+
+#### 4. Post-Order Flow
+1. The **Order Service** invokes the **Cart Service** to clear the cart.
+2. The **Order Service** creates the order entry in the order database.
+3. It publishes the `Order Placed` event to the **Order Events Stream**. This is done so that interested services can receive the order event and perform the necessary action.
+4. The **Fulfillment Service** consumes the event via **Fulfillment Queue** and begins picking, packing, and shipping.
+5. The **Notification Service** consumes the event via **Notification Queue** to send order confirmation to the customer.
+6. The **Notification Service** sends the order details to the customer via SMS, email, and push notification (app).
+7. Finally, the order service, shows the order confirmation status to the customer.
+
+#### How the items are reserved during checkout
+The inventory data are stored in the inventory database. Each entry of the database will have the item ID, item Name, and its available quantity.
+During checkout, the inventory service blocks that items being checked out so that others cannot order the same item. There are multiple approaches
+available such as optimistic and pessimistic locking to reserve items. To learn more about inventory reservation refer section [Inventory Consistency](#inventory-consistency).
+
+### Order Tracking Flow
+After the order is placed, users want to track the delivery status. The tracking flow provides real-time status updates.
+
+
+
+1. The user clicks "Track Order" on the order confirmation page or navigates to "My Orders". The request (`GET /v1/orders/{orderId}`) reaches the **API Gateway** of the shopping service.
+2. The **API Gateway** routes the request to the **Order Service**.
+3. The **Order Service** fetches the order details from the **Order Cache**, including status, items, shipping address, and payment summary. The cache is updated when the data is updated in the **Order Database**
+4. The **Order Service** also invokes the **Fulfillment Service** to fetch the latest shipment tracking information.
+5. The **Fulfillment Service** retrieves tracking details from the **Fulfillment Cache**, which includes carrier name, tracking number, current location, and estimated delivery date. The cache is updated when the data is updated in the **Fulfillment Database**
+6. The **Order Service** combines order data and tracking data into a single response and send it back the user's device.
+
+**Real-time Updates:** As the order moves through different stages, the **Fulfillment Service** receives updates from shipping carriers (UPS, FedEx, etc.) and These updates are stored in the **Fulfillment Database**
+and trigger notifications to the user via email or push notifications.
+
+---
+
+## Deep Dive Insights
+### Database Selection
+We cannot make a "single database" choice for the entire online shopping system. Each functionality of the system will have a specific database choice based on the requirement.
+
+| Guideline | Recommendation |
+|---------------------------------------------------------------|----------------------|
+| When eventual consistency is not accepted | Use SQL (Relational) |
+| When eventual consistency is accepted | Use NoSQL |
+| When you need faster access | Prefer NoSQL |
+| When data correctness is critical (no partial failures) | Use SQL |
+| When row-level locking is required to block concurrent writes | Use SQL |
+| When it is read-heavy | Prefer NoSQL |
+| When you have simpler queries | NoSQL works well |
+
+Based on the above guidelines, we made the database choices for our online shopping
+service.
+
+
+ | Database |
+ Deciding Factors |
+ Decision |
+
+
+ | Product Catalog DB |
+
+
+ - Read-Heavy Data – Product details are read far more often than updated.
+ - Non-Critical Consistency – Slight delays in reflecting updates are acceptable.
+ - High Scalability – Must support millions of concurrent product views.
+
+ |
+ NoSQL (Document) |
+
+
+ | Inventory DB |
+
+
+ - Concurrent Checkouts – Multiple users may attempt to buy the same item.
+ - Strong Consistency – Stale data can cause overselling.
+ - Locking / Versioning – Requires optimistic or pessimistic locking.
+ - Atomic Updates – Quantity updates must be all-or-nothing.
+
+ |
+ Relational (ACID) |
+
+
+ | Cart DB |
+
+
+ - High Read & Write Throughput – Frequent updates during browsing.
+ - Eventual Consistency Acceptable – Cart is revalidated at checkout.
+
+ |
+ NoSQL (Key–Value / Document) |
+
+
+ | Order DB |
+
+
+ - Financial Source of Truth – Represents confirmed purchases.
+ - Atomic Order Creation – Order, payment status, and totals must be consistent.
+
+ |
+ Relational (ACID) |
+
+
+
+### Database Modelling
+#### Product Catalog Schema
+
+
+* Database Type: NoSQL (Document Store)
+* Common Queries:
+ * Fetch product details by `productId`
+ * Fetch products by category or brand
+* Indexing: `productId`, `category`, `brand`
+
+#### Inventory Schema
+
+
+* Database Type: Relational Database
+* Common Queries:
+ * Read available quantity during checkout
+ * Reserve and decrement inventory atomically
+* Indexing: `productId`
+
+#### Cart Schema
+
+* Database Type: NoSQL (Key-Value / Document Store)
+* Common Queries:
+ * Read cart by `cartId`
+ * Add, update, or remove cart items
+* Indexing: `cartId`, `userId`
+
+#### Order Schema
+
+* Database Type: Relational Database
+* Common Queries:
+ * Fetch order details by `orderId`
+ * Fetch all orders of a user by `userId`
+* Indexing: `orderId`, `userId`
+
+### Search Algorithm
+
+Search is the important entry point to sales in an online shopping platform. Most users know the items they like to purchase and search them in the website/app. A fast, accurate search engine can improve the user experience and conversion rates. But building a search system that handles millions of products and returns relevant results in milliseconds is challenging.
+
+Imagine there are 100 million products in the database, and a user searches for "wireless headphones". If we query the database directly using `SELECT * FROM products WHERE name LIKE '%wireless%' OR description LIKE '%headphones%'`, the database would scan every single row, which takes several seconds. The solution is to build a **search index**.
+
+#### Inverted Index
+
+Think of it like an index at the back of a textbook. Instead of reading every page to find mentions of "wireless", we flip to the index, which tells exactly which pages contain that word.
+
+
+
+Search engines like Elasticsearch use an **inverted index** data structure. Instead of mapping **product id to product name**, it maps **word to list of product ids"
+
+
+
+When a user searches for "wireless headphones", the search engine look up both words in the index: `wireless → [prod_001, prod_002]`, and
+`headphones → [prod_001, prod_003]`. The intersection of these lists gives products that contain **both** words. In this case, `prod_001` contains both the words `wireless` and `headphones`.
+
+When a new product is added to the catalog, the search engine processes it through several steps:
+
+1. **Tokenization** - The item name and description are split into a list of words, or tokens. For instance, "Sony Wireless Headphones" turns into [ "Sony", "Wireless", "Headphones"].
+2. **Normalization** - Convert the words to lowercase and remove any special characters. For example, "Headphones" turns into "headphones".
+3. **Stemming** - This step reduces words to their root form. For example, "running" become "run," and "headphones" become "headphone." That way, when a user searches for "headphone," we will also provide the results of "headphones."
+4. **Remove Stop Words** - Remove common words like "the", "a", "and" that don't add search value.
+5. **Indexing** - Add the tokens processed to the inverted index and map every token with the Product ID.
+
+
+### Inventory Consistency
+
+Inventory consistency is one of the critical challenges in e-commerce. Overselling of products (selling more items than available) lead to customer dissatisfaction, order cancellations, and revenue lost. But maintaining consistency when thousands of users are trying to buy the same popular product at the same time is very difficult.
+
+Assume there is only 1 iPhone 15 Pro left in stock. At the exact same time, two customers (Customer A and Customer B) add the iPhone to their cart and proceed to checkout. Lets say both the Customer A and Customer B places the order at the same time. Assume both the orders execute at the same time, both order gets placed but only one customer gets the product delivered and the other customers order get cancelled. This is called a **race condition** - two concurrent transactions read the same data and make decisions based on stale information.
+
+#### Pessimistic Locking
+
+Pessimistic locking prevents race conditions by locking the inventory row during the checkout process. When Customer A starts checkout, the system locks the iPhone 15 Pro inventory row. Customer B's checkout request waits until Customer A's transaction completes.
+
+
+
+**How it works:**
+
+1. Customer A clicks "Place Order".
+2. The Inventory Service acquires a lock on the database row of the iPhone 15 Pro.
+3. The lock prevents any other transaction from reading or modifying that row.
+4. The system checks if inventory is sufficient (1 available), place the order, and decrement the value to 0
+5. The lock is released
+6. Now Customer B's checkout request acquires the lock.
+7. The system checks inventory: 0 available and Customer B receives "Out of Stock" error.
+
+Pessimistic locking `prevent conflicts by blocking`. In a real-world system, when thousands of customers tries to buy the same item at the same time,
+we will block all other orders in favor of one order. This leads to **high latency for customers** and **resource wastage due to waiting transactions**.
+
+#### Optimistic Locking
+
+Optimistic locking assumes conflicts are rare. Instead of locking, the system uses a **version number** to detect conflicts. Since it doesn't have a locking mechanism, it doesn't block other transactions until the first transaction is completed.
+
+
+
+**How it works:**
+
+Each item of the inventory table has a `version` column.
+
+```
+product_id | available_quantity | version
+prod_12345 | 1 | 10
+```
+
+1. Customer A's checkout reads inventory. Available quantity is 1 and the version number is 10.
+2. At the same time, Customer B's checkout reads inventory. Available quantity is 1 and the version number is 10.
+3. Customer A's payment succeeds first. The system tries to update inventory using the below query. The query succeeds because the version is still 10. Version is incremented to 11.
+ ```sql
+ UPDATE inventory SET available_quantity = 0, version = 11 WHERE product_id = 'prod_12345' AND version = 10
+ ```
+4. Customer B's payment succeeds. The system tries to update inventory using the same query. This fails because version is now 11 and there is no entry with version 10. The database returns "0 rows updated".
+ ```sql
+ UPDATE inventory SET available_quantity = 0, version = 11 WHERE product_id = 'prod_12345' AND version = 10
+ ```
+5. The system detects this conflict and retries Customer B's checkout. During retry, we get the available quantity as 0 and the version number as 11
+6. Since there are 0 available quantity, Customer B receives"Out of Stock" error.
+
+Optimistic locking `detect conflicts and retry`. So, unlike pessimistic locking, we don't block all transactions in favor of
+one transaction. When a conflict it detected for other transactions, they retry again to resolve conflicts.
+
+### Recommendation Engine
+
+In online world, recommendation system drives significant amount of sales. The recommendations are shown like **Customers who bought this also bought...**, **Recommended for you**, etc. These suggestions are powered by complex algorithms and machine learning models. We will discuss some of the widely used approaches in recommendation systems.
+
+
+
+|
+
+**User Activity Based Recommendation**
+
+
+
+ |
+
+
+**Similar User Based Recommendation**
+
+
+
+ |
+
+
+
+
+
+
+
+#### The Cold Start Problem
+
+When a new user visits the platform for the first time, the system have no data about their preferences. So, it doesn't know what product to recommend. This is called the **cold start problem**. To solve the cold start problem, we use fallback strategies such as:
+
+* **Trending Products** - Show the products that are currently popular across all users.
+* **Category-Based Recommendations** - If the user browse for "Electronics", then show top-rated electronic items.
+* **Location-Based Recommendations** - Show the products that are popular in the user's region.
+
+As the user interacts with the platform, the system collects behavioral data and switches to personalized recommendations.
+
+#### Collaborative Filtering
+
+Collaborative filtering recommends products based on the interest from similar users. For example, if User A and User B have similar preferences, and if User A liked Product X, then User B will probably like Product X. So, this system recommends Product X to User B. We calculate the similarities between user's preferences using methods like `cosine similarity`.
+
+Cosine similarity is based on mathematical vectors and measures how similar two items are by comparing their vectors. If the angle between the two vectors are small, then they are more similar.
+
+
+
+We perform the below steps to identify the similarity:
+
+
+1. Build a **user-item interaction matrix** where rows are users, columns are products, and values are ratings/purchases/views. In this case, we used **ratings**.
+
+| | iPhone | AirPods | Galaxy | Sony_WH |
+|--------|--------|---------|--------|---------|
+| User A | 5 | 1 | 0 | 0 |
+| User B | 3 | 0 | 4 | 0 |
+| User C | 0 | 4 | 0 | 5 |
+| User D | 4 | 5 | 0 | 4 |
+
+2. Calculate the **similarity** between users using [cosine similarity](https://www.ibm.com/think/topics/cosine-similarity)
+
+```
+* Similarity(User A, User D) = 0.6 (very similar)
+* Similarity(User A, User B) = 0.5 (somewhat similar)
+* Similarity(User A, User C) = 0.1 (not similar)
+```
+3. When generating the recommendations for User A, find the users most similar to User A. In this case it is User D.
+4. Recommend products that User D liked but User A hasn't interacted with yet. In this case, it is Sony_WH.
+
+#### Content-Based Filtering
+
+Content-based filtering recommends products that are similar to the ones a user has already liked, by comparing their attributes (like category, brand, features, or keywords).
+
+
+
+This approach involves the below steps:
+
+1. Extract **features** from each product: category, brand, price.
+
+```
+iPhone 15 Pro: [category: smartphone, brand: Apple, price: high]
+AirPods Pro: [category: audio, brand: Apple, price: medium]
+Galaxy S24: [category: smartphone, brand: Samsung, price: high]
+```
+
+2. Build a **user profile** based on products the user interacted with. If the user viewed iPhone and AirPods, the profile is:
+
+```
+User A Profile: [brand: Apple (high preference), category: smartphone/audio, price: medium-high]
+```
+
+3. Recommend products that match the user's profile. Galaxy S24 matches [category: smartphone, price: high], so it might be recommended. But since the user prefers Apple, it ranks lower.
+
+#### Evaluation Metrics
+
+How do we know if the recommendation engine is working fine? We incoporate metrics to find the success rate of our recommendation. Some of the metrics include:
+
+* **Click-Through Rate (CTR):** - If 10,000 users see recommendations and 500 click on them, CTR = 5%. Higher the click-through rate, better the recommendations
+* **Conversion Rate:** - If 10,000 users see recommendations and 100 users purchase the recommended product, Conversion = 1%.
\ No newline at end of file
diff --git a/14. Design Online Shopping System/Resources/API_AddToCart.png b/14. Design Online Shopping System/Resources/API_AddToCart.png
new file mode 100644
index 0000000..1235aef
Binary files /dev/null and b/14. Design Online Shopping System/Resources/API_AddToCart.png differ
diff --git a/14. Design Online Shopping System/Resources/API_Checkout.drawio.png b/14. Design Online Shopping System/Resources/API_Checkout.drawio.png
new file mode 100644
index 0000000..7681d6b
Binary files /dev/null and b/14. Design Online Shopping System/Resources/API_Checkout.drawio.png differ
diff --git a/14. Design Online Shopping System/Resources/API_Checkout.png b/14. Design Online Shopping System/Resources/API_Checkout.png
new file mode 100644
index 0000000..a5e64a5
Binary files /dev/null and b/14. Design Online Shopping System/Resources/API_Checkout.png differ
diff --git a/14. Design Online Shopping System/Resources/API_DeleteCartItem.png b/14. Design Online Shopping System/Resources/API_DeleteCartItem.png
new file mode 100644
index 0000000..b1dc302
Binary files /dev/null and b/14. Design Online Shopping System/Resources/API_DeleteCartItem.png differ
diff --git a/14. Design Online Shopping System/Resources/API_OrderTracking.png b/14. Design Online Shopping System/Resources/API_OrderTracking.png
new file mode 100644
index 0000000..e28aa5d
Binary files /dev/null and b/14. Design Online Shopping System/Resources/API_OrderTracking.png differ
diff --git a/14. Design Online Shopping System/Resources/API_ProductSearch.png b/14. Design Online Shopping System/Resources/API_ProductSearch.png
new file mode 100644
index 0000000..5cbfff5
Binary files /dev/null and b/14. Design Online Shopping System/Resources/API_ProductSearch.png differ
diff --git a/14. Design Online Shopping System/Resources/API_Recommendations.png b/14. Design Online Shopping System/Resources/API_Recommendations.png
new file mode 100644
index 0000000..55a7254
Binary files /dev/null and b/14. Design Online Shopping System/Resources/API_Recommendations.png differ
diff --git a/14. Design Online Shopping System/Resources/API_UpdateCartItemQuantity.png b/14. Design Online Shopping System/Resources/API_UpdateCartItemQuantity.png
new file mode 100644
index 0000000..7f56fd9
Binary files /dev/null and b/14. Design Online Shopping System/Resources/API_UpdateCartItemQuantity.png differ
diff --git a/14. Design Online Shopping System/Resources/API_ViewCart.png b/14. Design Online Shopping System/Resources/API_ViewCart.png
new file mode 100644
index 0000000..53dbcc3
Binary files /dev/null and b/14. Design Online Shopping System/Resources/API_ViewCart.png differ
diff --git a/14. Design Online Shopping System/Resources/BookIndex.jpeg b/14. Design Online Shopping System/Resources/BookIndex.jpeg
new file mode 100644
index 0000000..a468f77
Binary files /dev/null and b/14. Design Online Shopping System/Resources/BookIndex.jpeg differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_CartSchema.png b/14. Design Online Shopping System/Resources/DiveDeep_CartSchema.png
new file mode 100644
index 0000000..da9569e
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_CartSchema.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_CollaborativeFiltering.png b/14. Design Online Shopping System/Resources/DiveDeep_CollaborativeFiltering.png
new file mode 100644
index 0000000..ffc29e2
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_CollaborativeFiltering.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_ContentBasedFiltering.png b/14. Design Online Shopping System/Resources/DiveDeep_ContentBasedFiltering.png
new file mode 100644
index 0000000..0f50b6f
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_ContentBasedFiltering.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_InventorySchema.png b/14. Design Online Shopping System/Resources/DiveDeep_InventorySchema.png
new file mode 100644
index 0000000..0d3d12d
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_InventorySchema.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_InvertedIndex.drawio.png b/14. Design Online Shopping System/Resources/DiveDeep_InvertedIndex.drawio.png
new file mode 100644
index 0000000..b55652d
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_InvertedIndex.drawio.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_InvertedIndex.png b/14. Design Online Shopping System/Resources/DiveDeep_InvertedIndex.png
new file mode 100644
index 0000000..b7a1ba7
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_InvertedIndex.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_OptimisticLocking.png b/14. Design Online Shopping System/Resources/DiveDeep_OptimisticLocking.png
new file mode 100644
index 0000000..fe825e8
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_OptimisticLocking.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_OrderSchema.png b/14. Design Online Shopping System/Resources/DiveDeep_OrderSchema.png
new file mode 100644
index 0000000..7ba783c
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_OrderSchema.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_PessimisticLocking.png b/14. Design Online Shopping System/Resources/DiveDeep_PessimisticLocking.png
new file mode 100644
index 0000000..b065ccb
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_PessimisticLocking.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_ProductSchema.png b/14. Design Online Shopping System/Resources/DiveDeep_ProductSchema.png
new file mode 100644
index 0000000..d4f7832
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_ProductSchema.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_RelatedCustomerBasedRecommendation.png b/14. Design Online Shopping System/Resources/DiveDeep_RelatedCustomerBasedRecommendation.png
new file mode 100644
index 0000000..457caa7
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_RelatedCustomerBasedRecommendation.png differ
diff --git a/14. Design Online Shopping System/Resources/DiveDeep_UserAcitivtyBasedRecommendation.png b/14. Design Online Shopping System/Resources/DiveDeep_UserAcitivtyBasedRecommendation.png
new file mode 100644
index 0000000..37626d4
Binary files /dev/null and b/14. Design Online Shopping System/Resources/DiveDeep_UserAcitivtyBasedRecommendation.png differ
diff --git a/14. Design Online Shopping System/Resources/HLD_AddToCart.png b/14. Design Online Shopping System/Resources/HLD_AddToCart.png
new file mode 100644
index 0000000..e8368e1
Binary files /dev/null and b/14. Design Online Shopping System/Resources/HLD_AddToCart.png differ
diff --git a/14. Design Online Shopping System/Resources/HLD_CheckoutFlow.png b/14. Design Online Shopping System/Resources/HLD_CheckoutFlow.png
new file mode 100644
index 0000000..2224a4f
Binary files /dev/null and b/14. Design Online Shopping System/Resources/HLD_CheckoutFlow.png differ
diff --git a/14. Design Online Shopping System/Resources/HLD_DeleteCartItem.png b/14. Design Online Shopping System/Resources/HLD_DeleteCartItem.png
new file mode 100644
index 0000000..d69aa72
Binary files /dev/null and b/14. Design Online Shopping System/Resources/HLD_DeleteCartItem.png differ
diff --git a/14. Design Online Shopping System/Resources/HLD_OrderTracking.png b/14. Design Online Shopping System/Resources/HLD_OrderTracking.png
new file mode 100644
index 0000000..a4227ec
Binary files /dev/null and b/14. Design Online Shopping System/Resources/HLD_OrderTracking.png differ
diff --git a/14. Design Online Shopping System/Resources/HLD_ProductSearch.png b/14. Design Online Shopping System/Resources/HLD_ProductSearch.png
new file mode 100644
index 0000000..b47d12e
Binary files /dev/null and b/14. Design Online Shopping System/Resources/HLD_ProductSearch.png differ
diff --git a/14. Design Online Shopping System/Resources/HLD_RecommendationGeneration.png b/14. Design Online Shopping System/Resources/HLD_RecommendationGeneration.png
new file mode 100644
index 0000000..a884be0
Binary files /dev/null and b/14. Design Online Shopping System/Resources/HLD_RecommendationGeneration.png differ
diff --git a/14. Design Online Shopping System/Resources/HLD_RecommendationRetrieval.png b/14. Design Online Shopping System/Resources/HLD_RecommendationRetrieval.png
new file mode 100644
index 0000000..c0db3d6
Binary files /dev/null and b/14. Design Online Shopping System/Resources/HLD_RecommendationRetrieval.png differ
diff --git a/14. Design Online Shopping System/Resources/HLD_UpdateCart.png b/14. Design Online Shopping System/Resources/HLD_UpdateCart.png
new file mode 100644
index 0000000..31f8174
Binary files /dev/null and b/14. Design Online Shopping System/Resources/HLD_UpdateCart.png differ
diff --git a/14. Design Online Shopping System/Resources/HLD_ViewCart.png b/14. Design Online Shopping System/Resources/HLD_ViewCart.png
new file mode 100644
index 0000000..d6c2b3e
Binary files /dev/null and b/14. Design Online Shopping System/Resources/HLD_ViewCart.png differ
diff --git a/14. Design Online Shopping System/Resources/HighLevelFlow.png b/14. Design Online Shopping System/Resources/HighLevelFlow.png
new file mode 100644
index 0000000..5591274
Binary files /dev/null and b/14. Design Online Shopping System/Resources/HighLevelFlow.png differ
diff --git a/14. Design Online Shopping System/Resources/Introduction_OnlineShopping.png b/14. Design Online Shopping System/Resources/Introduction_OnlineShopping.png
new file mode 100644
index 0000000..c219e9b
Binary files /dev/null and b/14. Design Online Shopping System/Resources/Introduction_OnlineShopping.png differ
diff --git a/14. Design Online Shopping System/Resources/Introduction_OnlineShoppingWorking.png b/14. Design Online Shopping System/Resources/Introduction_OnlineShoppingWorking.png
new file mode 100644
index 0000000..d7f83ec
Binary files /dev/null and b/14. Design Online Shopping System/Resources/Introduction_OnlineShoppingWorking.png differ
diff --git a/14. Design Online Shopping System/Resources/ShoppingService-Note_API_Gateway.png b/14. Design Online Shopping System/Resources/ShoppingService-Note_API_Gateway.png
new file mode 100644
index 0000000..5bb21cf
Binary files /dev/null and b/14. Design Online Shopping System/Resources/ShoppingService-Note_API_Gateway.png differ