<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Shwetabh Shekhar</title>
    <description>The latest articles on Forem by Shwetabh Shekhar (@shwetabh1).</description>
    <link>https://forem.com/shwetabh1</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F504261%2Fceb4386f-f3cf-4aaa-9f43-e95baf96518e.jpg</url>
      <title>Forem: Shwetabh Shekhar</title>
      <link>https://forem.com/shwetabh1</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/shwetabh1"/>
    <language>en</language>
    <item>
      <title>My favorite CLI Tools for improved productivity.</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Sun, 23 May 2021 15:22:32 +0000</pubDate>
      <link>https://forem.com/shwetabh1/my-favorite-cli-tools-for-improved-productivity-30l9</link>
      <guid>https://forem.com/shwetabh1/my-favorite-cli-tools-for-improved-productivity-30l9</guid>
      <description>&lt;p&gt;These are my top 5 favorites. Use them to make working with #terminal easier and efficient. - YMMV&lt;/p&gt;

&lt;p&gt;First and foremost, if you are on Mac replace your terminal with iTerm, a much more powerful powerful terminal emulator.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://fishshell.com/"&gt;Fishshell&lt;/a&gt;: I love the autosuggestions. Saves way too much time. There are many other useful features as well.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://github.com/nvbn/thefuck"&gt;thefuck&lt;/a&gt;: Misspelled a command? Use this simple command to correct typos. There is no need to retype it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://brew.sh/"&gt;HomeBrew&lt;/a&gt;: Easy installation of apps. On Mac, the cask install feature comes in handy and removes the need to drag applications.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://github.com/wting/autojump"&gt;autojump&lt;/a&gt;: Forget &lt;code&gt;cd&lt;/code&gt;. This is a much faster way to navigate your filesystem. It maintains a database of the directories you use the most from the command line.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://github.com/tldr-pages/tldr"&gt;TLDR&lt;/a&gt;: Concise man pages with lots of examples, just the way we want.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>productivity</category>
      <category>mac</category>
      <category>terminal</category>
    </item>
    <item>
      <title>These three books have helped shaped my Developer career.</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Mon, 19 Apr 2021 17:03:12 +0000</pubDate>
      <link>https://forem.com/shwetabh1/these-three-books-have-helped-shaped-my-developer-career-4h9n</link>
      <guid>https://forem.com/shwetabh1/these-three-books-have-helped-shaped-my-developer-career-4h9n</guid>
      <description>&lt;p&gt;&lt;em&gt;"Some books are to be tasted, others to be swallowed, and some few to be chewed and digested."&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Out of the plethora of books I have read through, these three technical and self-help books, for me, undoubtedly fall into the category of being chewed and digested. Why so? Because they have not only impacted the way I think about work or approach a problem but have helped me add order to my life, write improved code, crack interviews, and achieve a few of my biggest goals - YMMV.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Atomic Habits&lt;br&gt;
Have you ever wondered why solving one leet code question consistently in the long run always works? Why do you keep getting better and better? &lt;br&gt;
It is because of the power of consistent small progress that accumulates to give a positive result. This book helped me realize you don't need to start making drastic changes to become successful. Moreover, techniques such as habit stacking helped me form and maintain new habits easily.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Pragmatic Programmer&lt;br&gt;
I read this during the 2020 lockdown and was saddened to discover it so late. The beautiful thing about this book is that it sparks ideas when you read it. Can you do something more efficiently? Can you do it more elegantly? The topics introduced in this book are a must to put into practice for every developer to empower their career. The tips are equally good.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cracking the Coding Interview&lt;br&gt;
This book is laden with concise theories and thoughtful questions. Even though there are many online alternatives to it, this has a special place in my heart as it helped me crack the Amazon SDE Intern interview back in 2017 along with many others.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Please share with me books you would say have added value and helped you progress in your career.&lt;/p&gt;

</description>
      <category>books</category>
      <category>career</category>
      <category>programming</category>
    </item>
    <item>
      <title>Complete Webpage Rendering Process In Browser</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Tue, 09 Feb 2021 12:29:34 +0000</pubDate>
      <link>https://forem.com/shwetabh1/complete-webpage-rendering-process-in-browser-59l1</link>
      <guid>https://forem.com/shwetabh1/complete-webpage-rendering-process-in-browser-59l1</guid>
      <description>&lt;p&gt;&lt;em&gt;I will try to explain the webpage rendering process in a browser in depth.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Once the server supplies the resources (HTML, CSS, JS, images, etc.) to the browser it undergoes the below process:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parsing&lt;/strong&gt; - HTML, CSS, JS&lt;br&gt;
