Monday, June 9, 2025

Monday, January 6, 2025

What is WebRTC and How Does It Work?

 WebRTC or Web Real-Time Connection is an open-source project that allows real-time communication between devices and web browsers, You may confuse it with WebSockets, which also allow users to communicate in real-time. But what is the difference? Is WebRTC a websocket? What is WebRTC and why is it used in many places in place of a web socket? This is what we're gonna learn today.


WebSocket vs WebRTC

Feature WebSocket WebRTC
Communication Model Client-Server Peer-to-Peer
Primary Use Real-time data exchange between client and server Real-time audio, video, and data between peers
Latency Low, but depends on server routing Generally lower due to direct P2P connection
Data Types Text and binary Media streams (audio/video) and data channels
Setup Complexity Relatively simple More complex (requires signaling, NAT traversal)
Server Requirements Requires a server to manage connections and relay messages An initial signaling server is needed, but media/data flows directly between peers

Use Cases comparison:

Both of them have different use cases that they are designed for, and since they're not using the same connection mode;

WebSocket is mostly used for:

  1. Chat Applications: Real-time messaging between users.
  2. Live Notifications: Instant updates like stock tickers or social media feeds.
  3. Online Gaming: Real-time game state synchronization.
  4. Collaborative Tools: Real-time document editing or whiteboards.

While WebRTC is used for:

  1. Video Conferencing: Platforms like Zoom or Google Meet leverage WebRTC for real-time video and audio.
  2. Voice Calls: VoIP applications using browsers.
  3. P2P File Sharing: Direct transfer of files between users.
  4. Interactive Gaming: Real-time multiplayer games requiring low latency.

When to Use Each Technology

Use WebSocket when:
  1. You need real-time communication between a client and a server.
  2. Implementing features like live chat, real-time dashboards, or notifications.
  3. The communication does not involve high-bandwidth media streams.
Use WebRTC when:
  1. You require real-time peer-to-peer media communication (audio/video).
  2. Building applications like video conferencing, live streaming, or P2P file sharing.
  3. You want to reduce server load by handling media directly between clients.
 

What is WebRTC anyway?

Okay, so to explain it simply, it's a technology that provides a collection of APIs and protocols that allow for Peer-to-peer (P2P) exchange of audio, video, and data in general. It was mainly designed to handle video, audio, and generally heavy real-time communication, unlike WebSockets that are used for mostly text, and binary, and are not as frequent. 

synchronizing video or audio online, particularly on a server, can be resource-consuming due to the potential for high traffic from millions of users. To address this issue, WebRTC was developed. With WebRTC, a server is only needed for the initial signaling process, while the actual communication occurs through Peer-to-Peer connections. I've talked about P2P more in this What is Peer-to-peer (P2P) network? if you're interested.

 Key WebRTC APIs are:

  1. MediaStream API (getUserMedia): For capturing audio and video from local devices.
  2. RTCPeerConnection API: For managing connections between peers.
  3. RTCDataChannel API: For exchanging arbitrary data between peers.

Why would you use WebRTC instead of Websockets?

WebRTC's Main purpose in its life is to handle real-time audio and video streams, it has built-in support for codecs, synchronization, and media quality adjustments. While WebSockets are not optimized for media. In addition to that, Peer2Peer communication allows for lower latency and low resource consumption. 

On a WebSocket, as I mentioned earlier, each bit and frame of a video will have to pass through the server, which is very inefficient. WebRTC offers data channels that are optimized for real-time data transfer, with lower latency than Websockets. While WebSockets are capable of handling real-time data, it's not to the level that WebRTC was built for.

Conclusion

In conclusion, You may need to use them together, for example, you need to signal the WebRTC to start the data exchange and establish the peer-to-peer connection. You could even use them in parallel, WebRTC handles the video/audio or file transfer while WebSockets handles anything that is not that. that's all there is to it. I guess, Thank you for reading. You can check out official docs whenever you think you need to get in-depth in it.

What is Peer-to-peer (P2P) network?

 P2P or Peer to Peer is a distributed network architecture where connected devices, and peers, act as a server and client, instead of data being sent to the server and then processed back down to you, it's decentralized, meaning that you and all the peers that are connected with you share the resources directly with each other, allowing for fast and easy connection that requires has no middle man or authority.

Example of Peer to Peer
Source: Wikipedia

Examples of P2P

Peer-to-peer is often used in illegal activities like sharing pirated games/movies or sometimes it's used because of the speed, sometimes the servers can limit the download speed of any app but with peer, you can reach out to any device that has the files you need and the other device will send it back to you as fast as it can. No server or third party can see what that file is or limit the speed except your ISP; Examples of P2P are:

  1. BitTorrent: A popular file-sharing protocol that enables efficient distribution of large files.
  2. Skype: Uses P2P technology for voice and video calls, enhancing call quality and reducing latency.
  3. Bitcoin: A decentralized cryptocurrency network that relies on P2P principles for transactions and validation.

