├── Low level design.md ├── Low-level design code ├── Ecommerce Platform │ ├── Cart.java │ ├── Category.java │ ├── Customer.java │ ├── Item.java │ ├── MyFlipKart.java │ ├── Order.java │ ├── OrderLog.java │ ├── OrderStatus.java │ ├── Product.java │ ├── ProductsCatalog.java │ ├── Searchable.java │ ├── Seller.java │ ├── Shipment.java │ └── User.java ├── Online Movie Ticket Booking System │ ├── BookMyShow.java │ ├── Genre.java │ ├── GuestUser.java │ ├── Language.java │ ├── Movie.java │ ├── RegisteredUser.java │ ├── Show.java │ ├── Theater.java │ ├── Ticket.java │ ├── TicketBookingThread.java │ └── User.java └── Parking Lot │ ├── Admin.java │ ├── AutomatedSystem.java │ ├── Customer.java │ ├── DisplayBoard.java │ ├── ParkingLot.java │ ├── ParkingSpot.java │ ├── Status.java │ ├── Ticket.java │ └── Vehicle.java ├── Microservices.md └── README.md /Low level design.md: -------------------------------------------------------------------------------- 1 | # Low-level design: 2 | 3 | ## Objects and Classes: 4 | * Objects: 5 | * A real world element in object oriented environment, that may have physical or conceptual existence. 6 | * Classes: 7 | * Blueprint or description of objects, that can be created from it. 8 | 9 | ![image](https://user-images.githubusercontent.com/55986045/128104789-2b1a8546-90c4-4634-8bd4-467a08be9655.png) 10 | ![image](https://user-images.githubusercontent.com/55986045/128104809-cfae4358-6d90-4354-bf76-a02ac5c14723.png) 11 | 12 | 13 |
14 | 15 | ## Software development process: 16 | * Problem solving process: 17 | 1. Requirements Analysis 18 | 2. Design 19 | 3. Implementation 20 | 4. Delivery 21 | 22 | ![image](https://user-images.githubusercontent.com/55986045/128104662-1d095595-a305-4ed4-9440-5cdaa31e3223.png) 23 | 24 | 25 |
26 | 27 | ## UML Diagram: 28 | * The Unified Modeling Language (UML) is a standard graphical language for modeling object-oriented software. 29 | * As UML is a graphical language, it supports two types of diagrams which can be classified as: 30 | ![image](https://user-images.githubusercontent.com/55986045/127788611-5ed3f83c-2df2-4213-8ff4-08a1163f21ba.png) 31 | 32 | * Structural: 33 | * The structural Diagrams are used to create a static model of the software. 34 | * That is it gives an idea, what all components build up the system. 35 | * Behavioral: 36 | * The Behavioral Diagrams are used to create a dynamic model of the software. 37 | * It tells how the different components or modules interact with each other. 38 | 39 | * Some of the structural and behavioral diagrams supported by UML are: 40 | ![image](https://user-images.githubusercontent.com/55986045/128104576-45f10b17-dfb3-4ab6-b8c4-235b6634b9b2.png) 41 | 42 |
43 | 44 | ## Class Diagram and Object Diagram: 45 | * ### Class diagram: 46 | * A class diagram in the Unified Modeling Language (UML) is a type of structural diagram that describes the structure of a system by showing the System's Classes, their Attributes, Operations (or methods), and the relationships among objects. 47 | * In a class diagram a class is represented with the help of a rectangular box having three partitions: 48 | * The first partition contains the class name, 49 | * The second partition contains all the attributes of the class. 50 | * The third partition contains all the functionalities of the class. 51 | ![image](https://user-images.githubusercontent.com/55986045/128105232-e75658dd-62fc-4773-972c-8d7e6521b809.png) 52 | 53 | * Relationships: 54 | * The connection between the two classes in a class diagram is called Relationship. A class may be involved in one or more relationships with other classes. 55 | ![image](https://user-images.githubusercontent.com/55986045/128105338-2d81c6ea-afbc-44d6-a4a2-d5156eea0f62.png) 56 | 57 | 1. Association: 58 | * It shows that one class is associated with other classes. 59 | * In class diagrams, we can connect two classes with a solid line. 60 | ![image](https://user-images.githubusercontent.com/55986045/128105456-1cdbccb2-0373-4f1b-9722-915f5b5f6289.png) 61 | 62 | 2. Multiplicity: 63 | * Multiplicity of Association tells us: how many objects of each class take part in the relationship? 64 | ![image](https://user-images.githubusercontent.com/55986045/128105676-78dd7764-cd6b-4b67-97a8-246a42771cb9.png) 65 | 66 | 3. Generalization/Inheritence: 67 | * Parent-child class relationship 68 | ![image](https://user-images.githubusercontent.com/55986045/128105806-cd08107d-6046-462f-ba37-992295a0385f.png) 69 | 70 | 4. Aggregation: 71 | * Whenever we need to represent any class that is a part of another class, we can use aggregation. 72 | ![image](https://user-images.githubusercontent.com/55986045/128105931-4339101a-4a0d-4ec3-9958-20fcb47ee37f.png) 73 | 74 | * ### Object diagram: 75 | * We use OBJECT DIAGRAMS to show objects in software designs. 76 | ![image](https://user-images.githubusercontent.com/55986045/128106100-a40ac05a-5bcc-403a-95ff-37c28aec8716.png) 77 | ![image](https://user-images.githubusercontent.com/55986045/128106128-5e96a3b2-45c2-4f13-9c92-50a59f5f8349.png) 78 | 79 | 80 | 81 |
82 | 83 | ## Use Case Diagram: 84 | * In UML, use case diagrams are high level diagrams. 85 | * It provides a basic high level view about the system. 86 | * Four major components are: 87 | * System: 88 | * The application/software component we are going to develop. 89 | * Actor: 90 | * Any external agent that can interact with the system. 91 | * Two types: 92 | 1. Primary Actors (on the left side of use case diagram) 93 | * Responsible for initiating action. 94 | 2. Secondary Actors (on the right side of use case diagram) 95 | * Responsible for Response/Reactions 96 | 97 | ![image](https://user-images.githubusercontent.com/55986045/128103409-56f7af30-3a29-44dc-8bef-a50405fbf59b.png) 98 | 99 | * Use-Case: 100 | * Shows task within the system. Example: Registration, Login, Search, etc. 101 | 102 | * Relationship: 103 | * Relationship are represented by solid line from actors to use-case. 104 | * Types: 105 | 1. Association (between actors and use-case) 106 | * ![image](https://user-images.githubusercontent.com/55986045/128103237-29b4a4c5-925d-4655-a4a1-6fc46ed6fecf.png) 107 |
108 | 109 | 2. Inclusive (base use-case -> inclusive use-case) 110 | * ![image](https://user-images.githubusercontent.com/55986045/128103613-88d874fa-47f1-4230-95f3-cfac2ce2bd37.png) 111 |
112 | 113 | 3. Dependent 114 | * ![image](https://user-images.githubusercontent.com/55986045/128103677-2585bc6e-740e-429b-9523-ef6d2458f5d5.png) 115 |
116 | 117 | 4. Inheritance 118 | * ![image](https://user-images.githubusercontent.com/55986045/128103766-d0785d00-aa0c-4175-80d2-5735f7ac1849.png) 119 |
120 | 121 | Final diagram: 122 | ![image](https://user-images.githubusercontent.com/55986045/128103790-758ecc4b-9877-4967-894c-76b5774f117a.png) 123 | 124 | 125 |
126 | 127 | ![image](https://user-images.githubusercontent.com/55986045/128106505-5f6af2be-0983-4299-ab57-cfad3a9fd962.png) 128 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/Cart.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | 4 | public class Cart { 5 | private ArrayList itemList; 6 | 7 | public Cart() { 8 | this.itemList = new ArrayList<>(); 9 | } 10 | 11 | public void addItem(Item item){ 12 | itemList.add(item); 13 | } 14 | public void removeItem(Item item){ 15 | itemList.remove(item); 16 | } 17 | public void updateItemCount(Item item, int newCount){ 18 | int index = itemList.indexOf(item); 19 | itemList.get(index).updateCount(newCount); 20 | } 21 | public ArrayList getitemList(){ 22 | return itemList; 23 | } 24 | public void checkout(){ 25 | itemList.clear(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/Category.java: -------------------------------------------------------------------------------- 1 | 2 | public class Category { 3 | private String name; 4 | private String description; 5 | 6 | public Category(String name) { 7 | this.name = name; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/Customer.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.Date; 4 | 5 | public class Customer extends User { 6 | private Cart cart; 7 | private Order currentOrder; 8 | private ArrayList orderHistory; 9 | 10 | public Customer(String name, String phone) { 11 | super(name, phone); 12 | cart = new Cart(); 13 | orderHistory = new ArrayList<>(); 14 | } 15 | 16 | public void addItemToCart(Item item){ 17 | this.cart.addItem(item); 18 | } 19 | public void removeItemFromCart(Item item){ 20 | this.cart.removeItem(item); 21 | } 22 | public void printCartItems(){ 23 | System.out.println(this.cart.getitemList()); 24 | } 25 | public void updateItemCount(Item item, int newQuantity){ 26 | this.cart.updateItemCount(item,newQuantity); 27 | } 28 | public void placeOrder(){ 29 | currentOrder = new Order(); 30 | currentOrder.setOrderStatus(OrderStatus.UNSHIPPED); 31 | currentOrder.setOrderDate(new Date()); 32 | ArrayList orderedItems = this.cart.getitemList(); 33 | double orderAmount = 0; 34 | for(Item item : orderedItems){ 35 | orderAmount += item.getPrice(); 36 | } 37 | currentOrder.setItems(orderedItems); 38 | currentOrder.setAmount(orderAmount); 39 | currentOrder.setShippingAddress(this.getAddress()); 40 | this.cart.checkout(); 41 | this.orderHistory.add(currentOrder); 42 | } 43 | 44 | public ArrayList getOrderHistory() { 45 | return orderHistory; 46 | } 47 | 48 | public Order getCurrentOrder() { 49 | return currentOrder; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/Item.java: -------------------------------------------------------------------------------- 1 | 2 | public class Item { 3 | private int productId; 4 | private int count; 5 | private double price; 6 | 7 | public Item(Product product, int count) { 8 | this.productId = product.getId(); 9 | this.count = count; 10 | this.price = product.getPrice() * count; 11 | } 12 | 13 | public double getPrice() { 14 | return price; 15 | } 16 | 17 | @Override 18 | public String toString() { 19 | return "Item{" + 20 | "productId=" + productId + 21 | ", count=" + count + 22 | ", price=" + price + 23 | '}'; 24 | } 25 | 26 | public void updateCount(int newCount){ 27 | price = (price/count) * newCount; 28 | count = newCount; 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/MyFlipKart.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | 4 | public class MyFlipKart { 5 | public ProductsCatalog productsCatalog; 6 | 7 | public MyFlipKart() { 8 | productsCatalog = new ProductsCatalog(); 9 | } 10 | 11 | public static void main(String[] args) { 12 | // -------Data generation code ---- START ------------------------------// 13 | 14 | // Creating Customer --> Piyush 15 | Customer piyush = new Customer("Piyush Khandelwal","9876987655"); 16 | 17 | // Creating Seller --> Daily Needs Groceries 18 | Seller dailyNeedsGrocery = new Seller("Daily Needs Groceries","9876543210"); 19 | 20 | // Creating Seller --> Fashion Point 21 | Seller fashionPoint = new Seller("Fashion Point","9988776655"); 22 | 23 | // Creating Seller --> Digi Electronics 24 | Seller digiElectronics = new Seller("Digi Electronics","9876598765"); 25 | 26 | // Creating category --> Electronics 27 | Category electronics = new Category("Electronics"); 28 | 29 | // Creating category --> Cosmetics 30 | Category cosmetics = new Category("Cosmetics"); 31 | 32 | // Creating category --> Grocery 33 | Category grocery = new Category("Groceries"); 34 | 35 | // Creating category --> Clothing 36 | Category clothing = new Category("Clothing"); 37 | 38 | // -------Data generation code ---- END ------------------------------// 39 | 40 | MyFlipKart myFlipKart = new MyFlipKart(); 41 | 42 | // Adding all the categories to Flipkart catalog 43 | myFlipKart.productsCatalog.addCategory(clothing); 44 | myFlipKart.productsCatalog.addCategory(grocery); 45 | myFlipKart.productsCatalog.addCategory(cosmetics); 46 | myFlipKart.productsCatalog.addCategory(electronics); 47 | 48 | // Seller Digi Electronics adding Mobile to myFlipKart catalog 49 | digiElectronics.registerProduct(myFlipKart.productsCatalog, 50 | new Product("Mobile","Latest Technology",10000.00,electronics,5)); 51 | 52 | // Seller Digi Electronics adding Camera to myFlipKart catalog 53 | digiElectronics.registerProduct(myFlipKart.productsCatalog, // 54 | new Product("Camera","Advanced Technology",50000.00,electronics,10)); 55 | 56 | // Seller FashionPoint adding Wearbles to myFlipKart catalog 57 | fashionPoint.registerProduct(myFlipKart.productsCatalog, // 58 | new Product("Mens Jackets","XL - Size",1000.00,clothing,10)); 59 | 60 | fashionPoint.registerProduct(myFlipKart.productsCatalog, // 61 | new Product("Jackets","XL - Size",1000.00,clothing,10)); 62 | 63 | // Seller FashionPoint adding Cosmetics to myFlipKart catalog 64 | fashionPoint.registerProduct(myFlipKart.productsCatalog, // 65 | new Product("Nail Paint","Red Color",500.00,cosmetics,25)); 66 | 67 | // Seller dailyNeedsGrocery adding grocery to myFlipKart catalog 68 | dailyNeedsGrocery.registerProduct(myFlipKart.productsCatalog, // 69 | new Product("Sugar","Fine quality",40.00,grocery,1000)); 70 | 71 | // Seller dailyNeedsGrocery adding grocery to myFlipKart catalog 72 | dailyNeedsGrocery.registerProduct(myFlipKart.productsCatalog, // 73 | new Product("Milk","100% Pure",50.00,grocery,250)); 74 | 75 | dailyNeedsGrocery.registerProduct(myFlipKart.productsCatalog, // 76 | new Product("Toned Milk","Hygenic and Pure",45.00,grocery,250)); 77 | 78 | dailyNeedsGrocery.registerProduct(myFlipKart.productsCatalog, // 79 | new Product("Milk Cream","Natural",145.00,grocery,100)); 80 | 81 | 82 | // Customer searching for product --> milk 83 | ArrayList milkResults = myFlipKart.productsCatalog.searchProduct("Milk"); 84 | //System.out.println(milkResults); 85 | 86 | // Customer searching for all the products in grocery 87 | ArrayList groceryProducts = myFlipKart.productsCatalog.searchCategory("Groceries"); 88 | //System.out.println(groceryProducts); 89 | 90 | // Customer adding 10 packets of milk to cart 91 | Item milkTenPackets = new Item(milkResults.get(0),10); 92 | piyush.addItemToCart(milkTenPackets); 93 | 94 | // Printing current cart status 95 | piyush.printCartItems(); 96 | 97 | // Customer searching for another product --> camera 98 | ArrayList cameraResults = myFlipKart.productsCatalog.searchProduct("CaMeRa"); 99 | //System.out.println(cameraResults); 100 | 101 | // Customer adding 1 camera to cart 102 | Item oneCamera = new Item(cameraResults.get(0),1); 103 | piyush.addItemToCart(oneCamera); 104 | 105 | // Printing current cart status 106 | piyush.printCartItems(); 107 | 108 | // Customer updating quantity of milk packets from 10 to 15 109 | piyush.updateItemCount(milkTenPackets,15); 110 | 111 | // Printing current cart status 112 | piyush.printCartItems(); 113 | 114 | // Customer placing the order 115 | piyush.placeOrder(); 116 | 117 | // Customer cart is empty after checkout 118 | piyush.printCartItems(); 119 | 120 | // Printing the current Order of customer 121 | System.out.println(piyush.getCurrentOrder()); 122 | 123 | // Customer order is moved to shipment 124 | Shipment s = piyush.getCurrentOrder().moveToShipment(); 125 | 126 | // Printing the shipment details 127 | System.out.println(s); 128 | 129 | 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/Order.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.Date; 4 | import java.util.function.DoubleBinaryOperator; 5 | 6 | public class Order { 7 | private static int numberCounter =0; 8 | private int orderNumber; 9 | private OrderStatus orderStatus; 10 | private Date orderDate; 11 | private ArrayList items; 12 | private double amount; 13 | private String shippingAddress; 14 | private ArrayList orderLogs; 15 | 16 | public Order() { 17 | numberCounter += 1; 18 | this.orderNumber = numberCounter; 19 | orderLogs = new ArrayList<>(); 20 | addOrderLog(new OrderLog(new Date(),OrderStatus.CREATED)); 21 | } 22 | 23 | public Shipment moveToShipment(){ 24 | Shipment shipment = new Shipment(this); 25 | return shipment; 26 | } 27 | 28 | public void addOrderLog(OrderLog orderLog){ 29 | orderLogs.add(orderLog); 30 | } 31 | public void setOrderStatus(OrderStatus orderStatus) { 32 | this.orderStatus = orderStatus; 33 | addOrderLog(new OrderLog(new Date(),orderStatus)); 34 | } 35 | 36 | public void setOrderDate(Date orderDate) { 37 | this.orderDate = orderDate; 38 | } 39 | 40 | public void setItems(ArrayList items) { 41 | this.items = new ArrayList<>(items); 42 | } 43 | 44 | public void setAmount(double amount) { 45 | this.amount = amount; 46 | } 47 | 48 | public void setShippingAddress(String shippingAddress) { 49 | this.shippingAddress = shippingAddress; 50 | } 51 | 52 | @Override 53 | public String toString() { 54 | return "Order{" + 55 | "orderNumber=" + orderNumber + 56 | ", orderStatus=" + orderStatus + 57 | ", orderDate=" + orderDate + 58 | ", items=" + items + 59 | ", amount=" + amount + 60 | ", shippingAddress='" + shippingAddress + ''' + 61 | '}'; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/OrderLog.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Date; 3 | 4 | public class OrderLog { 5 | private Date creationTimestamp; 6 | private OrderStatus status; 7 | 8 | public OrderLog(Date creationTimestamp, OrderStatus status) { 9 | this.creationTimestamp = creationTimestamp; 10 | this.status = status; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/OrderStatus.java: -------------------------------------------------------------------------------- 1 | 2 | public enum OrderStatus { 3 | CREATED,PENDING, UNSHIPPED, SHIPPED, CANCELLED, COMPLETED; 4 | } 5 | 6 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/Product.java: -------------------------------------------------------------------------------- 1 | 2 | public class Product { 3 | private static int idCounter=0; 4 | private int id; 5 | private String name; 6 | private String description; 7 | private double price; 8 | private double ratings; 9 | private Category category; 10 | private int availableCount; 11 | private Seller seller; 12 | 13 | public Product(String name, String description, double price, 14 | Category category, int availableCount) { 15 | idCounter += 1; 16 | this.id = idCounter; 17 | this.name = name; 18 | this.description = description; 19 | this.price = price; 20 | this.category = category; 21 | this.availableCount = availableCount; 22 | } 23 | 24 | public int getId() { 25 | return id; 26 | } 27 | 28 | public String getName() { 29 | return name; 30 | } 31 | 32 | public String getDescription() { 33 | return description; 34 | } 35 | 36 | public double getPrice() { 37 | return price; 38 | } 39 | 40 | public double getRatings() { 41 | return ratings; 42 | } 43 | 44 | public Category getCategory() { 45 | return category; 46 | } 47 | 48 | public int getAvailableCount() { 49 | return availableCount; 50 | } 51 | 52 | public void setSeller(Seller seller) { 53 | this.seller = seller; 54 | } 55 | 56 | public void setAvailableCount(int availableCount) { 57 | this.availableCount = availableCount; 58 | } 59 | 60 | @Override 61 | public String toString() { 62 | return "Product{" + 63 | "id=" + id + 64 | ", name='" + name + ''' + 65 | ", description='" + description + ''' + 66 | ", price=" + price + 67 | ", ratings=" + ratings + 68 | ", category=" + category + 69 | ", availableCount=" + availableCount + 70 | ", seller=" + seller + 71 | '}'; 72 | } 73 | 74 | public Seller getSeller() { 75 | return seller; 76 | } 77 | } 78 | 79 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/ProductsCatalog.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Set; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | public class ProductsCatalog implements Searchable{ 9 | private ArrayList products; 10 | private ArrayList categories; 11 | private HashMap> categoryProductMap; 12 | private HashMap> productSellerMap; 13 | private ConcurrentHashMap> similarProducts; 14 | 15 | public ProductsCatalog(){ 16 | products = new ArrayList<>(); 17 | categories = new ArrayList<>(); 18 | categoryProductMap = new HashMap<>(); 19 | similarProducts = new ConcurrentHashMap<>(); 20 | similarProducts.put("Dummy Product",new ArrayList()); 21 | productSellerMap = new HashMap<>(); 22 | } 23 | 24 | public void updateSimilarProductsMap(Product newProduct){ 25 | String productName = newProduct.getName().toLowerCase(); 26 | Set keySet = similarProducts.keySet(); 27 | boolean isSimilar = false; 28 | for (String key : keySet){ 29 | if(key.toLowerCase().contains(productName) || productName.contains(key.toLowerCase())) { 30 | isSimilar = true; 31 | similarProducts.get(key).add(newProduct); 32 | } 33 | } 34 | if(!isSimilar){ 35 | similarProducts.put(newProduct.getName().toLowerCase(),new ArrayList(List.of(newProduct))); 36 | } 37 | } 38 | private void updateCategoryProductMap(){ 39 | for(Category category : categories){ 40 | categoryProductMap.put(category.getName().toLowerCase(), new ArrayList()); 41 | } 42 | } 43 | private void updateCategoryProductMap(Product product){ 44 | if(categoryProductMap.containsKey(product.getCategory().getName().toLowerCase())){ 45 | categoryProductMap.get(product.getCategory().getName().toLowerCase()).add(product); 46 | } else{ 47 | categoryProductMap.put(product.getCategory().getName().toLowerCase(),new ArrayList<>(List.of(product))); 48 | } 49 | 50 | } 51 | private void updateProductSellerMap(Product newProduct){ 52 | if(productSellerMap.containsKey(newProduct.getName().toLowerCase())){ 53 | productSellerMap.get(newProduct.getName().toLowerCase()).add(newProduct.getSeller()); 54 | }else{ 55 | productSellerMap.put(newProduct.getName().toLowerCase(),new ArrayList<>(List.of(newProduct.getSeller()))); 56 | } 57 | } 58 | 59 | public void addCategory(Category newCategory){ 60 | categories.add(newCategory); 61 | updateCategoryProductMap(); 62 | 63 | } 64 | 65 | public ConcurrentHashMap> getSimilarProducts() { 66 | return similarProducts; 67 | } 68 | 69 | public void addProduct(Product product){ 70 | products.add(product); 71 | updateProductSellerMap(product); 72 | updateCategoryProductMap(product); 73 | updateSimilarProductsMap(product); 74 | 75 | } 76 | 77 | @Override 78 | public String toString() { 79 | return "ProductsCatalog{" + 80 | "products=" + products + 81 | '}'; 82 | } 83 | 84 | @Override 85 | public ArrayList searchProduct(String productName) { 86 | return similarProducts.get(productName.toLowerCase()); 87 | } 88 | 89 | @Override 90 | public ArrayList searchCategory(String categoryName) { 91 | return categoryProductMap.get(categoryName.toLowerCase()); 92 | } 93 | 94 | public void updateProductQuantity(Product product, int newQuantity) { 95 | for(Product prod: products){ 96 | if(prod.getId()==product.getId()){ 97 | prod.setAvailableCount(newQuantity); 98 | } 99 | } 100 | } 101 | 102 | public void removeProduct(Product product) { 103 | products.remove(product); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/Searchable.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | 4 | public interface Searchable { 5 | public ArrayList searchProduct(String productName); 6 | public ArrayList searchCategory(String categoryName); 7 | } 8 | 9 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/Seller.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | 4 | public class Seller extends User{ 5 | private ArrayList products; 6 | 7 | public Seller(String name, String phone) { 8 | super(name, phone); 9 | products= new ArrayList<>(); 10 | } 11 | 12 | public void registerProduct(ProductsCatalog productsCatalog,Product product){ 13 | product.setSeller(this); 14 | productsCatalog.addProduct(product); 15 | products.add(product); 16 | 17 | } 18 | public void updateProductQuantity(ProductsCatalog productsCatalog,Product product, int newQuantity){ 19 | productsCatalog.updateProductQuantity(product,newQuantity); 20 | } 21 | public void removeProduct(ProductsCatalog productsCatalog, Product product){ 22 | productsCatalog.removeProduct(product); 23 | products.remove(product); 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | return "Seller{}"+ super.toString(); 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/Shipment.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Set; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | public class ProductsCatalog implements Searchable{ 9 | private ArrayList products; 10 | private ArrayList categories; 11 | private HashMap> categoryProductMap; 12 | private HashMap> productSellerMap; 13 | private ConcurrentHashMap> similarProducts; 14 | 15 | public ProductsCatalog(){ 16 | products = new ArrayList<>(); 17 | categories = new ArrayList<>(); 18 | categoryProductMap = new HashMap<>(); 19 | similarProducts = new ConcurrentHashMap<>(); 20 | similarProducts.put("Dummy Product",new ArrayList()); 21 | productSellerMap = new HashMap<>(); 22 | } 23 | 24 | public void updateSimilarProductsMap(Product newProduct){ 25 | String productName = newProduct.getName().toLowerCase(); 26 | Set keySet = similarProducts.keySet(); 27 | boolean isSimilar = false; 28 | for (String key : keySet){ 29 | if(key.toLowerCase().contains(productName) || productName.contains(key.toLowerCase())) { 30 | isSimilar = true; 31 | similarProducts.get(key).add(newProduct); 32 | } 33 | } 34 | if(!isSimilar){ 35 | similarProducts.put(newProduct.getName().toLowerCase(),new ArrayList(List.of(newProduct))); 36 | } 37 | } 38 | private void updateCategoryProductMap(){ 39 | for(Category category : categories){ 40 | categoryProductMap.put(category.getName().toLowerCase(), new ArrayList()); 41 | } 42 | } 43 | private void updateCategoryProductMap(Product product){ 44 | if(categoryProductMap.containsKey(product.getCategory().getName().toLowerCase())){ 45 | categoryProductMap.get(product.getCategory().getName().toLowerCase()).add(product); 46 | } else{ 47 | categoryProductMap.put(product.getCategory().getName().toLowerCase(),new ArrayList<>(List.of(product))); 48 | } 49 | 50 | } 51 | private void updateProductSellerMap(Product newProduct){ 52 | if(productSellerMap.containsKey(newProduct.getName().toLowerCase())){ 53 | productSellerMap.get(newProduct.getName().toLowerCase()).add(newProduct.getSeller()); 54 | }else{ 55 | productSellerMap.put(newProduct.getName().toLowerCase(),new ArrayList<>(List.of(newProduct.getSeller()))); 56 | } 57 | } 58 | 59 | public void addCategory(Category newCategory){ 60 | categories.add(newCategory); 61 | updateCategoryProductMap(); 62 | 63 | } 64 | 65 | public ConcurrentHashMap> getSimilarProducts() { 66 | return similarProducts; 67 | } 68 | 69 | public void addProduct(Product product){ 70 | products.add(product); 71 | updateProductSellerMap(product); 72 | updateCategoryProductMap(product); 73 | updateSimilarProductsMap(product); 74 | 75 | } 76 | 77 | @Override 78 | public String toString() { 79 | return "ProductsCatalog{" + 80 | "products=" + products + 81 | '}'; 82 | } 83 | 84 | @Override 85 | public ArrayList searchProduct(String productName) { 86 | return similarProducts.get(productName.toLowerCase()); 87 | } 88 | 89 | @Override 90 | public ArrayList searchCategory(String categoryName) { 91 | return categoryProductMap.get(categoryName.toLowerCase()); 92 | } 93 | 94 | public void updateProductQuantity(Product product, int newQuantity) { 95 | for(Product prod: products){ 96 | if(prod.getId()==product.getId()){ 97 | prod.setAvailableCount(newQuantity); 98 | } 99 | } 100 | } 101 | 102 | public void removeProduct(Product product) { 103 | products.remove(product); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /Low-level design code/Ecommerce Platform/User.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | 4 | public abstract class User { 5 | private int id; 6 | private String name; 7 | private String Address; 8 | private String username; 9 | private String password; 10 | private String phone; 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public String getAddress() { 17 | return Address; 18 | } 19 | 20 | public String getPhone() { 21 | return phone; 22 | } 23 | 24 | public User(String name, String phone) { 25 | this.name = name; 26 | this.phone = phone; 27 | } 28 | 29 | @Override 30 | public String toString() { 31 | return "User{" + 32 | "name='" + name + ''' + 33 | ", phone='" + phone + ''' + 34 | '}'; 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/BookMyShow.java: -------------------------------------------------------------------------------- 1 | 2 | import java.text.ParseException; 3 | import java.text.SimpleDateFormat; 4 | import java.util.ArrayList; 5 | import java.util.Date; 6 | import java.util.HashMap; 7 | 8 | public class BookMyShow { 9 | ArrayList theaters; 10 | static HashMap> movieMap; 11 | 12 | private void generateMovieMap(){ 13 | for (Theater theater :theaters) { 14 | ArrayList showArray = theater.getShows(); 15 | for(Show show : showArray) { 16 | if (show != null) { 17 | if (movieMap.containsKey(show.getMovie().getName())) { 18 | movieMap.get(show.getMovie().getName()).add(show); 19 | } else { 20 | ArrayList movieShowList = new ArrayList<>(); 21 | movieShowList.add(show); 22 | movieMap.put(show.getMovie().getName(), movieShowList); 23 | } 24 | } 25 | } 26 | } 27 | } 28 | public BookMyShow(ArrayList theaters) { 29 | this.theaters = theaters; 30 | this.movieMap = new HashMap<>(); 31 | generateMovieMap(); 32 | System.out.println(movieMap); 33 | } 34 | public static ArrayList searchShows(String movieName){ 35 | if (movieMap.containsKey(movieName)){ 36 | return movieMap.get(movieName); 37 | } 38 | else 39 | return null; 40 | } 41 | 42 | public static void main(String[] args) { 43 | /* --------Data generation code ----START ----------------- */ 44 | 45 | // Creating Guest User --> Piyush 46 | GuestUser piyush = new GuestUser("Piyush"); 47 | 48 | // Creating Registered User --> Ayush 49 | RegisteredUser ayush = new RegisteredUser("Ayush"); 50 | 51 | // Creating Registered User --> Saurabh 52 | RegisteredUser saurabh = new RegisteredUser("Saurabh"); 53 | 54 | // Creating Movie object --> Iron Man 55 | Movie ironMan = new Movie("Iron Man", Language.ENGLISH,Genre.ACTION); 56 | 57 | // Creating Movie object --> Avengers: End Game 58 | Movie avengers = new Movie("Avengers: End Game", Language.ENGLISH,Genre.ACTION); 59 | 60 | // Creating Movie object --> The Walk To Remember 61 | Movie walkToRemember = new Movie("The Walk To Remember", Language.ENGLISH,Genre.ROMANCE); 62 | 63 | // Creating Movie object --> HouseFull2 64 | Movie housefull = new Movie("HouseFull 2", Language.HINDI,Genre.COMEDY); 65 | 66 | // Creating Theater --> PVR @ GIP Noida with capacity 30 67 | Theater pvr_gip = new Theater("PVR","GIP Noida",30); 68 | 69 | // Creating Another Theater --> BIG Cinema @ Noida Sector 137 with capacity 40 70 | Theater big_cinema = new Theater("Big Cinema","Sector 137 Noida",40); 71 | 72 | 73 | 74 | 75 | // Creating four shows for movies 76 | Show show1=null, show2=null, show3=null, show4=null; 77 | SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a"); 78 | 79 | try { 80 | // Creating Show for Movie Iron Man on 7 Jun 2020 @ 9:00 AM in PVR 81 | String dateInString = "Friday, Jun 7, 2020 09:00:00 AM"; 82 | Date date = formatter.parse(dateInString); 83 | show1 = new Show(date,ironMan,pvr_gip); 84 | 85 | // Creating Show for Movie HOUSEFULL on 7 Jun 2020 @ 12:00 PM in PVR 86 | dateInString = "Friday, Jun 7, 2020 12:00:00 PM"; 87 | date = formatter.parse(dateInString); 88 | show2 = new Show(date,housefull,pvr_gip); 89 | 90 | // Creating Show for Movie WALK TO REMEMBER on 7 Jun 2020 @ 09:00 AM in BIG-CINEMA 91 | dateInString = "Friday, Jun 7, 2020 09:00:00 AM"; 92 | date = formatter.parse(dateInString); 93 | show3 = new Show(date,walkToRemember,big_cinema); 94 | 95 | // Creating Show for Movie WALK TO REMEMBER on 7 Jun 2020 @ 12:00 PM in BIG-CINEMA 96 | dateInString = "Friday, Jun 7, 2020 12:00:00 PM"; 97 | date = formatter.parse(dateInString); 98 | show4 = new Show(date,walkToRemember,big_cinema); 99 | 100 | } catch (ParseException e) { 101 | e.printStackTrace(); 102 | } 103 | 104 | /* --------Data generation code ---- END ----------------- */ 105 | 106 | // Now We have two theaters with their shows, lets add these theaters to our Book My Show app 107 | ArrayList theaterArrayList= new ArrayList<>(); 108 | theaterArrayList.add(pvr_gip); 109 | theaterArrayList.add(big_cinema); 110 | BookMyShow bookMyShow = new BookMyShow(theaterArrayList); 111 | 112 | // Searching Book My Show for all the shows of movie WALK TO REMEMBER 113 | ArrayList searchedShow = BookMyShow.searchShows("The Walk To Remember"); 114 | // Above code returns two shows of WALK TO REMEMBER 115 | /* 116 | searchedShow --> [Show{id=3, showTime=Sun Jun 07 09:00:00 IST 2020, 117 | movie=The Walk To Remember, theater=Big Cinema, availableSeats=40}, 118 | Show{id=4, showTime=Sun Jun 07 12:00:00 IST 2020, movie=The Walk To Remember, 119 | theater=Big Cinema, availableSeats=40}] 120 | */ 121 | // Now suppose AYUSH and SAURABH both wants to book 10 tickets each for first show 122 | // Then Book My show will create two Ticket Booking threads for their requests 123 | 124 | Show bookingShow = searchedShow.get(0); 125 | 126 | // Ticket Booking Thread for the request made by AYUSH for 10 Seats 127 | TicketBookingThread t1 = new TicketBookingThread(bookingShow,ayush,10); 128 | 129 | // Ticket Booking Thread for the request made by SAURABH for 10 Seats 130 | TicketBookingThread t2 = new TicketBookingThread(bookingShow,saurabh,10); 131 | 132 | // Start both the Ticket Booking Threads for execution 133 | t1.start(); 134 | t2.start(); 135 | 136 | // Waiting till both the thread completes the execution 137 | try { 138 | t1.join(); 139 | t2.join(); 140 | 141 | } catch (InterruptedException e) { 142 | e.printStackTrace(); 143 | } 144 | 145 | // After execution t1 will carry AYUSH ticket and t2 will carry SAURABH ticket 146 | Ticket ayush_ticket = t1.getTicket(); 147 | Ticket saurabh_ticket = t2.getTicket(); 148 | 149 | // Printing their tickets 150 | System.out.println(t1.getTicket()); 151 | System.out.println(t2.getTicket()); 152 | 153 | // Now, 20 seats are booked for this show and 20 seats are available, 154 | // Suppose AYUSH wants another 15 seats and SAURABH wants another 10 seats to be booked 155 | 156 | // Ticket Booking Thread for the request made by AYUSH for another 15 Seats 157 | TicketBookingThread t3 = new TicketBookingThread(bookingShow,ayush,15); 158 | 159 | // Ticket Booking Thread for the request made by SAURABH for another 10 Seats 160 | TicketBookingThread t4 = new TicketBookingThread(bookingShow,saurabh,10); 161 | 162 | // Start both the Ticket Booking Threads for execution 163 | t3.start(); 164 | t4.start(); 165 | 166 | // Waiting till both the thread completes the execution 167 | try { 168 | 169 | t4.join(); 170 | t3.join(); 171 | 172 | } catch (InterruptedException e) { 173 | e.printStackTrace(); 174 | } 175 | 176 | // After execution t3 will carry AYUSH ticket and t4 will carry SAURABH ticket 177 | Ticket ayushNewTicket = t3.getTicket(); 178 | Ticket saurabhNewTicket = t4.getTicket(); 179 | 180 | System.out.println(ayushNewTicket); 181 | System.out.println(saurabhNewTicket); 182 | 183 | /* Running this program several times, we will notice that 184 | if t3 enters the bookTicket function first, 185 | then ticket is allocated to Ayush, 186 | otherwise ticket is allocated to Saurabh. 187 | */ 188 | 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/Genre.java: -------------------------------------------------------------------------------- 1 | public enum Genre { 2 | ACTION, ROMANCE, COMEDY, HORROR; 3 | } 4 | -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/GuestUser.java: -------------------------------------------------------------------------------- 1 | 2 | public class GuestUser extends User { 3 | public GuestUser(String name) { 4 | super(name); 5 | } 6 | 7 | public void register(String username, String password){ 8 | 9 | } 10 | } -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/Language.java: -------------------------------------------------------------------------------- 1 | 2 | public enum Language { 3 | HINDI, ENGLISH; 4 | } -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/Movie.java: -------------------------------------------------------------------------------- 1 | 2 | public class Movie { 3 | private String name; 4 | private float ratings = 0.0f; 5 | private Language language; 6 | private Genre genre; 7 | 8 | public Movie(String name, Language language, Genre genre) { 9 | this.name = name; 10 | this.language = language; 11 | this.genre = genre; 12 | } 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public float getRatings() { 19 | return ratings; 20 | } 21 | 22 | public Language getLanguage() { 23 | return language; 24 | } 25 | 26 | public Genre getGenre() { 27 | return genre; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/RegisteredUser.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | 4 | public class RegisteredUser extends User { 5 | public ArrayList bookingHistory; 6 | 7 | public RegisteredUser(String name) { 8 | super(name); 9 | this.bookingHistory = new ArrayList<>(); 10 | } 11 | public void cancelTicket(Ticket ticket){ 12 | 13 | } 14 | } -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/Show.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Date; 3 | 4 | public class Show { 5 | private static int idCounter=0; 6 | private int id; 7 | private Date showTime; 8 | private Movie movie; 9 | private Theater theater; 10 | private int availableSeats; 11 | 12 | public Show(Date showTime, Movie movie, Theater theater) { 13 | idCounter += 1; 14 | this.id = idCounter; 15 | this.showTime = showTime; 16 | this.movie = movie; 17 | this.theater = theater; 18 | this.availableSeats = theater.getCapacity(); 19 | theater.getShows().add(this); 20 | } 21 | 22 | public Movie getMovie() { 23 | return movie; 24 | } 25 | public void setTheater(Theater theater) { 26 | this.theater = theater; 27 | } 28 | public void setAvailableSeats(int availableSeats) { 29 | this.availableSeats = availableSeats; 30 | } 31 | public int getAvailableSeats() { 32 | return availableSeats; 33 | } 34 | public void updateShow(){ 35 | } 36 | public synchronized Ticket bookTicket(RegisteredUser user, int seats){ 37 | if(availableSeats >= seats && seats >0){ 38 | Ticket ticket = new Ticket(); 39 | availableSeats -= seats; 40 | ticket.setOwner(user.getName()); 41 | ticket.setBookedShow(this); 42 | ticket.setBookingTime(new Date()); 43 | ticket.setNumberOfSeats(seats); 44 | System.out.println("Successfully booked"); 45 | user.bookingHistory.add(ticket); 46 | return ticket; 47 | } 48 | else{ 49 | System.out.println("Seats not Available"); 50 | return null; 51 | } 52 | } 53 | @Override 54 | public String toString() { 55 | return "Show{" + 56 | "id=" + id + 57 | ", showTime=" + showTime + 58 | ", movie=" + movie.getName() + 59 | ", theater=" + theater.getName() + 60 | ", availableSeats=" + availableSeats + 61 | '}'; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/Theater.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | 4 | public class Theater { 5 | private static int idCounter=0; 6 | private int id; 7 | private String name; 8 | private String location; 9 | private int capacity; 10 | private ArrayList shows; 11 | 12 | public Theater(String name, String location, int capacity) { 13 | idCounter += 1; 14 | this.id = idCounter; 15 | this.name = name; 16 | this.location = location; 17 | this.capacity = capacity; 18 | this.shows = new ArrayList<>(); 19 | } 20 | 21 | public void updateShow(Show oldShow, Show newShow){ 22 | 23 | } 24 | public ArrayList getShows(){ 25 | return shows; 26 | } 27 | 28 | public String getName() { 29 | return name; 30 | } 31 | 32 | public int getCapacity() { 33 | return capacity; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/Ticket.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Date; 3 | 4 | public class Ticket { 5 | private static int idCounter=0; 6 | private int id; 7 | private String owner; 8 | private Date bookingTime; 9 | private int numberOfSeats; 10 | private Show bookedShow; 11 | 12 | public Ticket() { 13 | idCounter += 1; 14 | this.id = idCounter; 15 | } 16 | 17 | public String getTicketInfo(){ 18 | return null; 19 | } 20 | public int cancelTicket(){ 21 | return 0; 22 | } 23 | 24 | public String getOwner() { 25 | return owner; 26 | } 27 | 28 | public void setOwner(String owner) { 29 | this.owner = owner; 30 | } 31 | 32 | public int getId() { 33 | return id; 34 | } 35 | 36 | public void setId(int id) { 37 | this.id = id; 38 | } 39 | 40 | public Date getBookingTime() { 41 | return bookingTime; 42 | } 43 | 44 | public void setBookingTime(Date bookingTime) { 45 | this.bookingTime = bookingTime; 46 | } 47 | 48 | public int getNumberOfSeats() { 49 | return numberOfSeats; 50 | } 51 | 52 | public void setNumberOfSeats(int numberOfSeats) { 53 | this.numberOfSeats = numberOfSeats; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "Ticket{" + 59 | "owner='" + owner + ''' + 60 | ", bookingTime=" + bookingTime + 61 | ", numberOfSeats=" + numberOfSeats + 62 | ", bookedShow=" + bookedShow + 63 | '}'; 64 | } 65 | 66 | public Show getBookedShow() { 67 | return bookedShow; 68 | } 69 | 70 | public void setBookedShow(Show bookedShow) { 71 | this.bookedShow = bookedShow; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/TicketBookingThread.java: -------------------------------------------------------------------------------- 1 | public class TicketBookingThread extends Thread { 2 | private Show show; 3 | private RegisteredUser user; 4 | private int numberOfSeats; 5 | private Ticket ticket; 6 | 7 | public TicketBookingThread(Show show, RegisteredUser user, int numberOfSeats) { 8 | this.show = show; 9 | this.user = user; 10 | this.numberOfSeats = numberOfSeats; 11 | } 12 | 13 | @Override 14 | public void run() { 15 | this.ticket = show.bookTicket(user,numberOfSeats); 16 | } 17 | 18 | public Ticket getTicket() { 19 | return ticket; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Low-level design code/Online Movie Ticket Booking System/User.java: -------------------------------------------------------------------------------- 1 | 2 | public abstract class User { 3 | private static int idCounter=0; 4 | private int id; 5 | private String name; 6 | 7 | public User(String name) { 8 | idCounter += 1; 9 | this.id = idCounter; 10 | this.name = name; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | } -------------------------------------------------------------------------------- /Low-level design code/Parking Lot/Admin.java: -------------------------------------------------------------------------------- 1 | 2 | public class Admin { 3 | String name; 4 | 5 | } 6 | -------------------------------------------------------------------------------- /Low-level design code/Parking Lot/AutomatedSystem.java: -------------------------------------------------------------------------------- 1 | 2 | import java.sql.Time; 3 | import java.time.Duration; 4 | import java.time.LocalDateTime; 5 | import java.util.HashMap; 6 | 7 | public class AutomatedSystem { 8 | private int id; 9 | 10 | 11 | 12 | private ParkingLot parkingLot; 13 | HashMap currentTickets; 14 | 15 | public AutomatedSystem(int id){ 16 | this.id = id; 17 | currentTickets = new HashMap<>(); 18 | } 19 | 20 | public ParkingLot getParkingLot() { 21 | return parkingLot; 22 | } 23 | 24 | public void setParkingLot(ParkingLot parkingLot) { 25 | this.parkingLot = parkingLot; 26 | } 27 | private ParkingSpot fetchAvailableSpot(){ 28 | return this.parkingLot.getAvailableSpot(); 29 | } 30 | 31 | public Ticket generateTicket(Customer customer){ 32 | ParkingSpot availableSpot = fetchAvailableSpot(); 33 | Vehicle vehicle = customer.getVehicle(); 34 | Ticket ticket = new Ticket(vehicle,availableSpot); 35 | currentTickets.put(ticket.getId(),ticket); 36 | return ticket; 37 | } 38 | public Ticket scanTicket(){ 39 | // Code for scanning the ticket and return ticketId 40 | // Here we are assuming that scanned ticket id is 1234 41 | return currentTickets.get(1234); 42 | } 43 | 44 | public double caluclateCharges(){ 45 | Ticket ticket= scanTicket(); 46 | long duration = Duration.between(LocalDateTime.now(),ticket.getArrivalTime()).toHours(); 47 | double charges = duration * parkingLot.getParkingCharges(); 48 | return charges; 49 | } 50 | 51 | public void openEntryBarrier(){ 52 | // Code for opening Entry Barrier 53 | this.parkingLot.getDisplayBoard().update(Status.FULL); 54 | } 55 | public void closeEntryBarrier(){ 56 | // Code for closing Entry Barrier 57 | } 58 | public void openExitBarrier(){ 59 | // Code for opening Entry Barrier 60 | this.parkingLot.getDisplayBoard().update(Status.AVAILABLE); 61 | } 62 | public void closeExitBarrier(){ 63 | // Code for closing Entry Barrier 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /Low-level design code/Parking Lot/Customer.java: -------------------------------------------------------------------------------- 1 | 2 | public class Customer { 3 | private String name; 4 | private Vehicle vehicle; 5 | 6 | public Customer(String name, String vehicleNumber) { 7 | this.name = name; 8 | this.vehicle = new Vehicle(vehicleNumber); 9 | } 10 | 11 | public Vehicle getVehicle() { 12 | return vehicle; 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /Low-level design code/Parking Lot/DisplayBoard.java: -------------------------------------------------------------------------------- 1 | 2 | public class ParkingSpot { 3 | String spotNumber; 4 | 5 | public ParkingSpot(String spotNumber) { 6 | this.spotNumber = spotNumber; 7 | } 8 | 9 | public String getSpotNumber() { 10 | return spotNumber; 11 | } 12 | } 13 | 14 | -------------------------------------------------------------------------------- /Low-level design code/Parking Lot/ParkingLot.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | 4 | public class ParkingLot { 5 | private String name; 6 | private int capacity; 7 | private String Location; 8 | 9 | public double getParkingCharges() { 10 | return parkingCharges; 11 | } 12 | 13 | private double parkingCharges; 14 | 15 | 16 | 17 | private Admin admin; 18 | 19 | private AutomatedSystem automatedSystem; 20 | private ArrayList parkingSpots; 21 | private ArrayList availableSpots; 22 | private DisplayBoard displayBoard; 23 | 24 | 25 | 26 | public ParkingLot(String name, int capacity, String location, double parkingCharges, AutomatedSystem automatedSystem, DisplayBoard displayBoard) { 27 | this.name = name; 28 | this.capacity = capacity; 29 | Location = location; 30 | this.parkingCharges = parkingCharges; 31 | this.automatedSystem = automatedSystem; 32 | this.automatedSystem.setParkingLot(this); 33 | this.displayBoard = displayBoard; 34 | this.parkingSpots = createParkingSpots(capacity); 35 | availableSpots = (ArrayList) parkingSpots.clone(); 36 | } 37 | private ArrayList createParkingSpots(int capacity){ 38 | ArrayList tempList = new ArrayList<>(); 39 | for (int i = 0; i 34 | 35 | ## Functional Decomposition: 36 | * A technique where we break down the existing system into smaller different modular services. 37 | * We decompose the whole application based on the functional areas. 38 | 39 |
40 | 41 | ## Scale Cube: 42 | * x-direction: Horizontal Scaling (Adding more instances of similar services). 43 | * y-direction: Functional decomposition (Keep decomposing the service to certain degree). 44 | * z-direction: Data partitioning (Processing part of the data by a service instance). 45 | 46 |
47 | 48 | ## API Gateway: 49 | * There are three patterns to access data from Microservices: 50 | 1. Direct Call: Client makes direct API calls to all of the microservices and gets the information needed to render the page. 51 | * Problems: 52 | * Too many request , Complex JS/Android code to handle 53 | * Protocol difference of micro services 54 | * Tigthly coupled client and services 55 | * Performance issues 56 | * Scalability issues 57 | 3. API Gateway 58 | 4. BFF 59 | * An API Gateway is a server that is the single entry point into the system. 60 | * The API Gateway is responsible for request routing, composition, and protocol translation. 61 | * All requests from clients first go through the API Gateway. 62 | * It then routes requests to the appropriate microservice. 63 | * The API Gateway will often handle a request by invoking multiple microservices and aggregating the results. 64 | * It can translate between web protocols such as HTTP and WebSocket and web‑unfriendly protocols that are used internally. 65 | * Advantages: 66 | * Authentication 67 | * SSL Termination 68 | * Load Balancer 69 | * Insulation 70 | * Disadvantages: 71 | * Increased hops 72 | * Complicated system 73 | * 74 | * API Gateway also helps to implement: 75 | * Caching 76 | * Managing access quotas 77 | * API health monitoring 78 | * API Versioning 79 | * Chaos Monkey Testing 80 | * A/B Testing 81 | * ### BFF (Backend for frontend): 82 | * BFF is essentially a variant of the API Gateway pattern. 83 | * It also provides an additional layer between microservices and clients. 84 | * But rather than a single point of entry, it introduces multiple gateways for each client. 85 | * The BFF is tightly focused on a single UI, and just that UI. That allows it to be focused, and will therefore be smaller. 86 | ![image](https://user-images.githubusercontent.com/55986045/127783144-ddb70d9d-870c-46a0-9a3f-ae1b0654659c.png) 87 | 88 | 89 |
90 | 91 | ## Service Registry/Discovery: 92 | * It is a pattern to identify the network addresses of all of the instances of microservices. 93 | * We use service register for this purpose. 94 | * Service register is more like a separate system/or a database which contains the list of all of the instances of every microservices and its network addresses. 95 | * Ways in which service registry can happen: 96 | 1. Self Registry: (The microservices automatically registers themselves to the register). 97 | 2. Third party Registry: (The registry will ask microservices about their address and updates). 98 | * In discovery we access all of the informations in the registry. 99 | 100 |
101 | 102 | ## Inter microservices communication: 103 | * In a monolithic application, components invoke one another via language‑level method or function calls. 104 | * In contrast, a microservices‑based application is a distributed system running on multiple machines. 105 | * Each service instance is typically a process. 106 | * Consequently, microservices must interact using an inter‑process communication (IPC) mechanism. 107 | * #### Synchronous inter microservice communication: 108 | * A synchronous microservice is one in which data moves to and from an endpoint of a service in a blocking interaction. 109 | * A typical example of a synchronous data exchange is an HTTP request/response interaction. 110 | ![image](https://user-images.githubusercontent.com/55986045/127782429-148ad5ae-792a-4c34-bca2-98dcad59ac3f.png) 111 | 112 | * Advantages: 113 | * Easy to implement 114 | * Easy to handle different use cases 115 | * Realtime 116 | * Disadvantages: 117 | * Service Availability 118 | * Response Time 119 | * #### Asynchronous inter microservice communication: 120 | * An asynchronous microservice is one in which a request to a service and the subsequent response occur independently from each other. 121 | * The general practice is to use a message broker technology, such as Kafka or RabbitMQ, to act as a go-between for services. 122 | ![image](https://user-images.githubusercontent.com/55986045/127782447-3a44e53c-1adf-4d15-9e1e-44f926550dc8.png) 123 | 124 | * Advantages: 125 | * Faster APIs 126 | * Decoupled Services 127 | * Works even when services are down 128 | * Disadvantages: 129 | * Complex design 130 | * Process latency 131 | * Monitoring costs 132 | 133 |
134 | 135 | ## Circuit Breaking: 136 | * A design pattern which is used when there are services that are interacting with other services. 137 | * To protect our microservices from an excess of requests, it’s better to interrupt communication between the front-end and the back-end as soon as a recurring fault has been detected in the back-end. 138 | * Pattern: 139 | * If a call from one microservice to other microservices fails, increment the number of failed calls by one. 140 | * If the number of failed calls goes above a certain threshold, open the circuit. 141 | * If the circuit is open, return with an error or a default response or cached response. 142 | * If the circuit is open and some wait timeout has passed, half-open the circuit.. 143 | * If the circuit is half-open and the next call fails, open it again. 144 | * If the circuit is half-open and the next call succeeds, close it. 145 | * Closed state: 146 | * This state implies that the service is up and running(properly). 147 | * Then if the number of error responses from the needed service passes a threshold limit, the circuit breaker will be tripped (ie: goes to the open stage). 148 | * Open state: 149 | * In the open state, the circuit breaker will trigger the fallback method. 150 | * A fallback method will handle the case if the needed service is down. 151 | * After a considerable time, the circuit breaker will go to half-open state. 152 | * Half open state: 153 | * The circuit breaker makes a remote call to the service. 154 | * If the request fails, the circuit breaker will go to the open stage. 155 | * If the service gives the proper response, the circuit breaker will go to the closed stage. 156 | * This state takes place after spending some time in the closed stage. 157 | 158 | ![image](https://user-images.githubusercontent.com/55986045/127782969-736548da-a319-4d6d-9846-3ef31503b7e6.png) 159 | 160 | * Features: 161 | * Cached response 162 | * Fallback mechanism 163 | * Recover 164 | 165 |
166 | 167 | ## Service Mesh: 168 | * Problems faced in inter microservices communication: 169 | * Load Balance 170 | * Service discovery 171 | * Metrics 172 | * Retries 173 | * Circuit Breaking 174 | * Timeout 175 | * Service mesh: A component which runs along with every microservice deployment and helps to do all of the above problems. 176 | * It is a sidecar pattern. 177 | * For every microservice instance, there will be an instance of service mess which is running in that container. 178 | * It also implements proxy design pattern. 179 | * In service mesh, there are two major components: 180 | 1. Control Plane 181 | * The centralized hub or a single hub which acts like a control panel from which we can configure configurations for all of the proxies which are side loaded whith every microservice running in every instance. 182 | 2. Data Plane 183 | * It is comprised of proxies and all of the requests goes through these proxies. 184 | 185 |
186 | 187 | ## Deployment Strategies: 188 | * Deployment goals: 189 | 1. Scalability and throughput 190 | 2. Reliable and available 191 | 3. Isolation 192 | 4. Resource limit 193 | 5. Monitor 194 | 6. Cost effective 195 | * Patterns: 196 | 1. Multiple Servers Per Host: 197 | * Advantages: 198 | * Efficient resource utilization 199 | * Fast deployment 200 | * Disadvantages: 201 | * Poor isolation 202 | * No resource limit 203 | * Dependency conflict 204 | 2. Service per VM/container: 205 | * Advantages: 206 | * Isolation and secure 207 | * Manageable 208 | * Fast(containers only) 209 | * Autoscaling 210 | * Disadvantages: 211 | * Slow (VM only) 212 | * Not efficient (VM only) 213 | * Not so secure (containers) 214 | 3. Serverless: 215 | * Advantages: 216 | * Focus on code 217 | * Pay as you go 218 | * No scaling worries 219 | * Disadvantages: 220 | * Runtime support 221 | * Expensive 222 | * Vendor lock 223 | * Debugging pain 224 | * Stateless and short running process only 225 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # System Design: 2 | 3 | ## Introduction: 4 | 5 | ### What is system? 6 | * A system is a loosely used term for an architecture or collection of software or technology that communicate with each other or interact with each other in order to serve a certain set of users with a certain set of requirements. 7 | * A system can be defined and built keeping these three factors in mind: 8 | 1. The user of the systems 9 | 2. The requirements of those users, and 10 | 3. The components that are chosen in order to build that system to serve those users and their requirements. 11 | 12 | ### What is design? 13 | * Design is a process of understanding the user requirements and selecting the components, modules, and software technologies how they are going to be intertwined and communicating with each other to actually serve the need of the system. 14 | 15 | `In order to understand and develop this skill of designing certain kind of systems which serve to larger scale and larger users the process of system design comes into the picture.` 16 | 17 |
18 | 19 | ## Components of System Design: 20 | * Components are the basic building blocks of system components. 21 | * It could be divided into two parts: 22 | 1. Logical entities: 23 | * Data 24 | * Databases 25 | * Applications 26 | * Cache 27 | * Message Queues 28 | * Infra 29 | * Communication Protocol 30 | * Requests (API, RPC, etc.) 31 | 2. Tangible entities: 32 | * Text, images, videos.. 33 | * MongoDB, MySQL, Cassandra.. 34 | * Java, Golang, Python, React.. 35 | * Redis, MemeCache.. 36 | * Kafka, RabbitMQ.. 37 | * AWS, GCP, Azure.. 38 | * APIs, RPCs, Messages.. 39 | 40 |
41 | 42 | 43 | ## Client Server Architecture: 44 | * Client-server architecture is a computing model in which the server hosts, delivers and manages most ofthe resources and services to be consumed by the client. 45 | * Client: a piece ofsoftware or application that takes the input and sends request to the servers. 46 | * Server: a piece ofsoftware that receives and processes requestsfrom clients. 47 | * Load balancer: responsible for distributing incoming network traffic across a group of backend servers to optimize resource usage. 48 | * #### A typical topological data flow goes as follows: 49 | 1. Client requests data from server 50 | 2. Load balancer routes the request to the appropriate server 51 | 3. Server processes the request client 52 | 4. Server queries appropriate database for some data 53 | 5. Database returns the queried data back to the server 54 | 6. The server processes the data and sends the data back to the client 55 | 7. This process repeats 56 | * #### Types of Architecture: 57 | * Thin client: 58 | * A thin client is designed to be especially small so that the bulk of the data processing occurs on the server. 59 | * Example: Ecommerce, streaming applications. 60 | * Thick client: 61 | * A thick client (fat client) is one that will perform the bulk of the processing in client/server applications. With thick clients, there is no need for continuous server communications as it is mainly communicating archival storage information to the server. 62 | * Example: Gaming apps, video editing software. 63 | * #### Tier based architecture: 64 | * 1-Tier: 65 | * It is the simplest one as it is equivalent to running the application on the personal computer. 66 | * 2-Tier: 67 | * It is like Client-Server architecture, where communication takes place between client and server. 68 | * 3-Tier: 69 | * The 3-tier architecture has three different layers. 70 | * Presentation layer 71 | * Business Logic layer 72 | * Database layer 73 | * N-Tier: 74 | * An N-Tier Application program is one that is distributed among three or more separate computers in a distributed network. 75 | 76 |
77 | 78 | ## Proxies: 79 | * Proxy is an intermediary server between client and the internet. 80 | * Proxy servers allow to hide, conceal and make your network id anonymous by hiding your IP address. 81 | * Proxy servers offers the following basic functionalities: 82 | * Firewall and network data filtering. 83 | * Network connection sharing 84 | * Data caching 85 | * #### Types of proxy: 86 | * Forward Proxy 87 | * In this the client requests its internal network server to forward to the internet. 88 | * Reverse Proxy 89 | * In this the requests are forwarded to one or more proxy servers and the response from the proxy server is retrieved as if it came directly from the original server. 90 | 91 |
92 | 93 | ## Data and Data Flow: 94 | * #### Different formats of data (representation): 95 | * In Business Layer: 96 | * Texts, Videos, Images, etc. 97 | * In Application Layer: 98 | * JSON/XML 99 | * In Data Stores: 100 | * Databases, Tables, Indexes, Cache, Queues, etc. 101 | * Network Layer: 102 | * Packets. 103 | * Hardware Layer: 104 | * 0s and 1s. 105 | * #### Data Generation: 106 | * Users 107 | * Internal Data (System populates on their own). 108 | * Insights 109 | * #### Data Flow Methods: 110 | * APIs. 111 | * Messages. 112 | * Events. 113 | * #### Factors to be considered: 114 | * Type of data 115 | * Volume 116 | * Consumption/Retrieval 117 | * Security 118 | * #### Types of System (Examples): 119 | * Authorization System 120 | * Streaming System 121 | * Transactional System 122 | * Heavy Compute System 123 | 124 |
125 | 126 | ## Databases: 127 | ### Types of databases: 128 | * If we consider data as people, in terms of buildings, then the way those buildings house people can be said as databases. 129 | * Some common types of databases are: 130 | * Relational 131 | * Non-relational 132 | * File type 133 | * Network, etc. 134 | 135 |
136 | 137 | ## Anatomy of applications and services: 138 | * Applications or services performs certain tasks, and at different layers they have different responsibility. 139 | * Tech stack: 140 | * All the codes in applications are written in some languages using some frameworks. 141 | * Any application can be written solely with the use of language. But frameworks do most of the bootstrapping so we can use this feature to make an application on the top of the framework. 142 | * Responsibilities: 143 | * Client app: 144 | * Render UI. 145 | * Handle interactions. 146 | * Collect data. 147 | * Communicate with backend (API) to fetch and store data. 148 | * Render static data/informations. 149 | * Backend app: 150 | * Expose API endpoints. 151 | * House business logics. 152 | * Handle data modelling/transformation. 153 | * Interact with data stores. 154 | * Interact with other services. 155 | * Elements/factors of application development: 156 | * Feature requirements. 157 | * Layer. 158 | * Tech Stack. 159 | * Code structure/design pattern. 160 | * Data store interactions. 161 | * Performance/cost. 162 | * Deployment. 163 | * Monitoring. 164 | * Operational excellence/reliability. 165 | 166 |
167 | 168 | ## Application Programming Interface (API): 169 | * An API is a set of defined rules that explain how computers or applications communicate with one another. 170 | * Advantages: 171 | * Communication. 172 | * Abstraction. 173 | * Platform agnostic. 174 | * Examples: 175 | * Private APIs: The hidden APIs. Not accessible to everyone. 176 | * Public APIs: Available to public. (Ex: Google maps api) 177 | * Web APIs: Superset of public and private APIs. 178 | * SDK/Library APIs 179 | * Factors to consider: 180 | * API contracts 181 | * Documentation 182 | * Data format 183 | * Security 184 | * Standards: 185 | * REST: 186 | * Stands for REpresentational State Transfer. 187 | * Guidelines: 188 | * Client Server. 189 | * Cacheable. 190 | * Layered. 191 | * Stateless. 192 | * Uniform Interface. 193 | * Code on demand. 194 | * RPC 195 | * SOAP 196 | 197 |
198 | 199 | ## Caching: 200 | * A hardware or software component which helps in serving the data which is either frequently requested or it is expensive to compute on, so cache stores the computed response and saves the cost of computing. 201 | * Cache hit: If a response for a request is available in cache memory, it is called a cache hit. 202 | * Cache miss: If a response for a request is not available in cache memory, it is called a cache miss. 203 | * Invalidation and eviction: 204 | * Invalidation: 205 | * The data that is kept in cache is not there for forever, it is volatile. 206 | * The data is going to change at some point of time, hence we need to update the cache as well. 207 | * The process of updating the data in cache by replacing the old value with new value is called data invalidation. 208 | * Methods to invalidate: 209 | * Cache expiry (TTL: Time to live). 210 | * Remove the cache. (When a new request come, cache miss will happen, and data will be fetched.) 211 | * Update the cache. 212 | * Eviction: 213 | * A cache eviction algorithm is a way of deciding which element to evict when the cache is full. 214 | * Catch eviction methods: 215 | * FIFO. 216 | * LRU. 217 | * LFU. 218 | * Cache Patterns: 219 | * Cache-aside strategy/pattern: 220 | * A pattern in which cache never talks to db, only the application code talks to cache. 221 | * Advantages: 222 | * If cache fails, data can still be served. 223 | * Disadvantage: 224 | * To decide the expiry time for data, or write the logic to update the cache whenever data is changed. 225 | * Read through strategy/pattern: 226 | * In this pattern, cache sits between application and db, hence application always talks to cache and never to db. 227 | * Advantage: 228 | * Supports read heavy workloads. 229 | * Disadvantage: 230 | * First request will always be a cache miss. (Solved sometimes by pre heating the cache) 231 | * Write through strategy/pattern: 232 | * It is similar to read through pattern. 233 | * There is an extra layer of latency while writing. (App to cahce then to db). 234 | * Write around strategy/pattern: 235 | * Similar to write through, only difference being app directly writes to db, but for reading it reads from the cache. 236 | * Write back strategy/pattern: 237 | * All the write requested are stored at cache. 238 | * After some time these writes are sent in bulk to the db. 239 | 240 | ![Untitled](https://user-images.githubusercontent.com/55986045/122691774-41049200-d24f-11eb-9c77-4230023b1d51.png) 241 | 242 | * Where can be keep cache? 243 | * Browser level 244 | * Proxy level 245 | * Application level 246 | * Outside Application level 247 | 248 |
249 | 250 | ## MESSAGE QUEUE: 251 | ![image](https://user-images.githubusercontent.com/55986045/122849696-a2009880-d329-11eb-96a8-16a8d578aa20.png) 252 | * Message queue 253 | 254 |
255 | 256 | ## Performance Metrics (used to evaluate how good the system is performing): 257 | * ### Throughput 258 | * Throughput is the number of actions executed or results produced in a certain amount of time. 259 | * In system design, throughput comes into picutre when we need to understand how many API calls are being served in a particular amount of time. 260 | * ### Bandwidth 261 | * Bandwidth is the maximum amount of data that can travel through a 'channel'. 262 | * ### Latency 263 | * Latency is the time required to perform some action or to produce some result. 264 | * ### Response Time 265 | * Response time is the time between a client sending a request and receiving a response. It is the sum of round trip latency and service time. 266 | * ### EXAMPLES (analogies): 267 | * Water Analogy: 268 | * Latency is the amount of time it takes to travel through the tube. 269 | * Bandwidth is how wide the tube is. 270 | * The amount of water flow will be your throughput 271 | * Vehicle Analogy: 272 | * Vehicle travel time from source to destination is latency. 273 | * Types of Roadways are bandwidth. 274 | * Number of Vehicles traveling is throughput. 275 | 276 |
277 | 278 | ## Performance metrics of different components: 279 | * ### Applications: 280 | * API Response Time 281 | * Throughput of APIs 282 | * Error occurences 283 | * Bug/defect in the code 284 | * ### Databases: 285 | * Time taken by various database queries 286 | * Number of queries executed per unit time(or throughput) 287 | * Memory 288 | * ### Caches: 289 | * Latency of writing to cache 290 | * Number of cache eviction and invalidation 291 | * Memory of cache instance 292 | * ### Message Queues: 293 | * Rate of production and consumption 294 | * Fraction of stale or unprocessed messages 295 | * Number of consumers affects bandwidth and throughput 296 | * ### Workers: 297 | * Time taken for job completion 298 | * Resources used in processing 299 | * ### Server instances: 300 | * Memory/RAM 301 | * CPU 302 | 303 |
304 | 305 | ## Fault v/s Failure: 306 | * Fault is the cause, failure is the effect. 307 | 308 |
309 | 310 | ## Scaling: 311 | * The ability to handle more request by buying more machines/bigger machines. 312 | * Key features: 313 | * Able to handle the increased load. 314 | * Not complex to implement and maintain. 315 | * Performance shouldn' takr a hit or rather performance should increase. 316 | * ## Vertical Scaling: 317 | * When we increase the capacity of existing resource it is vertical scaling. 318 | * ## Horizontal Scaling: 319 | * When we increase the number of resources it is horizontal scaling. 320 | * ## Horizontal v/s Vertical Scaling: 321 | | Horizontal | Vertical | 322 | |------------|----------| 323 | |Need load balancers.|Load balancers not needed.| 324 | |Resilient.|Single point of failure.| 325 | |Slow remote procedure calls.|Fast inter process communication.| 326 | |Data inconsistency.|Data consistent.| 327 | |Scales well as uses increases.| Hardware limit.| 328 | 329 |
330 | 331 | ## Database Replication: 332 | * Replication: To have a copy. 333 | * Having exact copy of data present in other databases in other machines. 334 | * The database that has main source of writes/updates becomes the primary db. (Master) 335 | * The database which has the copies from the primary db's is called the secondary database. (Slave) 336 | * Why do we need replication? 337 | * Having replicas helps in tolerating faults. 338 | * Having replicas helps in reducing latency. 339 | * Replica databases can be used for read queries, whereas the primary one can be used for write queries. (Gain application performance) 340 | * Replication lag: 341 | * The time it takes for the value to be copied from the primary to secondary database. 342 | * If replication lag is huge, then it becomes a problem. 343 | * Replicas will give inconsistent data. 344 | * To overcome this there are several consistenct models: 345 | * Synchronous replication: 346 | * All replicas have to be updated before host is acknowledged. 347 | * Advantages: 348 | * No lag. 349 | * Data is always consistent. 350 | * Disadvantage: 351 | * Performance might take a hit, because every write will have to wait for all replicas to get updated as well as acknowledge. (High latency) 352 | * If any replica goes down, and couldn't give any acknowledgement, write will fail. 353 | * Asynchronous replication: 354 | * Host is acknowledged after primary database is updated. Replicas update asynchronously. 355 | * Advantage: 356 | * Write opeartion becomes faster. 357 | * Disadvantage: 358 | * If any replica fails, system will be in a inconsistent state. 359 | * Semi-synchronous replication: 360 | * Whenever a new write is issued, the primary database will update the value to all the replicas, and will wait for one of the replicas to acknowledge. 361 | 362 | ## CAP (Consistency, Availability, and Partitioning) 363 | * ### Consistency: 364 | * In a consistent system, once a client writes a value to any server and gets a response, it expects to get that value (or a fresher value) back from any server it reads from. 365 | * ### Availability: 366 | * In an available system, if the client sends a request to a server and the server has not crashed, then the server must eventually respond to the client. The server is not allowed to ignore the client's requests. 367 | * ### Partitioning: 368 | * The system continues to function and upholds its consistency guarantees in spite of network partitions. 369 | * If we can tolerate the partition, and even though if partition happens and system can still be available and consistent is called partition tolerance. 370 | * ### CAP theorem (Brewer Theorem): 371 | * Any network shared system wants to have these three properties. 372 | * In such a system, having all three properties is nearly impossible. 373 | * We need to sacrifice one of them. 374 | * Partition tolerance happens due to network failures, and we do not have complete control over network failures. 375 | * Hence, partition tolerance becomes a mandatory property to support. 376 | 377 | ## Database Sharding 378 | * 379 | --------------------------------------------------------------------------------