&lt;strong&gt;Rendering&lt;/strong&gt; - Construct DOM Tree → Render Tree → Layout of Render Tree → Painting the render tree.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The rendering engine starts getting the contents of the requested document from the networking layer. This will usually be done in 8kB chunks.
&lt;/li&gt;
&lt;li&gt;A DOM tree is built out of the broken response. 
&lt;/li&gt;
&lt;li&gt;New requests are made to the server for each new resource that is found in the HTML source (typically images, style sheets, and JavaScript files). 
&lt;/li&gt;
&lt;li&gt;At this stage the browser marks the document as interactive and starts parsing scripts that are in "deferred" mode: those that should be executed after the document is parsed. The document state is set to "complete" and a "load" event is fired. 
&lt;/li&gt;
&lt;li&gt;Each CSS file is parsed into a StyleSheet object, where each object contains CSS rules with selectors and objects corresponding to CSS grammar. The tree built is called CSSCOM. 
&lt;/li&gt;
&lt;li&gt;On top of DOM and CSSOM, a rendering tree is created, which is a set of objects to be rendered. Each of the rendering objects contains its corresponding DOM object (or a text block) plus the calculated styles. In other words, the render tree describes the visual representation of a DOM. 
&lt;/li&gt;
&lt;li&gt;After the construction of the render tree it goes through a "layout" process. Which means giving each node the exact coordinates where it should appear on the screen. 
&lt;/li&gt;
&lt;li&gt;The next stage is painting–the render tree will be traversed and each node will be painted using the UI backend layer. 
&lt;/li&gt;
&lt;li&gt;Repaint: When changing element styles that don't affect the element's position on a page (such as background-color, border-color, visibility), the browser just repaints the element again with the new styles applied (that means a "repaint" or "restyle" is happening). 
&lt;/li&gt;
&lt;li&gt;Reflow: When the changes affect document contents or structure, or element position, a reflow (or relayout) happens. 
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;What is the internal structure of a web browser?&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://i.stack.imgur.com/vgtHG.png" rel="noopener noreferrer"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.stack.imgur.com%2FvgtHG.png" alt="browser structure"&gt;&lt;/a&gt;&lt;br&gt;
To understand the page rendering process explained in the above points we also need to understand the structure of a web browser.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;User interface:&lt;/strong&gt; The user interface includes the address bar, back/forward button, bookmarking menu, etc. Every part of the browser display except the window where you see the requested page. &lt;br&gt;&lt;br&gt;
&lt;strong&gt;Browser engine:&lt;/strong&gt; The browser engine marshals actions between the UI and the rendering engine. &lt;br&gt;&lt;br&gt;
&lt;strong&gt;Rendering engine:&lt;/strong&gt; The rendering engine is responsible for displaying requested content. For example, if the requested content is HTML, the rendering engine parses HTML and CSS and displays the parsed content on the screen. &lt;br&gt;&lt;br&gt;
&lt;strong&gt;Networking:&lt;/strong&gt; The networking handles network calls such as HTTP requests, using different implementations for different platforms behind a platform-independent interface. &lt;br&gt;&lt;br&gt;
&lt;strong&gt;UI backend:&lt;/strong&gt; The UI backend is used for drawing basic widgets like combo boxes and windows. This backend exposes a generic interface that is not platform-specific. Underneath it uses operating system user interface methods. &lt;br&gt;&lt;br&gt;
&lt;strong&gt;JavaScript engine:&lt;/strong&gt; The JavaScript engine is used to parse and execute JavaScript code. &lt;br&gt;&lt;br&gt;
&lt;strong&gt;Data storage:&lt;/strong&gt; The data storage is a persistence layer. The browser may need to save all sorts of data locally, such as cookies. Browsers also support storage mechanisms such as localStorage, IndexedDB, WebSQL, and FileSystem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt;&lt;br&gt;
During the rendering process, the graphical computing layers can use a general-purpose CPU or the graphical processor GPU as well.&lt;br&gt;
When using GPU for graphical rendering computations the graphical software layers split the task into multiple pieces, so it can take advantage of GPU's massive parallelism for float point calculations required for the rendering process.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Useful Links:&lt;/strong&gt; &lt;br&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;a href="https://github.com/alex/what-happens-when" rel="noopener noreferrer"&gt;https://github.com/alex/what-happens-when&lt;/a&gt; 
&lt;/li&gt;
&lt;li&gt;&lt;a href="https://codeburst.io/how-browsers-work-6350a4234634" rel="noopener noreferrer"&gt;https://codeburst.io/how-browsers-work-6350a4234634&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>html</category>
      <category>css</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>What strategy do you follow when learning something new?</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Tue, 19 Jan 2021 09:10:55 +0000</pubDate>
      <link>https://forem.com/shwetabh1/what-strategy-do-you-follow-when-learning-something-new-100l</link>
      <guid>https://forem.com/shwetabh1/what-strategy-do-you-follow-when-learning-something-new-100l</guid>
      <description>&lt;p&gt;Do you target it's BREADTH first? Go through different sections on the subject matter in a shallow way and then slowly dive deep into each one.&lt;/p&gt;

&lt;p&gt;Or do you do a DEPTH first approach where you finish each section in detail and then only move onto the next?&lt;/p&gt;

</description>
      <category>discuss</category>
      <category>watercooler</category>
    </item>
    <item>
      <title>Generating Meaningful Test Data Using Faker</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Sun, 17 Jan 2021 10:49:28 +0000</pubDate>
      <link>https://forem.com/shwetabh1/generating-meaningful-test-data-using-faker-3f9e</link>
      <guid>https://forem.com/shwetabh1/generating-meaningful-test-data-using-faker-3f9e</guid>
      <description>&lt;p&gt;Whether you are building an API or writing tests for features that process massive datasets, meaningful test data is always a necessity. How do we fill this need? Faker is the answer.&lt;/p&gt;