What are the types of P2P?

There are multiple types of Peer to Peer connections, and each has its own features:

The Unstructured P2P Networks; In this network, peers connect randomly with no organization at all, this type of connection is obviously easy to build but has some efficiency issues for content delivery.

On the other hand, Structured P2P Networks; Are the opposite of the latter, peers are structured and each of them has a specific task or portion of the network, allowing for more efficient content location.

Finally, there is the Hybrid P2P Networks which are a combination of both P2P and client-server models, They typically use a centralized server for specific functionality while maintaining peer-to-peer interactions for others.

What made P2P standout

In summary, peer-to-peer (P2P) connections offer significant benefits for both end users and developers. They enable low-latency communication, improving the overall user experience, reducing server workload, and allowing servers to allocate resources to other tasks more efficiently. This makes P2P particularly valuable in applications where minimal delay is crucial, such as video conferencing, online gaming, and voice calls.

Additionally, P2P networks excel in scenarios requiring high-speed data transfer. Unlike centralized servers, which could struggle under the burden of managing massive data volumes—such as transmitting hundreds of gigabits per second to thousands of users—P2P connections distribute the workload across participants, ensuring smoother operations. They are also inherently more resilient to censorship, server outages, and network disruptions, offering a decentralized and robust alternative to traditional systems.

Furthermore, P2P technology promotes scalability by leveraging the resources of connected devices, making it a cost-effective solution for developers. It can also enhance privacy, as direct communication between peers minimizes reliance on intermediaries. These features position P2P as a versatile and future-proof technology in the evolving digital landscape. 

Saturday, January 4, 2025

What is Local Area Network (LAN)?

Local Area Network (LAN) Explained

Local Area Network (LAN) is a type of network that interconnects a countable number of devices that are connected in a fairly small area, such as homes, offices, small groups of buildings, and so on. Its relatives, the World Wide Web (WWW) and Wide Area Network (WAN) consist of thousands or rather millions of LANs, it's like the building blocks of the Internet.

A Local Area Network is made up of multiple components that need to work together to correctly send and receive data from and to your device, this process of giving and receiving data is mostly handled by routers, switches, access points, and modems through connected wires or Wi-Fi.

An image demonstrating a small Local Area Network
Example of a Home/Office LAN

LAN vs WAN and WWW

LANs are quite different from Wide-Area Networks (WANs) and the World Wide Web (WWW). They only cover a small geographic area and typically don't connect more than a couple of buildings, usually one single building.

WAN, on the other hand, is simply a LAN but on a wider scale, says its name (Wide Area Network), it covers a considerable zone that spans cities and even countries, often by connecting multiple LANs across.

WWW is the father of all the Internet. When you access a URL, sometimes you see WWW at the beginning of the URL, and that's it. The World Wide Web is a global information system that interconnects documents and resources via the Internet; it's the core of the Internet. It conveys information using the rules of HTTP.

It's important to note that LAN is not part of the WWW, and WWW and WAN are not the same concept. These are separate networking concepts with different scales and purposes.

LAN Connectivity

LANs typically connect devices using:

  • Routers: Direct network traffic between different networks (e.g., your home network and the internet).
  • Switches: Manage communication between devices within the same local network by forwarding data to the correct device.
  • Access Points: Extend the network wirelessly, allowing devices to connect via Wi-Fi.
  • Modems: Connect your network to your internet service provider (ISP) by converting signals (digital to analog and vice versa).

Devices can connect via Ethernet cables, Wi-Fi, or in some cases, other wireless technologies. The fastest way that connect the internet together is a wire type called fiber optics.

Conclusion

LAN has many advantages that make it superior, it's very fast in transferring data within it, and since it's relatively small, it's pretty easy to set strong security measures and manage its cost by sharing resources from printers/computers and files in a small area. Thanks to the technology and the people who helped it flourish, we're now more advanced than ever.

How does the Internet work?

The world is connected like never before because of the internet, a massive network of systems and technologies. This network links billions of devices globally, allowing us to communicate, shop, learn, and have fun. At its core, the Internet is a bunch of networks working together using hardware, software, and protocols to send and receive data smoothly.

How the Internet Works

The internet works by breaking data into small packets that travel across networks to reach their destination, like text, video, or email. These packets find their way using IP (Internet Protocol) addresses, which are unique to every device online.

