Understanding Single Points of Failure
Understanding Single Points of Failure
1) Redundancy: Have multiple components in place so that if one node fails, the
others can take over.
2) Load Balancing: Distribute workloads across multiple components to prevent
any one component from becoming overwhelmed.
3) Master-Slave Architecture: Have a backup system in place to ensure that
operations can continue even if a primary system fails. Generally we take
backups of databases.
4) Regular Maintenance: Regular maintenance and testing can help identify and
prevent failures before they occur.
5) Disaster Recovery Planning: Have a plan in place for how to respond to
failures and how to quickly recover operations.
Scaling
Scalability is the measure of the ability of a system to increase or decrease in
performance and cost, in response to changes in application or with increasing load
and traffic on an existing system.
It is of 2 types: -
-Payal
Master-Slave Architecture enables data from one database server (The Master) to
be replicated to one or more other database servers (The Slaves).
There 2 types of data replication techniques:-
1. Synchronous Replication - In a master-slave architecture, the master device is
the sender and the slave device is the receiver. The master sends a request
and waits for a response from the slave before proceeding. The data in
master and slave should always be synchronised.
2. Asynchronous Replication - In a master-slave architecture, the master device
can send requests to the slave device at any time and continue with other
tasks without waiting for a response. The slave device processes the request
and sends a response when it is ready.
Health service is closely tied to the Service Discovery problem. If a user requests a
service, that service is routed by a load balancer rather than by the service itself, and
it keeps the snapshot of all the data in its database or cache. Now the health service
will see a difference in the snapshot in the load balancer and then open’s up a new
connection with them and check their heartbeat..
2) Going Viral - During sales like black Friday events, load can increase on the
servers due to more Number of users logging in at once.
3) Bulk Job Scheduling - During events like New Year or diwali etc. there are
cron jobs like sending email notifications to users. If all the notifications are
sent at once then the load on servers increases.
A server sends a request to the database and the database acknowledges that it has
received the request. This can cause a lot of unnecessary data overhead.
To scale the database we need to reduce unnecessary exchange of data like
acknowledgements and headers and also reduce I/O calls which helps in freeing
resources and reducing response time.
In order to do it we can do the following:-
1. Condense data queries into single query:
● Advantage:
We can take multiple queries and process them in batches so as to
reduce I/O operations (Number of Acknowledgements reduce).
● Disadvantage:
Additional memory is utilised by the server to condense it.
2. Use linked list:
● Advantage:
Linked list has an insertion time of O(1). So using linked lists in the
database can help increase write operations.
● Disadvantage:
Read operations are slow as search time in the linked list takes O(N)
time.
3. Use Sorted array together with linked list:
● Advantage:
Search time becomes O(log N) and insertion time becomes O(1) hence
improving read and write time giving optimal solution.
We need to sort the data before inserting it in the database so the data is sorted first
and then persisted in the database. Data is processed in batches and these batches
are called sorted chunks. We can apply binary search on them to search for the data
required.
Now searching in these chunks will still be slow as we need to apply binary search to
each and every chunk.
So, we use a hybrid approach - Merging the sorted chunks in a sorted manner until
the sort time is reduced. This would help to reduce the number of sorted chunks and
hence improve the search time.
We can also use bloom filters to reduce search time.
Bloom filters - A Bloom filter is a probabilistic data structure used to test whether an
element is a member of a set or not. It offers an efficient way of checking for the
existence of an item in a large set, while using a small amount of memory. The key
idea behind a Bloom filter is to use multiple hash functions to map an element to
several positions, and set those positions to 1.
However, due to the probabilistic nature of Bloom filters, false positives (reporting
an element as being in the set when it is not) can occur.
Food Delivery Algorithm is based on location based algorithm. For searching the
location, we assign codes to each and every location i.e pincodes.
Using pin codes we can assign location to a particular post office.
REQUIREMENTS:
1. Measurable Distance:
● Uniform assignment: Distance can be uniformly assigned (In a
particular order) to each and every location.
● Scalable Granularity: Value of latitude and longitude can be extended
to many decimal places.
2. Proximity: It is used to find the people within a particular range or the people
closer to you.
-Rishabh Singh
System Design
What is system design
It is a process of designing the elements of a system such as architecture, modules
and components.
(Application ko define karne ke process ko system design bolte ha, elements matlab
uska architecture, modules, components , different interface or unke beech data flow
kaise hoga usko system design bolte hai)
It is of two type:
HLD LLD
1. ye main component ko describe karta 1. Jo HLD ke under hume
hai jisko hume développe karna hai apne elements/components likhe hai unke actual
resulting product ke liye design ko describe karne ke process ko
bolenge LLD
2. Esme system architecture details, data 2. Isme actual classes, interfaces kya likhne
base design(matlab cons use karenge), hoge or unke under kya business logic likhna
services , processes and in sab ke beech hoga. Or inka actual implement
relationship
Video 1:
[Link]
VH6EPyvoX&index=1
Horizontal Vertical
1. Load Balancing is required 1. Not required
2. It is resilient , there is no single point of failure 2. There is a single point of failure
3. Network calls (remote procedure calls). It is 3. Inter process communications. It is
slow fast
[Link] inconsistency 4. Data consistent
5. Scales well as users increase/ [Link] limit
Video 2:
System Design Primer : How to start with distributed systems? - YouTube
Pizza shop example:
1. Vertical Scaling: Optimise processes and increase throughput using the same resource.
2. Pre-Processing and Ron job: Preparing before hand at non peak hours.
3. Backups: Keep backups and avoid single point of failure.
4. Horizontal Scaling: Hire more resources.
5. Micro-Service Architecture: we well defines all the responsibilities to a chef and there’s
nothing outside our business use case that they handle.
6. Distributed System (Partitioning) : open a new shop as a backup, route all your request to
this so that any order that are local or very close range to this shop can be handle by it.
7. Load Balancer: It can make intelligent business design and route request in the smart way.
8. Decoupling: separating out concerns so that we can handle separate system more
efficiently.
9. Logging and metrics calculation : log every event and everything for analysis, auditing,
reporting and machine learning algorithms to find sense out of those events.
10. Extensible : we don’t want to re write the code again and again to serve a different purpose.
Example: delivery agent don’t need to know he is delivering a pizza, it could be a burger
tomorrow.
● Consistent Hashing is a concept relevant to hashing objects and it has certain properties
that one needs to know when building systems that can scale to a large extent.
● A server is a computer running a program that serves requests. For example, if someone
wants to use a facial recognition algorithm, they would connect to the server and send a
request. The server would then process the request and send back the result.
● As the number of requests increases, the single server may not be able to handle the load,
so more servers can be added to balance the load.
● The concept of taking n servers and balancing the load evenly on all of them is called load
balancing.
● The requests have a unique request ID, which is generated randomly. The request ID is then
hashed to map it to a particular server. The mapping is done by taking the result of the hash
function modulo n, where n is the number of servers.
● Because the request IDs are uniformly random and the hash function is uniformly random,
all the servers are expected to have uniform load.
● If more servers need to be added, the mapping of the requests to the servers will change,
and the requests that were being served previously will be affected. This is where consistent
hashing comes in.
● Consistent Hashing allows for a more stable distribution of requests to the servers even
when new servers are added or removed. It ensures that only a small portion of the requests
are affected and not the entire set of requests.
consistent hashing is used to evenly distribute the weight across all servers, given n servers
and a request ID that is uniformly random. The request ID is sent to the server, hashed to
produce a value, and then mapped to a particular server by taking the remainder with n (the
number of servers).
● For instance, consider the case where there are 4 servers: s0, s1, s2, and s3. If a request ID
r1 has a value of 10, when it is hashed using the hash function H, it gives the value 3. Then,
taking the remainder of 3 mod 4, gives 3, which maps to the server s3. If another request ID
r2 has a value of 20 and is hashed to give 15, then 15 mod 4 gives 3, which also maps to
server s3.
● This approach ensures that all the servers have uniform load, with each server having a load
factor of 1/n. However, the challenge arises when you need to add more servers. For
example, if you add a new server s4, then the requests which were previously served by
server s3 will have to change as well.
● In consistent hashing, when a new server is added, only a fraction of the keys that were
previously assigned to one server are remapped to the new server. The fraction of keys
remapped depends on the number of servers and the total number of keys. The mapping of
keys to servers is done such that the load is balanced across all servers, even after the
addition of a new server. This approach helps minimize the number of keys that have to be
remapped, making the process of adding new servers more efficient.
● In conclusion, consistent hashing is a way of distributing the load across servers in a
system such that when new servers are added, the load is rebalanced efficiently, with only a
fraction of the keys being remapped.
Consistent Hashing
Introduction:
● Consistent Hashing is a method used in computer networks to distribute requests evenly
among servers in a network.
Problem:
● Load balancing is difficult when adding or removing servers as it completely changes the
local data stored in each server.
Solution:
● The solution is to use a ring of hash function values, where each request is hashed
according to its ID and each server is hashed according to its ID.
● Requests are sent to the nearest server clockwise from their hash value on the ring.
● To improve the load balancing, multiple hash functions can be used.
● Virtual servers can also be used instead of physically adding more servers, reducing cost.
Theoretical Analysis:
● Hashes are uniformly random, so the distance between them is expected to be uniform.
● Load should be uniform, with an expected average of 1/n.
Practical Analysis:
● Practically, there can be skewed distributions if there are not enough servers.
● To mitigate this, multiple hash functions or virtual servers can be used.
Note: Consistent Hashing is a method used to distribute requests evenly among servers in a
network. By using a ring of hash function values, requests are sent to the nearest server clockwise.
This method can be improved by using multiple hash functions or virtual servers.
● A pizza shop receives multiple orders from clients at the same time
● To relieve the client from waiting for an immediate response, the shop gives them a
confirmation of the order placed
● The shop maintains a list of orders and works on making the pizzas as per the priority
● The architecture allows the client and the shop to perform other tasks while the orders are
being processed
Components:
Order Processing:
● If a server crashes (e.g., server 3), the notifier checks for its heartbeat
● If the server does not respond, the notifier assumes it is dead and cannot handle orders
● The notifier queries the database to find all orders that are not done and belong to the dead
server
● The notifier redistributes these orders to the remaining servers
Advantages:
● Asynchronous processing allows the client and the shop to perform other tasks while the
orders are being processed
● The priority of the orders can be manipulated as per the requirement
● The notifier helps in redistributing orders if a server crashes, ensuring that the orders are
completed
● The database provides persistence in data and ensures that the list of orders is not lost even
if a server crashes.
A monolith architecture is a large system that runs on one or multiple machines, where all clients
are connected to the same machine. The advantages of this architecture include ease of
deployment, faster performance due to the absence of network calls, and simplified testing.
However, it can be difficult for new team members to understand the entire system and
deployments may become complicated as the codebase grows.
On the other hand, microservices are individual business units that have all the data and functions
relevant to a specific service. They talk to their own dedicated databases and may communicate
with a gateway that connects to the clients. The benefits of microservices include easier scalability,
parallel development, and the ability for new team members to focus on a specific service. However,
there can be a large number of moving parts and it can be challenging to manage and maintain the
individual services.
Monolith Architecture:
Advantages:
1. Easier to scale
2. Assigning tasks based on service, reducing context for new team members
3. Facilitates parallel development
4. Reduced tight coupling between developers and services
Disadvantages:
5. They are not easy to design.
6. Complexity in managing multiple services and intercommunication
7. Increased need for monitoring and coordination between services
8. Increased complexity in testing.
The choice between monolith and microservice depends on the size and nature of the team, the
system requirements, and the scalability goals.
1. Inflexibility: Monolithic architecture is rigid and does not allow for changes to be made to
individual components without affecting the entire system.
2. Lack of scalability: Monolithic systems are not scalable and struggle to handle large
amounts of traffic or data.
3. Difficulty in deployment and testing: Monolithic architecture makes it difficult to deploy and
test individual components, as they are tightly integrated with the rest of the system.
On the other hand, microservices architecture, while offering many benefits, also comes with its own
set of challenges, such as:
I. Introduction
II. Sharding
IV. Conclusion
● Summary of the key points discussed about sharding and database optimization.
I. Introduction
The introduction explains database optimization, which is the process of making a database
perform better by improving its design and structure. It also explains indexing, which is a database
optimization technique that allows for faster search and retrieval of data by creating a separate data
structure that stores the values of one or more columns in a table.
II. Sharding
Sharding is a database partitioning technique that involves dividing a large database into smaller
parts called shards. The partitioning is done based on an attribute of the data, such as user ID, to
improve performance and efficiency of the database. Sharding can be either horizontal partitioning
or vertical partitioning, with horizontal partitioning dividing a table into multiple smaller tables, while
vertical partitioning divides a table into multiple smaller tables based on columns.
III. Key Considerations
When implementing sharding, it is important to consider consistency and availability, as the
distribution of data across multiple shards can sometimes lead to inconsistent or unavailable data.
Joining data across shards can also pose problems, and inflexibility in the number of shards can
limit the scalability of the database. A solution to this inflexibility is consistent hashing, which
assigns data to shards based on a hashing algorithm, and allows for the addition or removal of
shards without affecting the data distribution. The use of memcached, a database that uses
consistent hashing, is also discussed.
IV. Conclusion
The conclusion summarizes the key points discussed about sharding and database optimization,
highlighting the benefits of sharding and the importance of considering consistency, availability, and
scalability when implementing sharding.
Notes:
● Indexing is a method to improve query performance by creating a sorted list of the data in a
table.
● Sharding is a method of horizontal partitioning data by using an attribute of the data (e.g.
user ID or location) as a key to break the data into pieces and allocate them to different
database servers.
● Consistency is important in databases, meaning the data persisted in it should be what is
read out later, with synchronization to ensure updates are read by new requests.
● Availability is also important, meaning the database should not crash and stay down.
● Joins across shards are a problem as they need to pull data from different shards and join
the data across the network, which is expensive.
● Consistent hashing is a good algorithm to overcome the problem of inflexible shards.
● Sharding can also result in a dynamic number of shards, which can be solved by breaking a
shard that has too much data into smaller pieces.
Video 9:
1. Storing Profiles:
● Each user can have up to five images in their profile
1. Recommendation System:
● Based on user preferences, matches will be recommended
● Number of active users is an important factor to consider
1. Matches:
● When two users match, it will be noted down
● Assumption: 0.1% of users will match for every swipe (typical Indian match rate)
● Number of matches per day can be calculated as: Number of Active Users x (0.1%)
1. Direct Messaging:
● Users can chat with each other once they have matched
Note: Limit the number of features to 4-5 to avoid getting into too much detail during the interview.
The interviewer will guide the discussion towards the details they are interested in.
Storing Images:
File vs Blob
1. Mutability:
● Storing images as a file: Immutable, does not need the mutability feature offered by
databases.
● Storing images as a blob: Mutable, allows for easy updates to the image.
1. Transaction guarantees:
● Storing images as a file: Not required as image updates are not atomic operations.
● Storing images as a blob: Offers transaction guarantees, ensuring data consistency and
integrity.
1. Indexes:
● Storing images as a file: Not necessary, as images are binary objects and cannot be
searched by content.
● Storing images as a blob: Offers the ability to index data, improving search capabilities.
1. Access control:
● Storing images as a file: Access control can be achieved through a secure file system,
although it may be tedious.
● Storing images as a blob: Offers built-in access control mechanisms.
● If practicality and cost-effectiveness are the main concerns, files may be the better option.
● If transaction guarantees and access control are necessary, blobs may be the better option.
● Ultimately, the choice between files or blobs depends on the specific requirements and
constraints of the system being designed.
1. Client application: A mobile application where users can send requests by clicking a button.
2. Profile Service: A service responsible for registering the users with the system by storing
their username and password in a database. It also handles the authentication of the users
for the update profile requests.
3. Email Service: A service used for sending password and other authentication-related emails.
4. Authentication: The process of verifying the identity of a user. The profile service uses the
username and password or token to authenticate the user.
5. Gateway: A service that acts as a mediator between the client and the profile and image
services. It receives requests from the client and sends them to the profile service to
authenticate the user. If the request is authentic, the gateway forwards the request to the
appropriate service and sends the response back to the client.
6. Image Service: A service responsible for storing and processing the user's images. It has a
distributed file system and a database that stores the profile ID, image ID, and URL of the
images.
7. Distributed File System: A file system that stores images across multiple servers.
8. Decoupling: The process of separating different responsibilities and functions of a system
into separate services. The gateway acts as a decoupled system between the client and the
profile and image services, reducing the need for duplicated code and separating the
protocols.
9. Direct Messaging: A type of messaging protocol that allows for direct communication
between different services.
10. Heavy Computations: Intensive computational tasks such as image processing.
1. The system consists of a client application on a mobile device, a profile service, and a
gateway service.
2. The client application allows the user to send a request by clicking a button.
3. The profile service stores the user's username and password in a database and performs
authentication.
4. The profile service may also send emails and perform two-step authentication.
5. To update the user's profile, the client sends the username and a token for authentication.
6. The gateway service acts as an intermediary, taking the request from the client and
checking with the profile service to see if the request is authenticated.
7. If the request is authenticated, the gateway directs it to the appropriate service and
forwards the response back to the client.
8. This approach separates the responsibilities of authentication and request handling and
eliminates duplicated code across services.
9. The profile service updates the user's profile information such as the description, name, and
profile picture.
10. The image service stores and manages the user's profile pictures in a distributed file
system.
11. The image service also has a database that contains references to the profile ID, image ID,
and image URL.
12. The image service is used for heavy computations, such as when all images of a user are
needed, while the profile service is used for regular profile information retrieval.
Messaging:
Introduction to Direct Messaging:
Peer-to-Peer Protocol:
● A better solution for chat applications is to use a peer-to-peer protocol where both
clients are equal
● One example of such a protocol is XMPP (Extensible Messaging and Presence
Protocol)
● Another example is HTTP (Hypertext Transfer Protocol)
Conclusion:
Matching algorithm:
● The chat application stores information on the client device, but the server is the source of
truth for all information.
● The match service is responsible for noting down matches and will store all relevant
information on the server.
● If the client device uninstalls the app, the only information lost will be the number of people
swiped left or right, but this can be regained when the app is reinstalled.
Match Service:
● Keeps a table of user IDs to show which users have matched with each other.
● Checks if a user is authenticated to send a message to another user.
● Communicates with the session service to confirm a user's authentication and send
messages to the correct connection.
● Notes down all matches and stores the information on the server.
Session Service:
● Sends messages to the correct connection based on the user's authentication status.
Notes:
● The match service is the key component for noting down matches and maintaining
information about them.
● The client device only stores information about who was swiped left or right, but this
information can be regained if the app is reinstalled.
● The server is the source of truth for all information and ensures that information is not lost
in case the client device is uninstalled.
Recommendation System:
● To recommend people to a user, the system needs to figure out who are the users closest to
the user.
● The profile service has information about the users, such as name, age, gender, and
location. These three attributes (age, gender, and location) are used to make
recommendations.
● Having multiple indexes on these attributes is not possible in a traditional relational
database. Therefore, to optimize the recommendation system based on multiple
parameters, a NoSQL database such as Cassandra or Amazon Dynamo can be used.
● If the NoSQL databases are not preferred, sharding can be used in a relational database.
Sharding is a way of partitioning data based on its values and directing the data to a location
based on those values.
● In sharding, the data can be partitioned based on location, such that all users within a
specific location or a specific chunk of a location are sharded to a particular node.
● The data can then be pulled out from that node and searched based on age and gender
attributes.
● The sharded data can be protected from single point failure using a master-slave
architecture.
1. Sharding involves horizontal partitioning of data based on a property of the data and
directing the data to a location based on its value.
2. Consistent hashing is critical to keep the servers functioning and a master-slave
architecture can be used to prevent single point of failure.
3. Sharding the data based on the location of users can be done by dividing the city into
chunks and directing the users in a chunk to a particular node.
4. This allows for efficient searching among users within the age and gender variables.
● Caching is a technique used in computer systems to store frequently used data in memory
for faster access.
Benefits of Caching:
● Speeds up response times to clients.
● Avoids network calls to the database.
● Avoids expensive computations.
Drawbacks of Caching:
● The hardware used to run a cache is more expensive than a normal database.
● If too much data is stored in the cache, search times can increase, making it less efficient.
Cache Policy:
● The decision of when to load or evict data from a cache is referred to as a cache policy.
● LRU (Least Recently Used) is the most popular cache policy. It states that the most recently
used data should be kept at the top of the cache, and the least recently used data should be
evicted from the cache when space is needed.
● Some policies have been developed that perform even better than LRU.
● These policies are based on sliding windows and dynamically determine which data to keep
in the cache.
Cache Placement
Close to database
Close to servers
Global cache
● Distributed
● Limited in size
● Faster disk read
● More resilient to server crashes
● Can be scaled independently
● Higher accuracy of data consistency
● Avoids data inconsistency but may lead to stale data in other cache instances
Write Back Cache: Write to database first and then update cache
Cache is an important component in system design that helps to improve the performance of
applications. There are two types of cache: write-through and write-back.
● In a write-through cache, when data is updated in the cache, it is immediately sent to the
database. This ensures that the data in the cache is consistent with the data in the
database. However, the problem with this approach is that if there are other servers that
also have a copy of the same cache in memory, the update may not be reflected in all
instances, leading to data inconsistency.
● On the other hand, in a write-back cache, data is first updated in the database, and then the
cache is updated accordingly. This ensures that all instances of the cache have the same
data. However, this approach can be expensive as it requires constant updates to the cache.
● A hybrid approach, combining elements of both write-through and write-back, is also
possible. This approach involves updating the cache in a write-through manner, but instead
of immediately updating the database, the updates are stored in the cache and sent to the
database in bulk. This reduces the number of network calls and reduces the burden on the
database.
● Grokking the System Design Interview is a well-known online course that covers system
design topics, including load balancing and caching. This course provides hands-on
experience in system design and covers a range of topics, making it a valuable resource for
anyone preparing for a system design interview.
●
Video 12 : WhatsApp
group messaging
sent + delivered + read receipts
online/ last seen
image sharing
chats are temporary/ permanent/
1. Gateway:
● A user connects to the WhatsApp cloud using an external protocol when talking to the
application.
● The gateway acts as an interface between the user and the internal services of WhatsApp.
● The security mechanisms are handled by the gateway.
1. User-to-Box Mapping:
● The Gateway service needs to store information about which users are connected to which
box.
● This information was stored on the boxes but is expensive to maintain and leads to a lot of
coupling.
1. Sessions Microservice:
● To avoid this coupling, the information about who is connected to which box was decoupled
from the system and sent to the Sessions Microservice.
● The Sessions Microservice acts as a router that figures out where a user exists and routes
messages to the relevant box.
1. Send Message:
● A user sends a message by asking the gateway to send the message to another user.
● The gateway is dumb and sends the request to the Sessions Microservice.
● The Sessions Microservice routes the message to the relevant box, which sends it back to
the user.
1. Real-time Communication:
● HTTP is not suitable for real-time communication and long polling can only send messages
every minute or so.
● Websockets are used for real-time communication as they allow peer-to-peer
communication.
In summary, the WhatsApp architecture consists of a Gateway that acts as an interface between the
user and internal services. The Sessions Microservice acts as a router to route messages between
users by storing information about who is connected to which box. Real-time communication is
achieved through the use of websockets as HTTP is not suitable for chat applications.
1. Load Balancer: It balances the load across the system, but it will not be covered in detail as
it has already been discussed.
2. Service Discovery or Heartbeat Maintenance: not relevant to the chat application.
3. Authentication Service: it is simple.
4. Profile Service, Image Services, Sending Emails and SMS's: These services are not relevant
to the chat application.
5. Sending Messages: This is the core of the chat application.
6. Group Messaging: In this feature, whenever a user from a group sends a message, it should
go to all other members of the group. For example, if there is a red group with three users,
they are connected to three boxes, and if the session service stores all the information for
all groups, it becomes too complicated for the session service to handle. To resolve this, the
information for who is existing in which group is decoupled in a group service.
7. Group Service: The session service when it gets a message from a user will ask the group
service who the other group members are. The group service can then respond with the
number of members and their user IDs in the group. The session service then runs through
its own database to figure out where these users are connected to and routes the messages
to each of them.
8. Maximum Limit of Group Members: There is a maximum limit of 200 members in a group in
WhatsApp. Chat applications try to contain this to 500-600, as fanning out requests too
much is not practical, especially in real-time messaging.
9. Passing Message: To reduce the memory footprint, the session service passes the message
through a parser microservice, rather than passing the converted message object to the
gateway.
10. Parser Microservice: This microservice sends an unpassed message to any service, and its
responsibility is to pass the unpassed message through a parser. This reduces the
responsibilities of the gateways, which are expensive due to web sockets connected to
actual users.
11. Limiting the Number of Users: The number of users in a group is limited to some number x,
and it is assumed that the sessions can handle web sockets sending messages to relevant
users.
In conclusion, building a chat messaging application requires careful planning and consideration of
various factors such as load balancing, authentication, group messaging, and limiting the number of
users in a group. The session service plays a critical role in routing messages to the relevant users,
and the parser microservice helps reduce the memory footprint and responsibilities of the gateways.
1. Naming: The name of the API should reflect the action it performs. Avoid taking additional
parameters unless necessary.
2. Parameter List: Keep the parameter list as minimal as possible. Add additional parameters
only if it is needed for optimization.
3. Response: Avoid stuffing the response with more information than necessary. The response
should only contain what the caller needs.
4. Error Handling: Define the number of errors that the API can return. Keep it minimal, but
include all the important error cases.
5. Placement: Place the API in the appropriate microservice that handles related tasks.
6. Extensibility: Avoid making the response object overly complex in the hope of making it
extensible in the future. This leads to confusion and unnecessary network requirements.
7. Optimization: If the API is being heavily used and the number of calls is causing
performance issues, consider adding additional parameters for optimization purposes.
However, this should only be done when necessary and the name of the API should reflect
this change.
In summary, a good API design is about finding the balance between providing the necessary
information and making it easy for external consumers to understand how to use it. The key is to
ensure that the API is intuitive and provides clear and concise information, while avoiding any
unnecessary details.
The main disadvantage is that there might be a long wait time for a response to fail if one of the
services is down. This can lead to multiple changes for the same request, which can result in data
inconsistencies.
Disadvantages:
1) An extra layer of interaction slows services
2) Cannot be used in systems requiring strong consistency of data
3) Additional cost to team for redesigning, learning and maintaining the message queues.
Video 16:
Why do Databases fail? AntiPatterns to avoid! - YouTube
Using a database as a message queue is considered an anti-pattern. This approach is often used in
scenarios where servers (s1, s2, and s3) communicate with each other and clients (mobile or
desktop). In this approach, a server sends a message by inserting an entry into the database, and
the other server receives the message by polling the database at a specific interval. However, this
approach has several drawbacks:
1. Polling Interval: Frequent polling puts a lot of load on the database, while long intervals can
result in poor user experience.
2. Read/Write Optimization: Databases are optimized for either reading or writing, but not both.
3. Space and Deletion: The database will get filled up with entries and either needs to be
cleared frequently or updated to mark the messages as completed, which is an expensive
operation.
4. Scalability: With an increasing number of servers, the database will be unable to handle the
load of so many read operations.
In conclusion, using a database as a message queue is not an efficient or scalable solution, and
there are other technologies that are better suited for this purpose, such as message brokers or
message queue systems.
1. CDN's are used to improve the speed and efficiency of delivering content to users from
multiple countries or locations.
2. CDN's make use of caching to store static pages such as HTML pages, reducing the need to
make a request to the server for every single page.
3. CDN's can customize the content sent to different types of devices and locations, which can
help to optimize the user experience.
4. CDN's aim to serve content quickly, reducing the time it takes for web pages to load and
minimizing the risk of losing a user's interest.
5. CDN's can be a single point of failure, which can lead to the collapse of the whole system if it
crashes.
6. To mitigate this risk, CDN's can be designed as a distributed cache, with multiple nodes
working together in a group consensus.
7. Horizontal sharding of the cache can be done based on location, country, or other factors,
which helps to serve relevant content to specific users.
8. CDN's require a distributed consensus mechanism, such as Paxos or Raft, to ensure the
consistency of the cache.
9. CDN's should be designed to treat requests from different users differently, directing them
to the relevant part of the cache.
In conclusion, CDN's play a crucial role in improving the speed and efficiency of delivering content to
users and optimizing the user experience. To ensure reliability and scalability, CDN's should be
designed as a distributed cache, with a consensus mechanism to maintain consistency, and
sharding to serve relevant content to specific users.
● A single point of failure (SPOF) is a point in a system where if it fails, the entire system
crashes.
● Mitigating SPOFs is important for creating a resilient architecture and ensuring system
reliability.
● One way to reduce SPOFs is by adding another node, such as adding a backup database or
another profile server.
● Another way is to implement load balancing with multiple load balancers to distribute
requests.
● In case of load balancing, the load balancer itself can be a SPOF, so multiple load balancers
should be used and resolved through DNS.
● To prevent regional disasters, the system can be distributed across multiple regions.
● For a distributed database, the coordinator can also be a SPOF, so multiple coordinators
should be implemented.
● The process of reducing SPOFs should be propagated throughout the entire pipeline of the
distributed system.
● Tools like Netflix's chaos monkey can help test and improve resiliency.
In conclusion, reducing SPOFs is an ongoing process that requires careful planning and
implementation, but is essential for creating a reliable and resilient system.
1. Event Bus: The communication between services is facilitated through an event bus, which
acts as a medium for the services to send and receive events.
2. Producers and Subscribers: The services sending the events are known as producers, and
the services receiving the events are known as subscribers.
3. Data Persistence: Each service stores the events it receives from the event bus in its local
database. This ensures that the data remains accessible even if the service goes down.
4. Event-Driven Applications: Event-driven architecture is widely used in various applications,
including gateways, gaming systems, and first-person shooter games.
5. Timestamp-based Replication: In games, event-driven architecture allows for the replication
of events and movements at a specific timestamp. This helps in resolving disputes in a fair
manner.
6. Advantages: Event-driven architecture has several advantages, including improved
scalability, decoupled communication between services, and enhanced system resiliency.
7. Limitations: Despite its advantages, event-driven architecture can be challenging to
implement, and it may not be suitable for all types of applications. It is important to carefully
evaluate the requirements before choosing this architecture.
an example of a first-person shooter game, where event-driven architecture is used to handle the
events of headshots and movements in the game. It is stated that "in a first-person shooter game
like counter-strike, you know about the headshots that we can take." The example then goes on to
describe the scenario where player one takes a headshot, the information is sent to the server, and
the server updates the position of player two. However, due to delay response, player two moves to
a different position and the headshot is not recorded as a win for player one. To resolve this issue,
the example explains that event-driven architecture can be used by taking the events of movements
and shots with their timestamps and replicating them to see if the headshot was taken at the right
position.
Video 20 :
● NoSQL databases are non-relational databases that store data in a flexible and scalable
manner
● They are becoming increasingly popular due to their ability to handle large amounts of data,
provide high performance and scalability, and accommodate changing data structures
● SQL databases have a fixed schema and store data in structured tables with well-defined
relationships
● NoSQL databases have a flexible schema and store data as collections of documents, key-
value pairs, or graph data
1. SQL databases use a structured table format for data storage and retrieval, where each
column represents an attribute and each row represents a record. NoSQL databases use
unstructured data formats like JSON, which allow for nesting of objects and more flexible
data models.
2. In SQL databases, a foreign key relationship is used to link data from different tables. In
NoSQL databases, the data is contained in one block and there is no need for foreign key
relationships.
3. Selecting all the data relevant to a user in SQL requires a join operation which can be
expensive, while in NoSQL databases, the data is contained in one block making it easier to
insert and retrieve.
4. The schema in NoSQL databases is flexible and allows for the addition of new attributes
without the need to add a new column. This is not the case in SQL databases.
Advantages of NoSQL databases
1. Scalability: NoSQL databases can handle large amounts of data and provide horizontal
scalability, making it easy to scale out as needed
2. Flexibility: NoSQL databases can accommodate changes in data structure, making it easy to
add new fields and data types
3. Performance: NoSQL databases can provide high performance for read-heavy and write-
intensive applications
4. Cost-effective: NoSQL databases can be more cost-effective than traditional SQL databases
for large scale projects
1. Big Data: NoSQL databases can handle large amounts of data and provide scalability,
making them a popular choice for big data projects
2. Real-time web applications: NoSQL databases can provide high performance and low
latency, making them suitable for real-time web applications
3. Mobile and Internet of Things (IoT) applications: NoSQL databases can handle a large
number of concurrent users and handle rapidly changing data, making them suitable for
mobile and IoT applications
Conclusion
● NoSQL databases are becoming increasingly popular due to their ability to handle large
amounts of data, provide high performance and scalability, and accommodate changing
data structures
● It's important to choose the right type of NoSQL database for a specific use case and to
understand the trade-offs between performance, scalability, and data consistency
● In conclusion, NoSQL databases can be a valuable tool for organizations looking to manage
and analyze large amounts of data in real-time.
1. Cassandra is a NoSQL database that operates on a cluster of nodes, in this case, 5 nodes.
2. Requests coming into the cluster are assigned to a node based on their request ID. The
request ID can be a numeric value, UUID, or person's name, among others.
3. To assign the request ID to a node, the request ID is hashed and the resulting value is used
to determine the node it should be sent to.
4. A good hash function ensures that requests are distributed evenly across all nodes, allowing
each node to operate at its full capacity.
5. If the hash function is not good and one node ends up receiving too many requests, the
cluster can become overwhelmed. To avoid this, a two-layer cluster can be implemented,
with each layer using a different hash function to distribute the load more evenly.
6. To ensure that important data is not lost, replicas of the data are made and stored on other
nodes in the cluster.
7. Cassandra is used for high-availability and high-performance data storage.
The major advantage of using a hash function in Cassandra is to ensure that requests are
distributed evenly across all nodes and that important data is stored redundantly to ensure its
availability. By using a hash function and replicas, Cassandra can provide high availability and high
performance even under high load conditions.
Quorum is a term used in NoSQL databases, specifically in distributed databases like Cassandra. In
a distributed database, a quorum is the minimum number of nodes in a cluster that must
acknowledge a write operation for it to be considered successful. The purpose of a quorum is to
ensure data consistency and availability in the face of node failures.
For example, if you have a Cassandra cluster with 5 nodes and a quorum of 3, then at least 3 nodes
must respond to a write request before it is considered complete. If fewer than 3 nodes respond, the
write request will fail and the data will not be saved to the cluster. This ensures that even if some
nodes are down or unavailable, there will still be enough nodes to guarantee the reliability and
consistency of the data stored in the cluster.
Designing Instagram:
1. Key features:
● Storing and retrieving images
● Liking and commenting on posts
● Following other users
● Publishing a newsfeed
1. Image storage:
● File system is preferred for cost-effective storage
● CDN can be created for faster access
1. Liking and commenting:
● Likes table represents the posts liked by users, with user ID, timestamp, and active status.
● Parent ID in the likes table represents either a comment or a post, with a type field to
indicate the type.
● Select query can be used to find the number of likes for a post.
1. Newsfeed:
● Select star query for generating news feed is slow and not feasible for large scale.
● Solution: Maintaining a likes column in the posts table that increments whenever a post is
liked.
1. Scalability:
● Flexibility in design is important to accommodate future growth and changes.
● Optimization techniques such as caching and load balancing can be used to improve
performance.
●
1. Database design:
● ER diagram is a useful tool for designing the d
● atabase structure.
● Normalization techniques should be used to ensure consistency and efficient use of
resources.
1. Summary:
● Designing Instagram involves consideration of key features such as image storage, liking
and commenting, following users, and publishing a newsfeed.
● Database design and optimization techniques play a crucial role in ensuring scalability and
performance of the system.
Interviews: Directly give the answer to questions to save time for the interviewer and yourself.
1. System Design: Discussing advanced system design concepts using animations for better
understanding.
2. Instagram: Mobile application that needs to connect to the server-side through a gateway
that encapsulates security mechanisms(like reverse proxy , where to send request to ,
authentication, token etc).
3. Gateway: Can convert external protocols to an internal protocol for added security.
4. User Feed Service: Provides the top 20 posts for a user and is made resilient and scalable by
having multiple servers.
5. Load Balancer: Routes requests from the user's cellphone to a server and maintains a
snapshot of the entire system.
6. Consistent Hashing: Used to determine which server to send the request to by hashing the
user ID.
7. Dependent Services: User feed service depends on posts and follow services to get
information about the posts and users followed by a user.
8. Other Services: Image, activity, chat, and profile services also exist but are not directly
related to this application.
9. Finding User Feed: Simple way is to get all the users followed by a particular user ID and
retrieve the posts from the posts service.
10. Hidden Services: Other services such as image, activity, chat, and profile services are kept
hidden for now to focus on important features.
11. Future Discussions: The other services and features will be discussed in future videos.
Problem statement: A user needs to view the posts made by people they follow on Instagram.
1. Initial approach: Query the posts service for every user the user follows, which results in a
lot of wasteful computation and the post service gets bombarded with complex queries.
2. Optimizations:
3. a. Expose an API that takes in a set of user IDs and returns all posts in just one go, reducing
load on the database and the service.
4. b. Limit the number of posts that are called from the post service to reduce the load on the
database and the service.
5. The correct solution: Pre-compute the user feed anytime a user feed request comes in and
return the user feed in one shot.
6. Updating the user feed: Whenever a person the user follows posts something, the post
service should send a notification to the user feed service to update the pre-computed user
feed.
7. Storing the user feed: Use cache to store the user feeds as it separates the logic and can be
recomputed if there is a problem with memory. The most recently used users will have their
user feed served by cache.
8. Notifications: The user feed service can send notifications to relevant users whenever a new
post is made. These notifications can be sent using polling or push notifications.
9. Use of cache: The cache will store the user feeds and it will be quickly available to the users.
The cache management policies will take care of the user feeds for infrequently logging in
users.
In conclusion, the correct solution to the user's problem is to pre-compute the user feed and store it
in the cache. This approach is efficient as it reduces the load on the database and the service, and
provides quick access to the user's feed. The user feed service can also send notifications to
relevant users whenever a new post is made.
Video 30 :
System Design: Online Judge for coding contests - YouTube
Remote code execution engine:
● A system that takes code from different users and tests whether it passes the problem
statement.
● The code is submitted to the system and evaluated to give a result, either accepted (AC) or
rejected.
● Common scenario in competitive programming contests, interviews, or practice.
● Have a server that takes the code, runs it, and stores the result in a database as either
accepted or rejected.
● Issues: can't handle thousands of users submitting code at the same time (rate-limiting is
not a preferred solution).
Improved Approach:
Note: The server is probably going to have a lot of microservices, but for the 10,000 feet view, it can
be seen as a single black box.
Video 33:
System Design: Live Streaming Events like ESPN and Hotstar - YouTube
Video Flow:
Video 27 :
- Programs require a number of resources such as memory, IO, processing, and disk.
- The operating system is responsible for managing these resources.
- However, the problem of shared compute remains, where one program may take up all the
resources, leaving others without any.
II. Virtual Machines
A. Introduction
- Virtual machines provide a strong boundary between applications.
B. Technical details
- A virtual machine is like an operating system running on top of an operating system (i.e., the real
world is hidden behind a virtual world).
- Each virtual machine has been assigned a set of resources, isolated from other virtual machines.
C. Benefits
- Makes a new business model possible, called cloud computing.
- Companies like Amazon and Google can rent out their spare hardware to small businesses.
- Code does not need to be platform dependent.
- Flexible provisioning of resources.
III. Conclusion
A. Game Changer
- Platform independence is the most significant advantage of virtualization and containers.
Introduction to Containers:
Advantages of Containers:
Disadvantages of Containers:
Conclusion:
Containers provide a flexible and efficient way to virtualize applications, but they may not be
necessary for all cases. It is important to consider the advantages and disadvantages when deciding
whether to use containers in a particular situation.
● The concept of virtualization and containers comes from the problem of capacity planning in
software engineering. Previously, when a developer wrote code, they would have to estimate
the amount of compute, memory, and storage they needed and buy a computer to run it on.
This was a large investment, and if the business scaled, they would have to repeat the
process.
● To address this issue, organizations let employees use the same computer, but this led to
contention for resources. The solution was to isolate resource usage through the operating
system, which would manage the allocation of memory, IO, processing, and disk space to
different programs.
● However, there was still the problem of shared compute where if one program took up too
many resources, it would affect others. Virtual machines provided a solution by creating a
strong boundary between programs. A virtual machine is like an operating system running
on top of an operating system, giving each program its own set of resources and creating a
fake world that they can interact with, without concerning themselves with what other
programs are running in the same hardware.
● The concept of virtualization made cloud computing possible, where large companies like
Amazon and Google can rent out their spare hardware to small businesses. This allows
small businesses to avoid the upfront cost of buying and maintaining a computer and
eliminates the need for code to be platform dependent. The provisioning of resources is
also flexible and dynamic, as a virtual machine can be shut down and restarted as needed.
● Virtualization provides platform independence, flexibility, and dynamic provisioning, making
it a crucial aspect of cloud computing.
video 2 : components of system design
Logical Entities:
1. Database: Technology to store data that can be available to users in the future.
2. Application Layer: Code running on a machine that allows users to interact with the
database.
3. Communication Protocols: Enables communication between different machines so the
components can interact with each other.
4. Presentation Layer (optional): How the system is presented to the user (mobile apps,
desktop apps, websites, etc.).
Tangible Entities:
System Overview:
1. Presentation Layer: Where the system is presented to the user through desktop apps,
websites, or mobile apps.
2. Applications: Interact with databases for the exchange of data.
3. Databases: Stores data for the system.
4. Instances: Physical computers that house applications and databases and interact with each
other over network.
5. Communication: Applications interact with each other through APIs and messages.
6. Infrastructure: All components housed inside a cloud provider (AWS, GCP, etc.).
Components of a System:
1. Applications
2. Databases
3. Caches
4. Load Balancers
5. Client Interfaces
6. Network Request
7. Security Layer
8. Infrastructure.
Situation:
Requirement:
● Low latency
● Real-time response to the user
● Quick response from the server
● Avoid processing requests periodically
Solution:
1. Introduction:
● The conversation involves discussing a system for adding and executing code in
real-time
● The system involves the use of a stateful server and session-based Linux containers
2. Adding Code:
● Every time a person adds code in the session, the code is associated with a session
ID (e.g. "session ID 123")
● The code is added as a block with line numbers (e.g. line number 5)
3. Executing Code:
● For each browser session, a new Linux container is started and kept alive as long as
the user is present
● The code is executed on the container and the output is sent back to the user as a
response
● The container has its own space, hard disk space, network, and files, making it a
unique operating system
4. Server State and Persistent Storage:
● The system's statefulness and use of Linux containers ensure that code execution
does not need to be recomputed every time a new line is added
● If the system crashes, the containers can be restarted by looking at the persistent
storage (e.g. database) and building a container based on the stored code
5. Problem: Storing Results and Timestamps:
● Storing results can be a challenge as they cannot be stored onto variables
● The problem of timestamps (e.g. the real-world factor of time) can be solved by
storing the information that can change the state later on at the start of the code
execution
6. Mitigating System Crashes:
● If an engineer writes the system, crashes may occur quite often
● The system should be scalable as more users and containers are added
● Possible causes of crashes include power loss, data corruption, and network
partition
● To mitigate the effects of crashes, the database stores the code, but in case of a
crash, the user may have to wait for a few seconds
● The goal is to know about a container crash as quickly as possible, without
disrupting the user's experience while they are writing code.
CAP | Consistency, Availability and Partitioning | System Design Tutorials | Lecture 19 | 2020 -
YouTube
CAP Theorem:
● CAP theorem is a concept in computer science that defines the limitations of distributed
systems in regards to Consistency, Availability, and Partition tolerance.
● It states that it is impossible for a distributed system to simultaneously provide all three of
these guarantees.
● A distributed system can only provide two of the three guarantees at a given time.
Consistency:
● Consistency refers to the property that all nodes in a system see the same data at the same
time.
● It ensures that the system's data is consistent and up-to-date across all nodes.
● In a system with strong consistency, all nodes have the same view of the data, and any
change made to the data is immediately visible to all nodes.
Availability:
● Availability refers to the property that a system is always able to respond to a request,
regardless of the state of the system.
● It ensures that a system is able to serve its clients even in the event of failures or network
partitions.
Partition Tolerance:
● Partition tolerance refers to the property that a system continues to operate even when
there is a network partition or communication failure between nodes.
● It ensures that the system is able to operate even when there is a failure in communication
between nodes.
Choosing between Consistency and Availability:
● The choice between consistency and availability depends on the specific requirements of
the system.
● If consistency is more important, the system should sacrifice some level of availability in
order to ensure that all nodes have the same view of the data.
● If availability is more important, the system should sacrifice some level of consistency in
order to ensure that it is always able to respond to requests.
● In practice, most systems aim to strike a balance between consistency and availability, and
trade-off some level of partition tolerance.
● Different systems make different trade-offs based on their specific requirements.
● For example, in a banking system, consistency is more important than availability. In such a
system, it is more important to ensure that all nodes have the same view of the data, even if
the system is unavailable for a brief period of time.
● On the other hand, in a social media system, availability is more important than consistency.
In such a system, it is more important to ensure that the system is always available, even if
the data is inconsistent for a brief period of time.
Conclusion:
● CAP theorem is a fundamental concept in computer science that defines the limitations of
distributed systems.
● It states that a distributed system can only provide two of the three guarantees of
Consistency, Availability, and Partition tolerance at a given time.
● The choice between consistency and availability depends on the specific requirements of
the system, and most systems aim to strike a balance between the two.
Ritik
Monolith: A monolithic architecture is the traditional unified model for the design of a software
program. Monolithic, in this context, means "composed all in one piece." According to the
Cambridge dictionary, the adjective monolithic also means both "too large" and "unable to be
changed."
Performance – In a centralized code base and repository, one API can often
perform the same function that numerous APIs perform with microservices.
Easy debugging – With all code located in one place, it’s easier to follow a
request and find an issue.
As with the case of Netflix, monolithic applications can be quite effective until
they grow too large and scaling becomes a challenge. Making a small change
in a single function requires compiling and testing the entire platform, which
goes against the agile approach today’s developers favor.
Advantages of microservices
Agility – Promote agile ways of working with small teams that deploy
frequently.
Highly maintainable and testable – Teams can experiment with new features
and roll back if something doesn’t work. This makes it easier to update code
and accelerates time-to-market for new features. Plus, it is easy to isolate and
fix faults and bugs in individual services.
High reliability – You can deploy changes for a specific service, without the
threat of bringing down the entire application.
Happier teams – The Atlassian teams who work with microservices are a lot
happier, since they are more autonomous and can build and deploy
themselves without waiting weeks for a pull request to be approved.
Disadvantages of microservices
Exponential infrastructure costs – Each new microservice can have its own
cost for test suite, deployment playbooks, hosting infrastructure, monitoring
tools, and more.
Debugging challenges – Each microservice has its own set of logs, which
makes debugging more complicated. Plus, a single business process can run
across multiple machines, further complicating debugging.
Lack of clear ownership – As more services are introduced, so are the number
of teams running those services. Over time it becomes difficult to know the
available services a team can leverage and who to contact for support.
Vertical scaling, often referred to as "scaling up," involves adding resources to a single node in a system, such as increasing memory or processing power . This approach improves the performance of the node but has a finite limit and can lead to a single point of failure . In contrast, horizontal scaling, or "scaling out," involves adding more nodes to distribute workloads across multiple machines. This enhances capacity and resilience because if one machine fails, others can handle the workload without interruption . Horizontal scaling requires a load balancer for distributing the load evenly but can face challenges with data consistency due to the involvement of multiple nodes . In essence, vertical scaling enhances the capabilities of a single node, while horizontal scaling spreads the workload across a network of nodes, each approach offering distinct advantages and limitations in terms of system architecture and capacity management.
Consistent hashing is pivotal in supporting load balancing by efficiently mapping requests to servers in a dynamic cluster. It assigns each server a point on a hash ring, distributing request keys across the ring so that each server handles a proportionate share of requests based on its position . When a server is added or removed, only a small subset of keys are remapped, minimizing disruption and maintaining balanced loads . This property is particularly advantageous in systems with frequently changing server groups, as it allows for seamless scaling without substantial redistributions of existing keys . Consistent hashing's ability to distribute loads evenly while adapting to cluster changes makes it an ideal strategy for maintaining robust and efficient load balancing in dynamic server environments.
Gateways and session microservices play complementary roles in managing user connections in chat applications. The gateway acts as an interface between users and internal services, handling initial connection requests and ensuring security by converting external protocols to internal ones . It is generally responsible for authenticating and routing initial messages within the application's ecosystem . In contrast, session microservices focus on maintaining active connection information, mapping each user to their corresponding session or box, thus routing messages effectively within the chat application . This separation allows for a decoupled architecture where the gateway handles entry processes, and the session microservice manages ongoing communications, optimizes routing, and maintains overall system efficiency and scalability . Together, these components form a robust framework for real-time chat applications, enhancing security, scalability, and connection management.
To prevent a single point of failure (SPOF) in a system, several strategies can be used, each contributing to system resilience in different ways. Redundancy involves having multiple components (e.g., servers or network paths) so that if one fails, others can take over, ensuring continuity . Load balancing distributes workloads across multiple components to prevent any one from becoming overwhelmed, thereby reducing the risk of failure . Master-slave architecture ensures data is replicated and operations can continue even if the primary system fails, enhancing fault tolerance . Regular maintenance and testing help identify potential failures before they occur, minimizing the risk of unexpected outages . Disaster recovery planning outlines how to respond to and recover from failures swiftly, ensuring minimal downtime . Collectively, these approaches strengthen system resilience by anticipating and mitigating risks associated with component failures.
The master-slave architecture enhances system read operations and data availability by maintaining multiple replicas of data across slave nodes . This setup allows read operations to be distributed across these nodes, increasing the system's read throughput and reducing the load on the master node . Consequently, data availability is improved, as requests can be directed to any available slave node, thus preventing bottlenecks at the master . Moreover, in case the master node fails, the system can promote a slave to a master role, ensuring continuous data availability and minimizing downtime . This architecture scales out read operations and improves resilience, making it highly beneficial for systems with intensive read requirements.
Virtualization enhances IT infrastructure efficiency by allowing multiple virtual machines (VMs) to run on a single physical machine, optimizing resource use and enabling easy scaling . It separates software environments from the underlying hardware, facilitating cloud computing and improved workload management . Containers further improve efficiency by packaging an application and its dependencies into a single unit, making it lightweight and portable without the overhead of a full OS image . They enable rapid deployment and consistent execution across various environments, from local development to cloud systems . These technologies allow organizations to scale efficiently, as resources can be allocated dynamically, and applications can easily move across different infrastructures, thereby enhancing the scalability of IT systems.
Load balancing improves system performance and efficiency by distributing incoming network traffic or workloads evenly across multiple servers or nodes . This ensures that no single server becomes overwhelmed, enhancing the overall response time and reliability of the system . By preventing any single point from being a bottleneck, load balancing increases the network's capacity to handle more requests smoothly . Additionally, the use of consistent hashing in load balancing helps map requests to specific servers efficiently, ensuring balanced resource allocation and minimizing latency . These mechanisms collectively optimize system resource utilization and ensure high availability, leading to efficient management of distributed workloads.
Peer-to-peer (P2P) protocols in chat applications offer several benefits, including enhanced communication efficiency and reduced server load. By allowing direct communication between clients, P2P protocols like XMPP (Extensible Messaging and Presence Protocol) minimize the need for constant polling of a server, thus reducing the overhead typically associated with client-server communication . This setup also promotes scalability by enabling more direct and efficient data exchanges . However, potential challenges include increased complexity in maintaining connection information, as each client must be aware of others' IP addresses or identifiers for direct communication . Additionally, P2P protocols pose security concerns because the direct nature of the connections might expose users to risks unless proper encryption is implemented . Managing these connections effectively can be complex, requiring robust session handling and authentication processes to ensure secure and reliable communication.
The thundering herd problem occurs when numerous clients simultaneously access a resource, such as a server, leading to potential overload and failure . This can severely impact system performance by causing high load peaks, ultimately triggering cascading failures across dependent components . To mitigate the thundering herd problem, rate limiting can control the number of requests processed by the system over a specific period, helping to manage traffic spikes and protect server resources . Another approach involves pre-scaling, which anticipates high load periods (such as during a Black Friday sale) and prepares additional resources to handle increased traffic efficiently, thereby preventing crashes . These methods maintain system stability by evenly distributing the load and preventing bottlenecks during sudden demand increases.
Heartbeats in distributed systems are critical for maintaining the health and reliability of the network. They are periodic signals sent between nodes to verify status and confirm that nodes are operational . If a node fails to send a heartbeat, it is marked as down, and other nodes can take over its tasks, facilitating uninterrupted service continuity . This mechanism allows for the detection of node failures swiftly and reliably, triggering failover procedures to backup nodes and ensuring that the system continues to function effectively despite individual node failures . Furthermore, heartbeats integrate with service discovery by comparing snapshots in load balancers and establishing new connections if discrepancies are detected, thereby maintaining overall system reliability .