&lt;h2&gt;What is Faker?&lt;/h2&gt;

&lt;p&gt;Faker is a library that can be used to generates a humongous amount of realistic fake data in Node.js and the browser. It is also available in a variety of other languages such as Python, Perl, Ruby, and C#. This article, however, will focus entirely on the Node.js flavor of Faker.&lt;/p&gt;

&lt;p&gt;You can see a live demonstration of faker &lt;a href="https://rawgit.com/Marak/faker.js/master/examples/browser/index.html"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Generating Data using Faker&lt;/h2&gt;

&lt;p&gt;Let's consider a use case where we want to store personal information in a CSV file with the following fields:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First Name&lt;/li&gt;
&lt;li&gt;Last Name&lt;/li&gt;
&lt;li&gt;Address(City, State, Zip Code, Country)&lt;/li&gt;
&lt;li&gt;Phone Number&lt;/li&gt;
&lt;li&gt;Email&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And we need &lt;strong&gt;100,000&lt;/strong&gt; such records (&lt;em&gt;meaningful&lt;/em&gt;). Stop for a moment and think how would you have generated this? This is where Faker comes into play.&lt;/p&gt;

&lt;h3&gt;Generating CSV Datasets&lt;/h3&gt;

&lt;p&gt;Initialize your node project and Install faker:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i faker
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Include the dependencies in your project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const faker = require('faker');
const fs = require('fs');
const _ = require('lodash');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Define your headers for CSV based on the schema:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//define the headers of your csv file.
//define the object literal that would store the functions for each index
//faker generates new data for every call
let csvHeaders = {
    FIRST_NAME: faker.name.firstName(),
    LAST_NAME: faker.name.lastName(),
    STREET_ADDRESS: faker.address.streetAddress(),
    CITY: faker.address.city(),
    STATE: faker.address.state(),
    ZIP_CODE: faker.address.zipCode(),
    COUNTRY: faker.address.country(),
    VOICE_NUMBER: faker.phone.phoneNumber(),
    EMAIL_ADDRESS: faker.internet.email(),
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I am using &lt;strong&gt;streams&lt;/strong&gt;, given we are writing input into output sequentially.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// open write stream
let stream = fs.createWriteStream("huge-csv.csv");
// write the header line.
stream.write(Object.keys(csvHeaders).toString()+ "\n");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create the 100,000 record CSV file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//write the body
let csvBody = [];
for (let i = 0; i &amp;lt; 1000000; i++) {
    _.forEach(csvHeaders, function(value, key){
        //console.log(value);
        csvBody.push(value);
    })
    //console.log(csvBody.toString(), 'CSV BODY');
    stream.write(csvBody.toString()+ "\n");
    csvBody = [];


}
// close the stream
stream.end(); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;Generating JSON Datasets&lt;/h3&gt;

&lt;p&gt;The process of generating the JSON file remains more or less the same with minor tweaks. I will leave that as an exercise. The code is available at &lt;a href="https://github.com/Shwetabh1/Generate-Convert-Huge-Dataset-JSON-CSV/tree/master/Generate%20Massive%20Datasets"&gt;my github repository&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt; Other Features and API Methods of Faker &lt;/h2&gt;

&lt;p&gt;I have only used a subset of the supported API methods in the above example. The faker.js can generate fake data for various other areas, including &lt;strong&gt;commerce, company, date, finance, image, random&lt;/strong&gt;, etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const faker = require('faker');

# Jobs
let jobTitle = faker.name.jobTitle();
console.log(jobTitle);

let jobArea = faker.name.jobArea();
console.log(jobArea);

# dates

let futureDate = faker.date.future();
console.log(futureDate);

let recentDate = faker.date.recent();
console.log(recentDate);

let weekday = faker.date.weekday();
console.log(weekday);

# random values
let number = faker.random.number();
console.log(number);

let uuid = faker.random.uuid();
console.log(uuid);

let word = faker.random.word();
console.log(word);

let words = faker.random.words(6);
console.log(words);

# and so on...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can even use it directly in the browser as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script src = "faker.js" type = "text/javascript"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script&amp;gt;
  var randomName = faker.name.findName(); // Caitlyn Kerluke
  var randomEmail = faker.internet.email(); // Rusty@arne.info
  var randomCard = faker.helpers.createCard(); // random contact card containing many properties
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fake data is extremely useful when building and testing our application and Faker can help us with that. For a complete list of supported APIs, visit this &lt;a href="http://marak.github.io/faker.js/"&gt;link&lt;/a&gt;. Have you used Faker? How was your experience?&lt;/p&gt;

</description>
      <category>node</category>
      <category>javascript</category>
    </item>
    <item>
      <title>When Should You Jump From Your Job?</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Fri, 15 Jan 2021 16:11:44 +0000</pubDate>
      <link>https://forem.com/shwetabh1/when-should-you-jump-from-your-job-2oei</link>
      <guid>https://forem.com/shwetabh1/when-should-you-jump-from-your-job-2oei</guid>
      <description>&lt;p&gt;After you start at a new place:&lt;/p&gt;

&lt;p&gt;Every 4 months have a one-on-one meeting with your supervisor. Talk about your progress within the company/agency/group, and voice your support for participation in projects or programs that would be beneficial to your career, or promotions. Let your supervisor know you are interested in challenges.&lt;/p&gt;

&lt;p&gt;If you get to a point where your career trajectory at a company/group/whatever is stagnating - THEN you should start looking for another position.&lt;/p&gt;

&lt;p&gt;If you're at the same company for a while but you're progressing, there can be advantages - hikes, more money in stock options, higher responsibilities, you get to REALLY know your clients.&lt;/p&gt;

&lt;p&gt;If you're in a company and &lt;strong&gt;you let them know you're up for challenges or promotions and nothing happens - and you're demonstrating you can handle the harder work - that's a sign to move on&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;You are worth more the more you learn. Otherwise, you are getting paid less the more you know.&lt;/p&gt;

</description>
      <category>career</category>
    </item>
    <item>
      <title>How AWS Lambda Works Underneath?</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Wed, 13 Jan 2021 19:12:52 +0000</pubDate>
      <link>https://forem.com/shwetabh1/how-aws-lambda-works-underneath-4if1</link>
      <guid>https://forem.com/shwetabh1/how-aws-lambda-works-underneath-4if1</guid>
      <description>&lt;center&gt;_Details create the big picture. - Sanford I. Weill_&lt;/center&gt;

&lt;p&gt;AWS Lambda has become ubiquitous when it comes to serverless applications. And why shouldn't it be? Using it you can run code for virtually any type of application or backend service - all with zero administration. There is no need to provision or manage any infrastructure. Just upload your code and Lambda takes care of everything required to run and scale your code with high availability. But ever wondered how that happens?&lt;/p&gt;

&lt;p&gt;How exactly does Lamda run our code? How does it autoscale? How does it balance the load? How does it handle the errors? What about security? Where does the code exactly run? &lt;strong&gt;What exactly happens when you call &lt;code&gt;lambda.invoke()&lt;/code&gt;?&lt;/strong&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Understanding the basic building blocks
&lt;/h1&gt;

&lt;p&gt;To answer all our above questions we need to understand the architecture of AWS Lambda. Under the hood, AWS Lambda has a really sophisticated architecture that keeps on evolving. This is what takes care of all the undifferentiated heavy lifting for the developers. This architecture can be dissected into two parts, &lt;strong&gt;Control Plane&lt;/strong&gt; and &lt;strong&gt;Data Plane&lt;/strong&gt; as depicted below:&lt;/p&gt;

&lt;h2&gt;
  
  
  Control Plane
&lt;/h2&gt;

&lt;p&gt;This plane is responsible for our interaction with AWS Lambda using various methods such as AWS Console, APIs, and AWS SAM. It is responsible for packaging the code and providing configuration APIs which allows us to set various configurations such as concurrency, environment variables, timeouts amongst other options.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F3q0ofhr3uczocw2581wd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F3q0ofhr3uczocw2581wd.png" alt="Screenshot 2021-01-14 at 12.20.38 AM" width="800" height="452"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  Data Plane
&lt;/h2&gt;

&lt;p&gt;This plane is responsible for handling the synchronous and asynchronous invocation of Lambda. Different components present in it handle authentication, scalability, errors, different limits, etc. To understand how these components work in synergy and make Lambda what it is we first need to understand each and every component of it individually.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Front End Invoke:&lt;/strong&gt; This service authenticates all lambda invocation requests. Moreover, it is also responsible for loading metadata and coordinating with Counting Service to confirm concurrency. Basically, it orchestrates synchronous and asynchronous invocation of Lambda.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Counting Service:&lt;/strong&gt; A critical component that provides a region-wide view of customer concurrency to help enforce set limits. It tracks the current concurrency and takes further action when the limit is hit.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Worker Manager:&lt;/strong&gt; It tracks container idle and busy state and schedules incoming invoke requests to available containers. Moreover, it ensures lambda executes with correct privileges. In addition to that, it interacts with Placement Service to scale containers up and down for scalability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Placement Service:&lt;/strong&gt; This is responsible for placing sandboxes for workers. It uses intelligence to help determine where a sandbox should be put and how to administer unhealthy workers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Worker&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fkak3x0scl641nhozv969.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fkak3x0scl641nhozv969.png" alt="Alt Text" width="800" height="408"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is where our code executes. Worker Provisions a secure environment for customer code execution. It also provides multiple run time environments. Furthermore, it downloads customer code and mounts it for execution. In addition to that, it also notifies the Worker Manager when execution is completed.&lt;/p&gt;

&lt;p&gt;One Worker can have the Lambda function running from various accounts. There are virtualization mechanisms present to handle isolation for codes for the different lambda functions. (More on this in the next tutorial.)&lt;/p&gt;

&lt;h1&gt;
  
  
  How does everything fit together?
&lt;/h1&gt;

&lt;p&gt;Let's answer our original question &lt;code&gt;What exactly happens when we hit invoke on lambda?&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fp3allkonoi36y37l9ej3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fp3allkonoi36y37l9ej3.png" alt="Alt Text" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Lambda is invoked. The Application Load Balancer routes the request to a fleet of Front End Invoke service.&lt;/li&gt;
&lt;li&gt;Front End Invoke authenticates the request. It then downloads function metadata and goes to the counting service to check the concurrency limit. Upon successful authentication and concurrency validation, it goes to the Worker Manager to reserve a sandbox.&lt;/li&gt;
&lt;li&gt;Upon receiving the request, the Worker Manager firstly locates a Worker. It then creates a sandbox on it. Upon successful creation, it downloads the function code and then initializes the run time. It finally calls init on it. [cold start]&lt;/li&gt;
&lt;li&gt;Once the init function has completed, the Worker lets the Worker Manager know which lets the Front End Invoke know.&lt;/li&gt;
&lt;li&gt;Front End now directly calls Invoke on the Worker.&lt;/li&gt;
&lt;li&gt;Once the code finishes execution Worker lets the Worker Manager know it is idle and thus there is a warm sandbox.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  Warm Start
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fkp4x4cpx2t9uj3imphpr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fkp4x4cpx2t9uj3imphpr.png" alt="Alt Text" width="800" height="448"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We all know Warm start in Lambda's run faster. This is the exact reason why. During a warm start, the Worker Manager doesn't need to administer a worker and initialize it. It already exists and is ready for utilization. Consider the above scenario where the code has just run on a worker and it is warm.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The first three steps remain the same.&lt;/li&gt;
&lt;li&gt;Front End reaches to Worker Manager to reserve a sandbox but this time Worker Manager already has a warm sandbox and thus it straightway returns the Worker's location to the Front End Service.&lt;/li&gt;
&lt;li&gt;Front End calls invoke on it which is relatively faster.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  How does autoscaling work?
&lt;/h1&gt;

&lt;p&gt;What happens when the Worker Manager can't find a Worker for provisioning sandboxes? Such an event occurs when all Workers are utilized and in such a scenario, the Worker Manager interacts with Placement Service which provides it with a new Worker location. Placement service is solely responsible for fulfilling worker capacity and maintaining scalability. Anytime there are no new workers left it provides Worker Manager with new workers(with a lease of 6-10 hrs). &lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ftht4ii0hv1xfq0j4pxd7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ftht4ii0hv1xfq0j4pxd7.png" alt="Alt Text" width="800" height="444"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  How does it handle failures?
&lt;/h1&gt;

&lt;p&gt;Lambda continuously monitors the health of hosts and removes unhealthy hosts. When a Worker becomes unhealthy Worker Manager detects and stops provisioning sandboxes on it. And if the entire availability zone fails the system components continue working without routing traffic to the failed availability zone. This is how Lambda always remains fault-tolerant.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;This is more or less the whole crux of how Lambda works under the hood and executes our code while maintaining scalability and fault tolerance. There is still a lot of questions left unanswered though. How exactly does a Worker work? Moreover, Worker is running functions from various accounts on top of only one hardware then how does it isolate the code and runtime? What is the virtualization technology used? I will be answering all these questions in the next part of this tutorial. Hope this was helpful.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Acknowledgments:&lt;/strong&gt; All images are part of the AWS reinvent 2018 &amp;amp; 2019 sessions. I strongly suggest watching it. &lt;a href="https://www.youtube.com/watch?v=QdzV04T_kec&amp;amp;t=2149s"&gt;Video 1&lt;/a&gt;, &lt;a href="https://www.youtube.com/watch?v=xmacMfbrG28"&gt;Video 2&lt;/a&gt;&lt;/p&gt;

</description>
      <category>aws</category>
      <category>cloud</category>
      <category>serverless</category>
      <category>devops</category>
    </item>
    <item>
      <title>Browser: Complete Process Of Hitting A URL And Rendering The Page.</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Wed, 06 Jan 2021 08:10:26 +0000</pubDate>
      <link>https://forem.com/shwetabh1/browser-complete-process-of-hitting-a-url-and-rendering-the-page-2e4n</link>
      <guid>https://forem.com/shwetabh1/browser-complete-process-of-hitting-a-url-and-rendering-the-page-2e4n</guid>
      <description>&lt;p&gt;&lt;em&gt;Acknowledgments: My post is inspired by the famous &lt;a href="https://github.com/alex/what-happens-when"&gt;what-happens-when GitHub repository&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Ever wondered what happens when you type in an URL in the browser? What happens behind the scenes to fetch the page? How does the page load?&lt;/p&gt;

&lt;p&gt;Read on to find out.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;You type maps.google.com(Uniform Resource Locator) into the address bar of your browser and press enter.&lt;/li&gt;
&lt;li&gt;Every URL has a unique IP address associated with it. The mapping is stored in Name Servers and this procedure is called Domain Name System.&lt;/li&gt;
&lt;li&gt;The browser checks its cache to find the IP Address for the URL.

&lt;ul&gt;
&lt;li&gt;If it doesn't find it, it checks its OS to find the IP address (gethostname);&lt;/li&gt;
&lt;li&gt;It then checks the router's cache.&lt;/li&gt;
&lt;li&gt;It then checks the ISP's cache. If it is not available there the ISP makes a recursive request to different name servers.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;It checks the &lt;strong&gt;com&lt;/strong&gt; name server (we have many name servers such as 'us', 'gov', 'io' etc) and it will redirect to google.com. &lt;/li&gt;
&lt;li&gt;google.com's name server will find the matching IP address for maps.google.com in its’ DNS records and return it to your DNS recursor which will send it back to your browser.&lt;/li&gt;
&lt;li&gt;Browser initiates a TCP connection with the server. It uses a three-way handshake: &lt;/li&gt;
&lt;li&gt;Client machine sends an SYN packet to the server over the internet asking if it is open for new connections.&lt;/li&gt;
&lt;li&gt;If the server has open ports that can accept and initiate new connections, it’ll respond with an ACKnowledgment of the SYN packet using an SYN/ACK packet.&lt;/li&gt;
&lt;li&gt;The client will receive the SYN/ACK packet from the server and will acknowledge it by sending an ACK packet.
Then a TCP connection is established for data transmission!&lt;/li&gt;
&lt;li&gt;The browser will send a GET request asking for a maps.google.com web page. If you’re entering credentials or submitting a form this could be a POST request.&lt;/li&gt;
&lt;li&gt;The server sends the response.&lt;/li&gt;
&lt;li&gt;Once the server supplies the resources (HTML, CSS, JS, images, etc.) to the browser it undergoes the below process: 
&lt;strong&gt;Parsing -&lt;/strong&gt; HTML, CSS, JS  
&lt;strong&gt;Rendering -&lt;/strong&gt; Construct DOM Tree → Render Tree → Layout of Render Tree → Painting the render tree 
&lt;/li&gt;
&lt;li&gt;The rendering engine starts getting the contents of the requested document from the networking layer. This will usually be done in 8kB chunks.
&lt;/li&gt;
&lt;li&gt;A DOM tree is built out of the broken response. 
&lt;/li&gt;
&lt;li&gt;New requests are made to the server for each new resource that is found in the HTML source (typically images, style sheets, and JavaScript files). 
&lt;/li&gt;
&lt;li&gt;At this stage the browser marks the document as interactive and starts parsing scripts that are in "deferred" mode: those that should be executed after the document is parsed. The document state is set to "complete" and a "load" event is fired. 
&lt;/li&gt;
&lt;li&gt;Each CSS file is parsed into a StyleSheet object, where each object contains CSS rules with selectors and objects corresponding CSS grammar. The tree built is called CSSCOM. 
&lt;/li&gt;
&lt;li&gt;On top of DOM and CSSOM, a rendering tree is created, which is a set of objects to be rendered. Each of the rendering objects contains its corresponding DOM object (or a text block) plus the calculated styles. In other words, the render tree describes the visual representation of a DOM. 
&lt;/li&gt;
&lt;li&gt;After the construction of the render tree it goes through a "layout" process. This means giving each node the exact coordinates where it should appear on the screen. 
&lt;/li&gt;
&lt;li&gt;The next stage is painting–the render tree will be traversed and each node will be painted using the UI backend layer. 
&lt;/li&gt;
&lt;li&gt;Repaint: When changing element styles that don't affect the element's position on a page (such as background-color, border-color, visibility), the browser just repaints the element again with the new styles applied (that means a "repaint" or "restyle" is happening). 
&lt;/li&gt;
&lt;li&gt;Reflow: When the changes affect document contents or structure, or element position, a reflow (or relayout) happens. 
&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>html</category>
      <category>css</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Clean Off Your Dirt</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Tue, 29 Dec 2020 16:16:53 +0000</pubDate>
      <link>https://forem.com/shwetabh1/clean-off-your-dirt-2805</link>
      <guid>https://forem.com/shwetabh1/clean-off-your-dirt-2805</guid>
      <description>&lt;p&gt;Here's a short true story.&lt;/p&gt;

&lt;p&gt;In the temple of &lt;a href="https://en.wikipedia.org/wiki/Golden_Buddha_(statue)"&gt;Wat Traimit&lt;/a&gt;, Bangkok, Thailand there's a statue of Buddha, solid gold, 10.5 ft high, weighs around 5.5 tons. They used to think it was made of clay. The monastery used to be somewhere else and in 1957 they had to relocate it because of a highway development through Bangkok.&lt;/p&gt;

&lt;p&gt;When the crane came to lift it, the idol was so heavy that it began to crack so they put it back down, covered it in a tarpaulin so it wouldn't get wet, and decided to try again the next day.&lt;/p&gt;

&lt;p&gt;During the night the abbot came out to look at it, check it wasn't getting wet or damaged. He noticed something gleaming behind the crack and decided to take a closer look. They started to chip the clay away and ended up with a 10.5 ft high solid gold Buddha.&lt;/p&gt;

&lt;p&gt;Turns out that hundreds of years before Thailand (Siam as was) was invaded by Burma and the monks of that time covered the Buddha in clay so it wasn't looted. They were all killed by the Burmese along with many others. No-one who knew the secret was left so the golden reality remained intact but hidden. It was finally rediscovered hundreds of years later.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why tell this story here, now?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Because hidden inside, smothered by the accumulated mental dirt caused by years of disappointments, failures, rejections, regrets is a precious, valuable better you. The &lt;strong&gt;you&lt;/strong&gt; who has creativity, concentration, patience, resolve, purpose, and a million other virtues. All you have to do is clean off the dirt.&lt;/p&gt;

</description>
      <category>motivation</category>
      <category>writing</category>
    </item>
    <item>
      <title>Christmas Tree using Python</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Sun, 27 Dec 2020 14:09:00 +0000</pubDate>
      <link>https://forem.com/shwetabh1/christmas-tree-using-python-4kc4</link>
      <guid>https://forem.com/shwetabh1/christmas-tree-using-python-4kc4</guid>
      <description>&lt;p&gt;Merry Christmas Dev community. Here is a simple Christmas tree using Python.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Christmas Tree in Python
for i in range(10):
    print(''.join(['.'] * (9 - i) + ['^'] * (1 + i * 2) + ['.'] * (9 - i)))
else:
    print(''.join(['-'] * 8 + ['| |'] + ['-'] * 8))

'''
                .........^.........
                ........^^^........
                .......^^^^^.......
                ......^^^^^^^......
                .....^^^^^^^^^.....
                ....^^^^^^^^^^^....
                ...^^^^^^^^^^^^^...
                ..^^^^^^^^^^^^^^^..
                .^^^^^^^^^^^^^^^^^.
                ^^^^^^^^^^^^^^^^^^^
                --------| |--------
          Merry Christmas to all of you. @shwetabh1
'''
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is no use of the else clause but I have used it deliberately, to expose it to devs who are yet not aware of it.&lt;/p&gt;

&lt;p&gt;The else clause executes after the loop completes normally. It is useful in cases when we break from a loop. You can read more about it &lt;a href="https://book.pythontips.com/en/latest/for_-_else.html"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>python</category>
    </item>
    <item>
      <title>seal vs freeze vs preventExtenstions in JS.</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Mon, 07 Dec 2020 17:10:33 +0000</pubDate>
      <link>https://forem.com/shwetabh1/seal-vs-freeze-vs-preventextenstions-in-js-4mad</link>
      <guid>https://forem.com/shwetabh1/seal-vs-freeze-vs-preventextenstions-in-js-4mad</guid>
      <description>&lt;p&gt;&lt;code&gt;Object.seal()&lt;/code&gt;, &lt;code&gt;Object.freeze()&lt;/code&gt; and &lt;code&gt;Object.preventExtensions()&lt;/code&gt; are popular methods in javascript to render an object immutable. But what are the differences between each of them and when should you prefer one over the other?&lt;/p&gt;

&lt;p&gt;Let's try to understand the differences and use cases in detail.&lt;/p&gt;

&lt;h2&gt;
  
  
  Object.preventExtensions()
&lt;/h2&gt;

&lt;p&gt;This method prevents an object from having new properties added to it, but otherwise leave the rest of the object properties alone. &lt;/p&gt;

&lt;p&gt;You are allowed to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Modify existing values of an object.&lt;/li&gt;
&lt;li&gt;Delete existing properties of an object.&lt;/li&gt;
&lt;li&gt;Configure existing properties of an object.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You are not allowed to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add new properties to an object.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let virus = {
    name: 'SARS-CoV-2' 
}

Object.preventExtensions(virus);

/* ❌ Not Allowed ❌ */
// You can't add new properties.
virus.year = 2020;
virus.year; // undefined. In strict mode, it throws a TypeError

/* ☑️ Allowed ☑️ */
// You can still modify existing values.
virus.name = 'Corona Virus' 

// You can still configure existing properties. 
Object.defineProperty( virus, 'name', { 
    writable: false,
    enumerable: false,
    configurable: false
});

// You can still deleting existing properties.
delete virus.name 

// Use Object.isExtensible() to check if an object is extensible.
Object.isExtensible(virus) //false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Object.seal()
&lt;/h2&gt;

&lt;p&gt;It creates a "sealed" object, which means apart from not being extended, you also can not reconfigure or delete any existing properties&lt;/p&gt;

&lt;p&gt;You are allowed to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Modify existing values of an object.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You are not allowed to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add new properties to an object.&lt;/li&gt;
&lt;li&gt;Delete existing properties of an object.&lt;/li&gt;
&lt;li&gt;Configure the existing properties of an object.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let virus = {
    name: 'SARS-CoV-2' 
}
Object.seal(virus);

/* ❌ Not Allowed ❌ */
// You can't add new properties.
virus.year = 2020;
virus.year; // undefined. In strict mode, it throws a TypeError

// You can't reconfigure existing properties.
Object.defineProperty( virus, 'name', { 
    writable: false,
    configurable: false
}); // fails

// You can't deleting existing properties.
delete virus.name // fails

/* ☑️ Allowed ☑️ */
// You can still modify existing properties values.
virus.name = 'Corona Virus'

// Use Object.isSealed() to check if an object is sealed.
Object.isSealed(virus) // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Object.freeze()
&lt;/h2&gt;

&lt;p&gt;It creates a "frozen" object which is the highest level of immutability. A frozen object can no longer be changed. What it essentially means is you can not change the object in any way:&lt;/p&gt;

&lt;p&gt;You are not allowed to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add new properties to an object. &lt;/li&gt;
&lt;li&gt;Delete existing properties of an object.&lt;/li&gt;
&lt;li&gt;Configure the existing properties of an object.&lt;/li&gt;
&lt;li&gt;Modify the existing values of an object.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let virus = {
    name: 'SARS-CoV-2' 
}
Object.freeze(virus);

/* ❌ Not Allowed ❌ */
// You can't add new properties.
virus.year = 2020;
virus.year; // undefined. In strict mode, it throws a TypeError

// You can't configure existing properties. 
Object.defineProperty( virus, 'name', { 
    writable: false,
    enumerbale: false,
    configurable: false
}); // fails

// You can't delete existing properties.
delete virus.name // fails

// You can't modify existing property values.
virus.name = 'Corona Virus' // fails

// Use Object.isFrozen() to check if an object is frozen.
Object.isFrozen(virus) // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;I have created this table which highlights the differences concisely.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fwssueapx8jykyx0rkixk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fwssueapx8jykyx0rkixk.png" alt="difference between seal, freeze and preventExtenstions" width="800" height="289"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Event Loop and Single Thread Mechanism in JavaScript.</title>
      <dc:creator>Shwetabh Shekhar</dc:creator>
      <pubDate>Sun, 06 Dec 2020 06:14:25 +0000</pubDate>
      <link>https://forem.com/shwetabh1/event-loop-and-single-thread-mechanism-in-javascript-2mbg</link>
      <guid>https://forem.com/shwetabh1/event-loop-and-single-thread-mechanism-in-javascript-2mbg</guid>
      <description>&lt;p&gt;&lt;em&gt;"JavaScript is a single-threaded, non-blocking, asynchronous, concurrent language."&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Any Javascript book/tutorial has this line etched in their introduction. On top of that this compact line is perplexing. How exactly is Javascript single-threaded? If so, how does it handle multiple API calls? Isn't Javascript synchronous? Then, how does it perform asynchronous execution? How is Javascript concurrent?&lt;/p&gt;

&lt;p&gt;Here is my attempt to answer all these questions and explain how exactly the single thread mechanism works. Let's first try to understand the technical jargon thrown at us in the introductory line.&lt;/p&gt;

&lt;h3&gt;
  
  
  Single Thread
&lt;/h3&gt;

&lt;p&gt;If a language is single-threaded it signifies, it has only one execution context or thread. What it essentially means is at most one of the blocking functions can execute at a time.&lt;/p&gt;

&lt;h3&gt;
  
  
  Non-Blocking
&lt;/h3&gt;

&lt;p&gt;In a non-blocking language, the execution never stops or blocked.&lt;/p&gt;

&lt;h3&gt;
  
  
  Asynchronous and Synchronous Execution
&lt;/h3&gt;

&lt;p&gt;When you execute something synchronously, you wait for it to finish before moving on to another task. Javascript is actually synchronous but it can be manipulated to behave in an asynchronous way.&lt;/p&gt;

&lt;h3&gt;
  
  
  Concurrent Execution
&lt;/h3&gt;

&lt;p&gt;Concurrency basically signifies the execution of a multitude of tasks over a period of time which JS is very well capable of.&lt;/p&gt;

&lt;h3&gt;
  
  
  How does everything fit together?
&lt;/h3&gt;

&lt;p&gt;Now that we have those technicalities out of our way let's try to understand how everything fits together. Consider the following code snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('before');
setTimeout(()=&amp;gt; {
    console.log('Inside SetTimeout');
},3000)
console.log('after');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mull it over and try to figure out its execution flow. Since Javascript is single-threaded, does it wait 3 seconds at setTimeout() and then move to console.log()? We all know that is not the case. Then how does it work? It all is taken care of by the Javascript engine model depicted below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbj7oa91obxf5q6645tii.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbj7oa91obxf5q6645tii.png" alt="Javascript Event Loop" width="800" height="536"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://blog.sessionstack.com/"&gt;Image credits:&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Memory Heap:&lt;/strong&gt; This is where the memory allocation happens.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Call Stack:&lt;/strong&gt; This is where your stack frames are as your code executes. It records where we are in the program. Each entry into the stack is called a stack frame.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Web API:&lt;/strong&gt; They are not provided by the engine but the Browser (like the DOM, AJAX, setTimeout)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Callback queue:&lt;/strong&gt; Once the Web APIs have executed they are moved to the callback queue.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Event Loop:&lt;/strong&gt; When there is no stack frame it moves the result to the stack.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Code Execution Flow
&lt;/h3&gt;

&lt;p&gt;The above model is what makes Javascript tick. Any blocking task is passed on to the Web APIs for execution. Once it completes it is moved to callback queue in the order their execution was finished. Once the Call Stack is empty the event loop moves the output to call stack. This is how Javascript remains always non-blocking as execution is just moved to Web APIs.&lt;/p&gt;

&lt;p&gt;Here is the line by line execution flow for the above example:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First-line &lt;code&gt;console.log()&lt;/code&gt; goes into the call stack and then executes.&lt;/li&gt;
&lt;li&gt;Execution moves to the second line. It is executed asynchronously. SetTimeout is passed to the web APIs and then once the task is completed it is moved to the Callback Queue.&lt;/li&gt;
&lt;li&gt;While the above process is happening the third line executes.&lt;/li&gt;
&lt;li&gt;The call stack is now empty. The event loop moves th
e setTimeout output from the callback queue to the stack.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The above model is what makes Javascript very powerful. It provides it with excellent concurrency and the ability to handle asynchronous calls.&lt;/p&gt;

&lt;p&gt;PS: &lt;a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ&amp;amp;t=3s"&gt;This video&lt;/a&gt; by Philip Roberts is by far the best resource out there to understand this in more detail.&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
  </channel>
</rss>