The TCP/IP model explains how data moves through the internet in four layers:

  1. Application Layer: Handles user-facing services like HTTP, FTP, or email.
  2. Transport Layer: Manages reliable communication between devices (e.g., TCP, UDP).
  3. Internet Layer: Handles routing of data packets across networks (e.g., IP).
  4. Network Access Layer: Manages physical connections and data transmission.

Important devices like routers, switches, and servers make this all work. Routers send packets between networks, switches manage traffic within a network, and servers store and provide data when needed.

Fiber Optic Technology

Fiber optic cables are the backbone of the internet. They use light pulses to send data super fast over long distances. These cables are better than traditional wires because they can handle massive amounts of data with little to no interference. Except, it has very high maintenance.

Fiber optic cables have three main parts:

  • Core: The center where light signals travel.

  • Cladding: Surrounds the core and keeps the light from escaping.

  • Coating: Protects the cable from damage.

With speeds that reach gigabits per second, fiber optics are key for streaming, gaming, and cloud services.

A video explaining How Fiber Obtics:


How Fiber Optics Are Laid

Installing fiber optic cables happens both underwater and on land. Submarine cables connect continents by crossing oceans. Specialized ships lay these cables, burying them in the seabed for protection.

On land, cables are installed along roads or railways or buried underground. This involves digging trenches or using advanced methods like micro-trenching to avoid disruptions. In cities, existing utility ducts are often used.

Challenges and Maintenance

Setting up fiber optics isn’t easy. It’s expensive, and there are obstacles like rough terrains and the need for global cooperation for underwater cables. Maintenance is also critical since cables can get damaged by earthquakes or human activities like fishing. Repair teams and special ships fix these problems to keep the internet running.

Real World Example

Imagine sending a message to a friend in Asia or America. If you’re far away, your message would travel underwater to reach them—mind-blowing, right? That message made up of zeros and ones, gets routed through 1-20 different servers until it reaches the server closest to your friend. Using their router’s IP and device IP, the message is delivered, and they can respond. All of this happens in just milliseconds!

To calculate the minimum time your message needs to arrive to them, you have to calculate the distance divided by the speed of light, so if they're 2000 km, or 1242 miles away, then that's around 0.0066 seconds, which is 66ms. 

Conclusion

The internet connects the world, and it’s all possible because of clever engineering and teamwork. From data packets to fiber optics, everything works together to make sure we stay connected. As technology improves, the internet will continue growing, bringing us closer and making life easier.

What is Content Delivery Network (CDN)

One second ago, I thought CDN meant CloudFlare DNS or something like that, but now after discovering the truth, I'm here to share what I've learned:

What is a CDN?

A CDN is an acronym for Content Delivery Network. It is a network of servers distributed across the globe to make content (such as images, videos, JavaScript, CSS files, and other resources) load faster. The main goal of a CDN is to improve the loading speeds and reliability of the network and make users happy.

How do CDNs work

A CDN (Content Delivery Network) is a network of geographically distributed servers called edge servers, each with a copy or cache of data on the original server. These servers work together to deliver content (such as images, videos, JavaScript, CSS files, and other resources) to users based on their geographic location. CDN improves internet speed and reliability and makes users satisfied.

CDN example
Exhibition of origin and edge server
source: https://www.cloudns.net/blog/cdn-content-delivery-network/


Guess what, you just used a CDN, entered this page, and loaded the Fonts and other assets that are needed for this page to load, the Content Delivery Network found your local edge server and requested data from there since the world is connected with huge submarine Fiber optic cables. If the server is in Antarctica for example then all of us will wait a trivial 160ms (The time it takes for light to reach the server)  approximately for the data REQUEST to arrive and then the time needed by the server to find your data and THEN send it back within another 160ms, which is absurd.

Moreover, a CDN has many benefits. In addition to making content load faster, they also make the website safer by providing (Distributed Denial of Service) protection, SSL/TLS encryption, and Web Application Firewalls (WAF). There are multiple CDNs around the world, and each of them has its own network of servers across the world, I believe the reason I thought it had something to do with Cloudflare is that I was right. Cloudflare is a CDN. Funny, right?

Here is a list of some common CDNs:

  • Cloudflare
  • Akamai
  • jsDelivr
  • Google Cloud CDN
  • Amazon CloudFront
You're not responsible for choosing your own CDN, but the web developers are, they choose what service to use for their Domain, for example, use Blogger, so the CDN for me is Google and I can't change it until I get a Domaint that I can play around with.

Conclusion

And that's all it, in a nutshell, imagine a CDN as the middleman between you and the original server, each edge server is a middleman that is the nearest to you, namely you can even check all Cloudflare servers near you.

Thank you for reading


Wednesday, January 1, 2025

What is Largest Contentful Paint (LCP) and How to Optimize It

