System Design
System Design
System Design............................................................................................................................. 3
Framework.....................................................................................................................................3
4 steps for effective system design interview...........................................................................3
Step 1 - Understand the problem and establish design scope................................................ 3
Step 2 - Propose high-level design and get buy-in.................................................................. 3
System Design Acronyms.......................................................................................................... 4
CAP theorem........................................................................................................................... 4
PACELC Theorem................................................................................................................... 5
BASE....................................................................................................................................... 5
Basically available................................................................................................................... 5
Soft state..................................................................................................................................5
Eventual consistency............................................................................................................... 5
SOLID...................................................................................................................................... 5
ACID........................................................................................................................................ 5
KISS.........................................................................................................................................6
Design pattern..............................................................................................................................7
Creational................................................................................................................................ 8
Builder................................................................................................................................8
Prototype............................................................................................................................8
Abstract Factory.................................................................................................................8
Singleton............................................................................................................................ 8
Factory Method.................................................................................................................. 8
Structural................................................................................................................................. 8
Adapter.............................................................................................................................. 8
Bridge.................................................................................................................................8
Composite..........................................................................................................................8
Decorator........................................................................................................................... 8
Facade............................................................................................................................... 8
Flyheight............................................................................................................................ 8
Proxy..................................................................................................................................8
Behavioral................................................................................................................................8
Chain of responsibility........................................................................................................8
Command.......................................................................................................................... 8
Interpreter.......................................................................................................................... 8
Decorator........................................................................................................................... 9
Mediator............................................................................................................................. 9
Memetor.............................................................................................................................9
Observer............................................................................................................................ 9
State...................................................................................................................................9
Strategy..............................................................................................................................9
Visitor................................................................................................................................. 9
Template Method............................................................................................................... 9
Load Balancing.......................................................................................................................... 10
https://blog.bytebytego.com/p/ep47-common-load-balancing-algorithms..............................11
Cache.................................................................................................................................... 13
Cache tear............................................................................................................................. 13
Content Delivery network CDN.................................................................................................13
Stateless web tier...................................................................................................................... 14
Stateful web tier..................................................................................................................... 14
Message queue.......................................................................................................................... 15
Event Driven.......................................................................................................................... 17
Inventory Management and Concurrency Control................................................................. 18
Logging, metrics, automation.................................................................................................. 20
Scale System..............................................................................................................................21
Scale Database..................................................................................................................... 21
Dependency Injection............................................................................................................ 22
Technologies Theoric................................................................................................................23
Spring......................................................................................................................................... 24
Inversion of Control (IoC) and Dependency Injection (DI):.................................................... 24
"injection types.".................................................................................................................... 25
Java.............................................................................................................................................27
Database System....................................................................................................................... 28
Types of SQL Statements......................................................................................................28
DML................................................................................................................................. 28
DDL........................................................................................................................................29
System Design
Framework
Step 4 - Wrap up
System Design Acronyms
CAP theorem
Trade of between consistency, availability and partition tolerance in distributed systems.
● Consistency: consistency means all clients see the same data at the same time no
matter which node they connect to.
● Availability: availability means any client which requests data gets a response even if
some of the nodes are down.
● Partition Tolerance: a partition indicates a communication break between two nodes.
Partition tolerance means the system continues to operate despite network partitions.
“2 of 3”: CAP theorem states that a distributed system can't provide more than two of these
three guarantees simultaneously.
Example: In a bank system you have 2 ATMs in case of network partition ( one is down) in
Availability guarantee that you can withdraw in both But if your connection you will lose
consistency of data. Each will have an inconsistent balance. In Consistency you will not
provide availability in an unconnected device.
PACELC Theorem
BASE
Basically available
Soft state
Eventual consistency
TODO
SOLID
TODO
ACID
TODO
KISS
TODO
Design pattern
Creational
Builder
Prototype
Abstract Factory
Singleton
Factory Method
Structural
Adapter
Bridge
Composite
Decorator
Facade
Flyheight
Proxy
Behavioral
Chain of responsibility
Command
Interpreter
Decorator
Mediator
Memetor
Observer
State
Strategy
Visitor
Template Method
Load Balancing
Distribute incoming traffic among web servers that are defined in a load balance set.
The servers are unreachable directly by clients anymore.
When choosing tools for load balancing, you should consider the specific requirements of your
application, such as whether you need global or regional load balancing, the type of traffic you
need to manage (HTTP, HTTPS, TCP, UDP), and whether you need additional features like SSL
termination, health checks, or integration with a content delivery network (CDN).
https://blog.bytebytego.com/p/ep47-common-load-balancing-algor
ithms
Static Algorithms
● Round robin
○ The client requests are sent to different service instances in sequential order. The
services are usually required to be stateless.
● Sticky round-robin
○ This is an improvement of the round-robin algorithm. If Alice’s first request goes
to service A, the following requests go to service A as well.
● Weighted round-robin
○ The admin can specify the weight for each service. The ones with a higher weight
handle more requests than others.
● Hash
○ This algorithm applies a hash function on the incoming requests’ IP or URL. The
requests are routed to relevant instances based on the hash function result.
Dynamic Algorithms
● Least connections
○ A new request is sent to the service instance with the least concurrent
connections.
● Least response time
○ A new request is sent to the service instance with the fastest response time.
Cache
Is a temporary storage area that stores the result of expensive responses or frequently
accessed data in memory so that subsequent requests are served more quickly.
Cache tear
Is a temporary storage layer, much faster than the database.
Benefits:
● Better system performance,
● Ability to reduce database workloads,
● Ability to scale the cache tier independently
Examples:
cache.set('mykey', 'content', 3600)
cache.get('mykey')
Discantages:
● Inconsistency: data-modification operations on data store and cache are not in a single
transaction.
● Single cache server can be a potential single point of failure. SPOF.
● Eviction Policy: once the cache is full, any requests to add items might cause existing
item to be removed.
○ Least-recently-used LRU
○ Lest-frequently-used LFU
○ Fist in first out FIFO
Advantages:
● Asynchronous processing, Alow different parts of the system to communicate and
process tasks at their own pace.
● Decoupling: services can operate independently.
● Scalability: easier to scale different parts of the system as demand changes.
● Reliability: provide mechanisms to ensure messages are not lost and can be processed
even in case of temporary failure.
● Load Balance: Efficiency distribution tasks across workers.
● Ordering and consistency:
Disadvantages
● Complexity: add complexity to maintain the system.
● Latency: can introduce latency in the message processing
● Monitoring and management: requires monitoring to ensure smooth operation.
● Dependency and integration: requires integration with existing systems, which can be
challenging.
● Cost: depending on the solution it can add the operational costs.
Kafka
Pros:
● High throughput and scalability.
● Strong durability guarantees.
● Suitable for event streaming and log aggregation.
Cons:
● Complex setup and management.
● Steeper learning curve.
RabbitMQ
Pros:
● Mature, with strong support for various messaging protocols.
● Easier to set up and manage than Kafka.
● Good for lightweight and traditional message queue needs.
Cons:
● Lower throughput compared to Kafka.
● Not ideal for log aggregation or event streaming at a very large scale.
GCP Pub/Sub
Pros:
● Fully managed service, reducing operational overhead.
● Easy integration with other Google Cloud services.
● Good scalability and reliability.
Cons:
● Limited to the Google Cloud Platform ecosystem.
● Potentially higher costs for high-volume usage.
● Less control compared to self-hosted solutions.
Other Options
Amazon SQS: A fully managed queue service in AWS, easy to use but with limited message
size.
Azure Service Bus: Microsoft's solution, integrates well with other Azure services, offering
features like message sessions and dead-letter queues.
ActiveMQ: A reliable and mature open-source message broker with support for multiple
protocols.
Types of Publishers
Event Driven
An event-driven system is a design paradigm where the flow of the program is determined by
events such as user actions, sensor outputs, or messages from other programs. This approach
contrasts with a more traditional, procedural programming model, and it is particularly
well-suited to environments where certain conditions or changes in state dictate the execution of
various functionalities.
Inventory Management and Concurrency Control
● Optimistic Locking: When a customer attempts to purchase an item, the system
checks if the item is available. If yes, the purchase proceeds, and the inventory is
updated. This approach assumes conflicts are rare but checks to ensure data integrity.
It’s best for scenarios where write conflicts are not frequent.
● Pessimistic Locking: Lock the item for a short period when a user adds it to their cart.
This approach is more straightforward but can lead to scalability issues as it locks
resources and might impact user experience.
● Database Transactions: Use database-level transactions to ensure that the inventory
update operations are atomic. This helps in maintaining consistency even in the event of
system failures.
Scale Database
● Partition: We can split a table to gain performance. Example plit
● Denormalization: Join can take too much time and use resources. We can denormalize
our database to gain performance.
● Index
● Vertical Scale
● Horizontal scale
●
Dependency Injection
Big Data
Clean Code
Dependency injection
Java Dependency Injection
Java Spring Core is a fundamental part of the Spring Framework, which is a comprehensive
framework for building Java applications, especially for enterprise-level development. It provides
a wide range of features that simplify Java development and promotes good software design
practices. Here's an overview of its key concepts and internal organization:
"injection types."
Here's a brief overview of each injection type:
Constructor Injection:
● Dependencies are provided through a class constructor.
● This is the recommended way by Spring as it allows you to implement immutable objects
because the dependency cannot be altered after the object has been created.
● It's especially suitable when the dependency is mandatory and the object cannot
function without it.
● You can use the @Autowired annotation on the constructor to auto-wire the
dependencies, although as of Spring 4.3, if the class has only one constructor, it's not
necessary to annotate it with @Autowired.
Setter Injection:
● Dependencies are provided through setter methods in the class.
● This is a more traditional way of dependency injection and can be used for optional
dependencies that can be changed or set later in the bean's lifecycle.
● It also allows for the possibility of reconfiguring the bean by calling the setter method
again.
● Setter injection is specified by using the @Autowired annotation on the setter method.
Field Injection:
● Dependencies are injected directly into the fields of a class.
● This is the least preferred method for several reasons, including the difficulty of unit
testing, the inability to create immutable fields, and the interference with the
encapsulation principle.
● To use field injection, you annotate the field with @Autowired.
Setter Injection: Choose this for optional dependencies that can be altered after the bean has
been constructed. It's also a good choice when there are too many dependencies, leading to a
constructor with a large number of parameters.
Field Injection: While it's convenient for simple applications, it's generally discouraged for the
reasons mentioned above. However, it can still be used in certain scenarios like tests or when
dealing with frameworks that require parameterless constructors.
Java
Test
Smoke Testing
This is done after API development is complete. Simply validate if the APIs are working and
nothing breaks.
Functional Testing
This creates a test plan based on the functional requirements and compares the results with the
expected results.
Integration Testing
This test combines several API calls to perform end-to-end tests. The intra-service
communications and data transmissions are tested.
Regression Testing
This test ensures that bug fixes or new features shouldn’t break the existing behaviors of APIs.
Load Testing
This tests applications’ performance by simulating different loads. Then we can calculate the
capacity of the application.
Stress Testing
We deliberately create high loads to the APIs and test if the APIs are able to function normally.
Security Testing
This tests the APIs against all possible external threats.
UI Testing
This tests the UI interactions with the APIs to make sure the data can be displayed properly.
Fuzz Testing
This injects invalid or unexpected input data into the API and tries to crash the API. In this way,
it identifies the API vulnerabilities.
Database System
Link
● Data Definition Language (DDL) - Defines the structure of the database objects.
● Data Manipulation Language (DML) - Deals with the retrieval and manipulation of the
data stored in tables.
● Transaction Control Language (TCL) - Deals with the transaction within the database.
● Data Control Language (DCL) - Deals with the permissions and privileges of the
objects.
Join
Query
Index
DML
Select
SELECT d.id, d.name FROM Departments d
JOIN Employees e ON d.id = e.id_departement
GROUP BY d.id, d.name
HAVING Count(e.id) >2
Insert
Update
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Delete
DDL
Alter table
/* ADD COLUMN */
ALTER TABLE table_name ADD column_name datatype;
View
/* Using VIEWs */
CREATE VIEW view_name AS
SELECT column1, column2...
FROM table_name
WHERE [condition];
DROP VIEW view_name;
INDEX Constraint
Indexes can be used to speed up data retrieval. An index helps to speed up SELECT queries
and WHERE clauses, but it slows down data input, with the UPDATE and the INSERT
statements.