Sunday, 5 May 2024

What is CDN (Content Delivery network) and How it works?

CDN stands for Content Delivery Network, acts as a service to enhance the speed of content delivery in applications, making websites respond faster. To illustrate, consider a scenario where you've developed a learning website with users scattered across the globe, yet your application isn't deployed worldwide.

 

Suppose you've developed a learning website with a user base spanning the globe. However, your application is deployed only in New Delhi Datacenter.

 

Here are the approximate distances between New Delhi and the cities where your application users reside:

 

1.   Colombo: Approximately 2,000 kilometers (1,240 miles).

2.   Beijing: Approximately 3,600 kilometers (2,200 miles).

3.   Moscow: Approximately 4,000 kilometers (2,500 miles).

4.   Madrid: Approximately 7,100 kilometers (4,400 miles).

5.   Cape Town: Approximately 7,500 kilometers (4,660 miles).

6.   London: Approximately 7,600 kilometers (4,700 miles).

7.   Sydney: Approximately 10,300 kilometers (6,400 miles).

8.   New York: Approximately 11,800 kilometers (7,300 miles).

 

 


Let's examine the user journey for those in Colombo. When they make a request to the website, the data must travel 2,000 kilometers to New Delhi and back, totalling 4,000 kilometers. Generally, response times are measured in milliseconds. For instance, let's assume a round trip time of approximately 200 milliseconds for a 2,000-kilometer distance:

 

Colombo: Approximately 2,000 kilometers (1,240 miles) : 200 milliseconds

 

Now, considering the distances to other cities:

 

1.   Beijing: Approximately 3,600 kilometers

Network call time = (200 milliseconds * 3,600) / 2,000 = 360 milliseconds

2.   Moscow: Approximately 4,000 kilometers

Network call time = (200 milliseconds * 4,000) / 2,000 = 400 milliseconds

3.   Madrid: Approximately 7,100 kilometers

Network call time = (200 milliseconds * 7,100) / 2,000 = 710 milliseconds

4.   Cape Town: Approximately 7,500 kilometers

Network call time = (200 milliseconds * 7,500) / 2,000 = 750 milliseconds

5.   London: Approximately 7,600 kilometers

Network call time = (200 milliseconds * 7,600) / 2,000 = 760 milliseconds

6.   Sydney: Approximately 10,300 kilometers

Network call time = (200 milliseconds * 10,300) / 2,000 = 1,030 milliseconds

7.   New York: Approximately 11,800 kilometers

Network call time = (200 milliseconds * 11,800) / 2,000 = 1,180 milliseconds

 

These computations assume a linear correlation between distance and time, which may not fully reflect real-world scenarios due to other factors such as network infrastructure and latency. In summary, the greater the distance, the longer it takes to deliver data to users, resulting in slower website performance.

 



How CDN helps in this scenario?

CDNs tackle this challenge by minimizing the distance between users and content. Typically, CDNs establish content delivery network endpoints in as many locations worldwide as possible. Here's an overview of some leading Content Delivery Networks (CDNs) and the regions where they commonly maintain a presence:

 

1.   Akamai: Akamai operates one of the largest CDNs globally. Its reach spans major cities in North America, Europe, Asia-Pacific, and South America.

2.   Cloudflare: Covering over 200 cities worldwide, Cloudflare boasts a widespread network of data centers. Its presence extends across North America, Europe, Asia-Pacific, Africa, and South America.

3.   Amazon CloudFront: Amazon CloudFront's vast network of edge locations is dispersed across multiple continents, including North America, South America, Europe, Asia-Pacific, and the Middle East.

4.   Google Cloud CDN: Leveraging Google's expansive global infrastructure, Google Cloud CDN maintains edge locations in numerous cities across North America, Europe, Asia-Pacific, and other regions.

5.   Microsoft Azure CDN: With edge locations in various cities across continents, including North America, Europe, Asia-Pacific, and the Middle East, Microsoft Azure CDN has a comprehensive global presence.

6.   Fastly: Operating a network of edge servers in major cities worldwide, Fastly has a robust presence in North America, Europe, Asia-Pacific, and South America.

7.   KeyCDN: KeyCDN's global network of POPs (Points of Presence) spans major cities across North America, Europe, Asia-Pacific, and other regions.

 

To simplify this example, let's assume that the CDN we're utilizing is available in all the locations where our users are located.

 


 

Now, when a user in Beijing attempts to access the content, it's initially fetched by the Content Delivery Network Service and then distributed globally to all the nodes in CDN. Consequently, users in London no longer need to access the application deployed in New Delhi to retrieve the content; they can directly access it from the nearest CDN. This significantly reduces the time taken to deliver the content. Additionally, CDNs reduce the amount of traffic reaching the server deployed in New Delhi.

 

Points to consider while choosing a CDN