Maintaining a fast and performant website that can work in multiple environments, slow internet, and devices is such a hard thing to do, and you may have struggled with this thing called Largest Contentful Paint (LCP), which all it does is tell every single time that there is an item on your page that is not rendering/loading as fast as it was expecting, which is obnoxious. In this blog post, you'll what exactly is LCP and how each of its 4 components works together to give you bad results. Which is probably the reason why you're not ranking well.

What is LCP

Largest Contentful Paint (LCP) is a key web performance metric that measures the time it takes for the largest content element visible in the viewport to render on a web page. This element is typically an image, video, or large text block. LCP is one of Google's Core Web Vitals, used to assess website performance and user experience.

LCP focuses on the content above the fold, which is visible without scrolling. It provides insight into a website's perceived loading speed by measuring the render time of the most visually significant element. This metric is considered more reliable than First Contentful Paint (FCP) for determining when a page is ready for interaction.

To provide a good user experience:

  • LCP should occur within 2.5 seconds of page load initiation (considered good).
  • LCP between 2.5 and 4 seconds needs improvement.
  • LCP above 4 seconds is considered poor.

Optimizing LCP can improve a website's overall user experience and lead to higher search rankings, lower bounce rates, and increased conversion rates.

Now LCP has different components that lead to it, for example:

LCP components

These components impact the LCP percentage, with longer timings indicating worse performance. A higher percentage means more focus is needed on the specific contributor to fix the problem faster.

Time to First Byte (TTFB)

TTFB measures the time between the request for a resource and when the first byte of the response begins to arrive. It includes:

  • Redirect time
  • Service worker startup time
  • DNS lookup
  • Connection and TLS negotiation
  • Initial server response time
If TTFB is high, the problem could be with the server hosting the resource, but it could also be due to network issues or server performance bottlenecks. It's worth investigating server response times and network latency.

Load Delay

Load delay (Resource Load Delay) is the time between TTFB and when the browser starts loading the LCP resource. Key characteristics include:

  • The time between the HTML document starts loading and the image download
  • Directly impacts LCP performance
  • Determines initial resource loading speed

It is an important factor in determining how quickly the key content on a page loads, meaning that we need to have a deeper understanding of this particular element.

To reduce Load Delay and improve LCP, focus on optimizing server response time (TTFB) by using faster web servers and a CDN (Like Cloudflare), prioritize critical resources like images and fonts with preload, minimize render-blocking JavaScript, defer non-essential scripts, and lazy-load images. Compress and serve images in modern formats (e.g., WebP), use responsive images, reduce DNS lookups by limiting external resources, and enable efficient caching with appropriate headers. These steps ensure faster resource loading and a better LCP score.

Render Delay

Render delay is the time between LCP resource loading and full element rendering. Caused by:

  • Render-blocking resources
  • Elements not yet in the DOM
  • Hidden elements by code
  • Main thread blockage

Ideal render delay: About 10% of the total LCP budget

Attention: I noticed that when I start the analyzing in the lighthouse, if I was not on the page while analyzing the performance score will go down significantly, and some of the factors to LCP will go wild, like Load Time and Render Delay. So keep this on a good note :).

While i'm not on focusing on pagespeed.web.dev
Not on the page
Results of not focusing on the site
The render delay was almost 100%, because of the issue I described. Load delay and load time are 0 because there are no render-blocking scripts, I had to remove a font to make it work, you could try. Sometimes using fonts that break the website apart is not worth it.
Results of focusing on the site
While on the page



Load Time

Load time refers to the duration to load the LCP resource, also known as Resource Load Duration.

  • For text nodes with system fonts: 0 load time
  • Measures actual resource download duration
This is different than load delay because in load delay the browser has finished TTFB and is now waiting for something that has more priority.

Relationship to LCP

These components collectively compose the Largest Contentful Paint metric:

  1. TTFB: Initial process delay
  2. Load Delay: The time until the Resource starts loading
  3. Load Time: time taken for the element to be fully loaded
  4. Render Delay: Element display time

Optimization Impact

Improving these components can:

  • Enhance user experience
  • Boost search engine rankings
  • Reduce perceived loading time
Lastly, I would like to give you a method that you might not know to optimize and remove the unused bytes on the page, This will lead to a subsequent reduction in load delays and render delays, which affects the Largest Contentful Paint (LCP). Either from CSS or javascript, you have a Coverage tab in your dev tools, this beautiful tool tells you exactly line by line what resources aren't being used on this specific website (Excess resources), this can occur if you put all CSS in one file, or all javascript in one file, and yes, this can have a sensible impact on your site's performance. 

Total LCP Time = TTFB + Load Delay + Load Time + Render Delay

Thank you for reading