a. Cost: The pricing structure of a CDN can vary significantly depending on factors such as data transfer volume, request rates, and additional services. It's essential to evaluate the cost-effectiveness of different CDN providers based on your traffic patterns and budget constraints.

 

b. Cache Expiry Policies: CDN cache expiry policies determine how long content remains cached at edge locations before it's refreshed from the origin server. Understanding and configuring cache expiry policies appropriately can impact content freshness and performance. Consider whether the CDN offers flexible options for setting cache expiry times based on content type or URL patterns.

 

c. CDN Fallback Implementation (When CDN is Down): It's crucial to have a fallback strategy in place for situations when the CDN experiences downtime or performance issues. This may involve configuring DNS failover to direct traffic back to the origin server or utilizing alternative CDN providers as backups.

 

d. Invalidating CDN Content via APIs: CDNs typically offer APIs or control panels to programmatically invalidate cached content when updates are made to the origin server. Evaluate the ease of use and effectiveness of these invalidation mechanisms, as efficient cache invalidation is essential for timely content updates.

 

e. Availability of CDN Across the Globe: Consider the geographical coverage of the CDN provider's network to ensure adequate reach for your global user base. Assess the number and distribution of edge locations worldwide, as well as the network's performance in regions where your users are concentrated.

 

f. Security Features: Evaluate the CDN's security offerings, including DDoS protection, SSL/TLS encryption, and access control mechanisms. Robust security features are essential for safeguarding content and mitigating potential threats.

 

g. Analytics and Reporting: Consider the availability of analytics tools and reporting features provided by the CDN for monitoring traffic, performance metrics, and usage patterns. Insights from these analytics can help optimize content delivery and troubleshoot issues effectively.

 

h. Scalability and Traffic Handling: Assess the CDN's scalability capabilities to accommodate traffic spikes and growing user demand. Look for features like auto-scaling and load balancing to ensure smooth performance under varying traffic conditions.

 

By carefully considering these factors and conducting thorough evaluations, you can choose a CDN that best aligns with your requirements for cost-effectiveness, performance, reliability, and scalability.


                                                  System Design Questions

PlantUML: Use icons from OpenIconic

OpenIconic is an open source icon set. As these icons are integrated with creole parser, you can use them in PlantUML.

 

How to see all the available icons?

Command 'listopeniconic' print all the available icons.

 

printAllIcons.txt

@startuml
listopeniconic
@enduml

Above snippet generate below command.


 


How to refer an existing icon?

Using <&icon_name> syntax, we can refer an existing icon.

 

icons.txt

@startuml

scale 1.5

Client -> Server: Client send folder structure
Server -> Client: Server process the folder


note left of Client 
euro : <&euro>
bar chart : <&bar-chart> 
end note

@enduml

Above snippet generate below diagram.



 

  

Previous                                                    Next                                                    Home

PlantUML: embed special Unicode characters

We can embed special Unicode characters using below notation.

Syntax 1

&#XXX

 

Syntax 2

<U+XXXX>

 

specialUnicodeHandling.txt

@startuml

scale 1.5

Client -> Server: Client send folder structure
Server -> Client: Server process the folder


note left of Client 
Special chars1: &#8734;
Special chars1: <U+2606>
end note

@enduml

 

Above snippet generate below diagram.

 


 

Previous                                                    Next                                                    Home

PlantUML: build a tree using Creole

Symbols |_ used to build a tree.

tree.txt

@startuml

scale 1.5

Client -> Server: Client send folder structure
Server -> Client: Server process the folder


note left of Client 
root
|_ folder1
|_ **Secret Folder**
|_ folder2
  |_ subfolder1
  |_ subfolder2
|_ folder3
end note

@enduml

Above snippet generate below diagram.




Previous                                                    Next                                                    Home

Points to consider while using the cache

A cache is a temporary storage, designed to store the result of resource-intensive tasks and frequently accessed information. By enabling subsequent operations to retrieve data from the cache, it mitigate the risk of overloading database servers.

 

Without cache

When there's no cache, every time the application needs data from the database, it asks the database directly. This puts a lot of stress on the database. When the queries are complicated/resource intensive, it takes a long time to get the response, and the database gets used up quickly. The picture below shows what happens when there's no cache.

 


 

With Cache

With a cache layer, the application first looks in the cache to see if the data it needs is already there before asking the database. If the data is in the cache, it's retrieved from there. If not, the data is fetched from the database, stored in the cache, and then sent to the client. This process is shown in the image below.

 


Pseudo code

function getData(key):
    if cache.contains(key):
        // If data is in cache, retrieve it
        return cache.get(key)
    else:
        // If data is not in cache, fetch from database
        data = queryDatabase(key)
        // Store data in cache for future use
        cache.put(key, data)
        return data

// Application logic
data = getData("some_key")
// Use the data retrieved from either cache or database

In the above code, the getData function first checks if the data is present in the cache. If it is, it retrieves the data from the cache. If not, it queries the database to fetch the data, stores it in the cache, and then returns the data. This way, subsequent requests for the same data can be served from the cache, reducing the load on the database.

 

Points to consider while using the cache

1. Decide the areas that benefitted from cache layer

Frequently accessed data that undergoes infrequent modifications can be efficiently stored in the cache. The results of resource-intensive operations can be cached to reduce the computational load on the system.

 

2. Expiration Policy

It's advisable to establish an expiration policy for cached data. Without one, data remains in the cache indefinitely, potentially causing discrepancies between the database and cache over time.

 

Time based expiration is the most common cache expiration policy, where the data is removed from the cache after a specified period of time has elapsed since it was stored or last accessed.

 

3. Eviction Policy

Eviction refers to the selection of items for removal from the cache when a new item needs to be added but the cache has reached its maximum capacity (Capacity can be defined either by size or by total number of items etc.,).

 

Some common cache eviction policies include:

 

a.   LRU (Least Recently Used): Data that has not been accessed for a certain period of time is evicted from the cache, prioritizing the retention of more recently accessed data.

b.   LFU (Least Frequently Used): Data that has been accessed the fewest number of times is removed from the cache when space is needed.

c.    FIFO (First In First Out): Data that has been added to the cache times is removed from the cache when space is needed.

 

4. Distributed vs in-memory Cache

Distributed cache and in-memory cache do similar jobs but work differently.

 

a.   Distributed Cache: It spreads across many servers, each storing a part of the data. They're good for handling lots of traffic because they split the work between servers. Examples are Redis Cluster and Memcached.

b.   In-Memory Cache: It lives in the server's memory itself. It's easier to use but might not handle as much traffic. Examples include local caches like Java Caching System, Caffeine.

 

Both help things work faster by saving time and reducing how much the database does. Which one you choose depends on how much traffic you have, how well you want things to handle mistakes, and how complicated your system is.

 

5. Cache size

Here are some tips for finding the right cache size:

 

a.   Start with Small and Watch: Begin with a modest cache size and keep an eye on how well it's working. Look at things like how often data is served from the cache instead of the database.

b.   Look at Cache Hit Rate: If most requests (over 90%) are coming from the cache, that's great! But if it's lower, your cache might need to be bigger or hold onto data for longer.

c.    Watch for Old Data: If users are seeing old information because your cache is too big, it might be time to shrink it or make items expire faster.

d.   Use Monitoring Tools: There are lots of tools out there to help you keep an eye on how your cache is doing. They can show you what's happening and where you might need to make changes.

 

Remember, finding the perfect cache size is all about keeping an eye on things and adjusting as needed.

 

6. Security considerations

Caching poses risks if not adequately secured. Here are key considerations:

 

a.   Avoid storing sensitive data such as passwords in the cache, or employ encryption if necessary.

b.   Restrict access to the cache to authorized users to prevent unauthorized access to sensitive information.

c.    Validate data before caching to prevent the storage of potentially harmful content.

d.   Implement encryption protocols like TLS to safeguard data during transit between your application and the cache.

e.   Monitor cache access and modifications to identify any suspicious activity.

f.     Implement expiration policies for cached data to prevent it from persisting indefinitely.

g.   Conduct regular security assessments of your cache infrastructure to address any vulnerabilities.

 

If you want to take a look at popular caching systems, refer below tutorials.

 

Caffeine Cache

Ehcache

ExpiringMap

Guava Cache

JCS (Java Caching System)

Spymemcached

Redis

Caching


                                                  System Design Questions

PlantUML : apply colors to creole table cells

Using #color notation, we can apply colors to the table cells.

 

Example 1: Apply colors to individual cell


| <#ff00ff>1 | <#PaleGreen> Krishna | <#PaleVioletRed>34 |

 

Example 2: Apply colors to entire row.


<#YellowGreen>| 2 | Ram | 43 |

 

tableColors.txt

@startuml

scale 1.5

Client -> Server: Client send employees information
Server -> Client: Server process employees data and send response


note left of Client 
Example of simple employees data
|= id |= name |= age |
| <#ff00ff>1 | <#PaleGreen> Krishna | <#PaleVioletRed>34 |
<#YellowGreen>| 2 | Ram | 43 |
end note

@enduml

 

Above snippet generate below diagram.

 


 

Previous                                                    Next                                                    Home

PlantUML: Use code tag to display programming code

code.txt

@startuml

skinparam NoteFontSize 8

scale 1.5

Client -> Server: Client Hello
Server -> Client: Server Hello


note left of Client 
<code>
public static void main(String args[]){
     System.out.println("Hello")
}
</code>
end note

@enduml

 

Above snippet generate below diagram.


 

 

Previous                                                    Next                                                    Home